blob: 141c41618d8b9d5d110d08ac18a5ec6bd7448cef [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
John McCall78b81052010-11-10 02:40:36 +000033// Exported for use by Parser.
34SourceRange
35clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
36 unsigned N) {
37 if (!N) return SourceRange();
38 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
39}
40
Douglas Gregor2dd078a2009-09-02 22:59:36 +000041/// \brief Determine whether the declaration found is acceptable as the name
42/// of a template and, if so, return that template declaration. Otherwise,
43/// returns NULL.
John McCallad00b772010-06-16 08:42:20 +000044static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
45 NamedDecl *Orig) {
46 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000047
Douglas Gregor2dd078a2009-09-02 22:59:36 +000048 if (isa<TemplateDecl>(D))
John McCallad00b772010-06-16 08:42:20 +000049 return Orig;
Mike Stump1eb44332009-09-09 15:08:12 +000050
Douglas Gregor2dd078a2009-09-02 22:59:36 +000051 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
52 // C++ [temp.local]p1:
53 // Like normal (non-template) classes, class templates have an
54 // injected-class-name (Clause 9). The injected-class-name
55 // can be used with or without a template-argument-list. When
56 // it is used without a template-argument-list, it is
57 // equivalent to the injected-class-name followed by the
58 // template-parameters of the class template enclosed in
59 // <>. When it is used with a template-argument-list, it
60 // refers to the specified class template specialization,
61 // which could be the current specialization or another
62 // specialization.
63 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000064 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000065 if (Record->getDescribedClassTemplate())
66 return Record->getDescribedClassTemplate();
67
68 if (ClassTemplateSpecializationDecl *Spec
69 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
70 return Spec->getSpecializedTemplate();
71 }
Mike Stump1eb44332009-09-09 15:08:12 +000072
Douglas Gregor2dd078a2009-09-02 22:59:36 +000073 return 0;
74 }
Mike Stump1eb44332009-09-09 15:08:12 +000075
Douglas Gregor2dd078a2009-09-02 22:59:36 +000076 return 0;
77}
78
John McCallf7a1a742009-11-24 19:00:30 +000079static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor01e56ae2010-04-12 20:54:26 +000080 // The set of class templates we've already seen.
81 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCallf7a1a742009-11-24 19:00:30 +000082 LookupResult::Filter filter = R.makeFilter();
83 while (filter.hasNext()) {
84 NamedDecl *Orig = filter.next();
John McCallad00b772010-06-16 08:42:20 +000085 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCallf7a1a742009-11-24 19:00:30 +000086 if (!Repl)
87 filter.erase();
Douglas Gregor01e56ae2010-04-12 20:54:26 +000088 else if (Repl != Orig) {
89
90 // C++ [temp.local]p3:
91 // A lookup that finds an injected-class-name (10.2) can result in an
92 // ambiguity in certain cases (for example, if it is found in more than
93 // one base class). If all of the injected-class-names that are found
94 // refer to specializations of the same class template, and if the name
95 // is followed by a template-argument-list, the reference refers to the
96 // class template itself and not a specialization thereof, and is not
97 // ambiguous.
98 //
99 // FIXME: Will we eventually have to do the same for alias templates?
100 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
101 if (!ClassTemplates.insert(ClassTmpl)) {
102 filter.erase();
103 continue;
104 }
John McCall8ba66912010-08-13 07:02:08 +0000105
106 // FIXME: we promote access to public here as a workaround to
107 // the fact that LookupResult doesn't let us remember that we
108 // found this template through a particular injected class name,
109 // which means we end up doing nasty things to the invariants.
110 // Pretending that access is public is *much* safer.
111 filter.replace(Repl, AS_public);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000112 }
John McCallf7a1a742009-11-24 19:00:30 +0000113 }
114 filter.done();
115}
116
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000117TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000118 CXXScopeSpec &SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000119 bool hasTemplateKeyword,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000120 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +0000121 ParsedType ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000122 bool EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000123 TemplateTy &TemplateResult,
124 bool &MemberOfUnknownSpecialization) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000125 assert(getLangOptions().CPlusPlus && "No template names in C!");
126
Douglas Gregor014e88d2009-11-03 23:16:33 +0000127 DeclarationName TName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000128 MemberOfUnknownSpecialization = false;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000129
130 switch (Name.getKind()) {
131 case UnqualifiedId::IK_Identifier:
132 TName = DeclarationName(Name.Identifier);
133 break;
134
135 case UnqualifiedId::IK_OperatorFunctionId:
136 TName = Context.DeclarationNames.getCXXOperatorName(
137 Name.OperatorFunctionId.Operator);
138 break;
139
Sean Hunte6252d12009-11-28 08:58:14 +0000140 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000141 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
142 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000143
Douglas Gregor014e88d2009-11-03 23:16:33 +0000144 default:
145 return TNK_Non_template;
146 }
Mike Stump1eb44332009-09-09 15:08:12 +0000147
John McCallb3d87482010-08-24 05:47:05 +0000148 QualType ObjectType = ObjectTypePtr.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Douglas Gregorbfea2392009-12-31 08:11:17 +0000150 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
151 LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000152 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
153 MemberOfUnknownSpecialization);
John McCall67d22fb2010-08-28 20:17:00 +0000154 if (R.empty()) return TNK_Non_template;
155 if (R.isAmbiguous()) {
156 // Suppress diagnostics; we'll redo this lookup later.
John McCallb8592062010-08-13 02:23:42 +0000157 R.suppressDiagnostics();
John McCall67d22fb2010-08-28 20:17:00 +0000158
159 // FIXME: we might have ambiguous templates, in which case we
160 // should at least parse them properly!
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000161 return TNK_Non_template;
John McCallb8592062010-08-13 02:23:42 +0000162 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000163
John McCall0bd6feb2009-12-02 08:04:21 +0000164 TemplateName Template;
165 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000166
John McCall0bd6feb2009-12-02 08:04:21 +0000167 unsigned ResultCount = R.end() - R.begin();
168 if (ResultCount > 1) {
169 // We assume that we'll preserve the qualifier from a function
170 // template name in other ways.
171 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
172 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000173
174 // We'll do this lookup again later.
175 R.suppressDiagnostics();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000176 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000177 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
178
179 if (SS.isSet() && !SS.isInvalid()) {
180 NestedNameSpecifier *Qualifier
181 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c153532010-08-06 12:11:11 +0000182 Template = Context.getQualifiedTemplateName(Qualifier,
183 hasTemplateKeyword, TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000184 } else {
185 Template = TemplateName(TD);
186 }
187
John McCallb8592062010-08-13 02:23:42 +0000188 if (isa<FunctionTemplateDecl>(TD)) {
John McCall0bd6feb2009-12-02 08:04:21 +0000189 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000190
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
193 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000194 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
195 TemplateKind = TNK_Type_template;
196 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000197 }
Mike Stump1eb44332009-09-09 15:08:12 +0000198
John McCall0bd6feb2009-12-02 08:04:21 +0000199 TemplateResult = TemplateTy::make(Template);
200 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000201}
202
Douglas Gregor84d0a192010-01-12 21:28:44 +0000203bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
204 SourceLocation IILoc,
205 Scope *S,
206 const CXXScopeSpec *SS,
207 TemplateTy &SuggestedTemplate,
208 TemplateNameKind &SuggestedKind) {
209 // We can't recover unless there's a dependent scope specifier preceding the
210 // template name.
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000211 // FIXME: Typo correction?
Douglas Gregor84d0a192010-01-12 21:28:44 +0000212 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
213 computeDeclContext(*SS))
214 return false;
215
216 // The code is missing a 'template' keyword prior to the dependent template
217 // name.
218 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
219 Diag(IILoc, diag::err_template_kw_missing)
220 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000221 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor84d0a192010-01-12 21:28:44 +0000222 SuggestedTemplate
223 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
224 SuggestedKind = TNK_Dependent_template_name;
225 return true;
226}
227
John McCallf7a1a742009-11-24 19:00:30 +0000228void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000229 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000230 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000231 bool EnteringContext,
232 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000233 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000234 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-11-24 19:00:30 +0000235 DeclContext *LookupCtx = 0;
236 bool isDependent = false;
237 if (!ObjectType.isNull()) {
238 // This nested-name-specifier occurs in a member access expression, e.g.,
239 // x->B::f, and we are looking into the type of the object.
240 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
241 LookupCtx = computeDeclContext(ObjectType);
242 isDependent = ObjectType->isDependentType();
243 assert((isDependent || !ObjectType->isIncompleteType()) &&
244 "Caller should have completed object type");
245 } else if (SS.isSet()) {
246 // This nested-name-specifier occurs after another nested-name-specifier,
247 // so long into the context associated with the prior nested-name-specifier.
248 LookupCtx = computeDeclContext(SS, EnteringContext);
249 isDependent = isDependentScopeSpecifier(SS);
250
251 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000252 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000253 return;
254 }
255
256 bool ObjectTypeSearchedInScope = false;
257 if (LookupCtx) {
258 // Perform "qualified" name lookup into the declaration context we
259 // computed, which is either the type of the base of a member access
260 // expression or the declaration context associated with a prior
261 // nested-name-specifier.
262 LookupQualifiedName(Found, LookupCtx);
263
264 if (!ObjectType.isNull() && Found.empty()) {
265 // C++ [basic.lookup.classref]p1:
266 // In a class member access expression (5.2.5), if the . or -> token is
267 // immediately followed by an identifier followed by a <, the
268 // identifier must be looked up to determine whether the < is the
269 // beginning of a template argument list (14.2) or a less-than operator.
270 // The identifier is first looked up in the class of the object
271 // expression. If the identifier is not found, it is then looked up in
272 // the context of the entire postfix-expression and shall name a class
273 // or function template.
John McCallf7a1a742009-11-24 19:00:30 +0000274 if (S) LookupName(Found, S);
275 ObjectTypeSearchedInScope = true;
276 }
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000277 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000278 // We cannot look into a dependent object type or nested nme
279 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000280 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000281 return;
282 } else {
283 // Perform unqualified name lookup in the current scope.
284 LookupName(Found, S);
285 }
286
Douglas Gregor2e933882010-01-12 17:06:20 +0000287 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000288 // If we did not find any names, attempt to correct any typos.
289 DeclarationName Name = Found.getLookupName();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000290 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000291 false, CTC_CXXCasts)) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000292 FilterAcceptableTemplateNames(Context, Found);
John McCallad00b772010-06-16 08:42:20 +0000293 if (!Found.empty()) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000294 if (LookupCtx)
295 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
296 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000297 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000298 Found.getLookupName().getAsString());
299 else
300 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
301 << Name << Found.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000302 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000303 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000304 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
305 Diag(Template->getLocation(), diag::note_previous_decl)
306 << Template->getDeclName();
John McCallad00b772010-06-16 08:42:20 +0000307 }
Douglas Gregorbfea2392009-12-31 08:11:17 +0000308 } else {
309 Found.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000310 Found.setLookupName(Name);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000311 }
312 }
313
John McCallf7a1a742009-11-24 19:00:30 +0000314 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000315 if (Found.empty()) {
316 if (isDependent)
317 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000318 return;
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000319 }
John McCallf7a1a742009-11-24 19:00:30 +0000320
321 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
322 // C++ [basic.lookup.classref]p1:
323 // [...] If the lookup in the class of the object expression finds a
324 // template, the name is also looked up in the context of the entire
325 // postfix-expression and [...]
326 //
327 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
328 LookupOrdinaryName);
329 LookupName(FoundOuter, S);
330 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000331
John McCallf7a1a742009-11-24 19:00:30 +0000332 if (FoundOuter.empty()) {
333 // - if the name is not found, the name found in the class of the
334 // object expression is used, otherwise
335 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
336 // - if the name is found in the context of the entire
337 // postfix-expression and does not name a class template, the name
338 // found in the class of the object expression is used, otherwise
John McCallad00b772010-06-16 08:42:20 +0000339 } else if (!Found.isSuppressingDiagnostics()) {
John McCallf7a1a742009-11-24 19:00:30 +0000340 // - if the name found is a class template, it must refer to the same
341 // entity as the one found in the class of the object expression,
342 // otherwise the program is ill-formed.
343 if (!Found.isSingleResult() ||
344 Found.getFoundDecl()->getCanonicalDecl()
345 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
346 Diag(Found.getNameLoc(),
Jeffrey Yasskin21d07e42010-06-05 01:39:57 +0000347 diag::ext_nested_name_member_ref_lookup_ambiguous)
348 << Found.getLookupName()
349 << ObjectType;
John McCallf7a1a742009-11-24 19:00:30 +0000350 Diag(Found.getRepresentativeDecl()->getLocation(),
351 diag::note_ambig_member_ref_object_type)
352 << ObjectType;
353 Diag(FoundOuter.getFoundDecl()->getLocation(),
354 diag::note_ambig_member_ref_scope);
355
356 // Recover by taking the template that we found in the object
357 // expression's type.
358 }
359 }
360 }
361}
362
John McCall2f841ba2009-12-02 03:53:29 +0000363/// ActOnDependentIdExpression - Handle a dependent id-expression that
364/// was just parsed. This is only possible with an explicit scope
365/// specifier naming a dependent type.
John McCall60d7b3a2010-08-24 06:29:42 +0000366ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000367Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000368 const DeclarationNameInfo &NameInfo,
John McCall2f841ba2009-12-02 03:53:29 +0000369 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000370 const TemplateArgumentListInfo *TemplateArgs) {
371 NestedNameSpecifier *Qualifier
372 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallea1471e2010-05-20 01:18:31 +0000373
374 DeclContext *DC = getFunctionLevelDeclContext();
John McCallf7a1a742009-11-24 19:00:30 +0000375
John McCall2f841ba2009-12-02 03:53:29 +0000376 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000377 isa<CXXMethodDecl>(DC) &&
378 cast<CXXMethodDecl>(DC)->isInstance()) {
379 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2f841ba2009-12-02 03:53:29 +0000380
John McCallf7a1a742009-11-24 19:00:30 +0000381 // Since the 'this' expression is synthesized, we don't need to
382 // perform the double-lookup check.
383 NamedDecl *FirstQualifierInScope = 0;
384
John McCallaa81e162009-12-01 22:10:20 +0000385 return Owned(CXXDependentScopeMemberExpr::Create(Context,
386 /*This*/ 0, ThisType,
387 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000388 /*Op*/ SourceLocation(),
389 Qualifier, SS.getRange(),
390 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +0000391 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000392 TemplateArgs));
393 }
394
Abramo Bagnara25777432010-08-11 22:01:17 +0000395 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +0000396}
397
John McCall60d7b3a2010-08-24 06:29:42 +0000398ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000399Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000400 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000401 const TemplateArgumentListInfo *TemplateArgs) {
402 return Owned(DependentScopeDeclRefExpr::Create(Context,
403 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
404 SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +0000405 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000406 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000407}
408
Douglas Gregor72c3f312008-12-05 18:15:24 +0000409/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
410/// that the template parameter 'PrevDecl' is being shadowed by a new
411/// declaration at location Loc. Returns true to indicate that this is
412/// an error, and false otherwise.
413bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000414 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000415
416 // Microsoft Visual C++ permits template parameters to be shadowed.
417 if (getLangOptions().Microsoft)
418 return false;
419
420 // C++ [temp.local]p4:
421 // A template-parameter shall not be redeclared within its
422 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000423 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000424 << cast<NamedDecl>(PrevDecl)->getDeclName();
425 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
426 return true;
427}
428
Douglas Gregor2943aed2009-03-03 04:44:36 +0000429/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000430/// the parameter D to reference the templated declaration and return a pointer
431/// to the template declaration. Otherwise, do nothing to D and return null.
John McCalld226f652010-08-21 09:40:31 +0000432TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
433 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
434 D = Temp->getTemplatedDecl();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000435 return Temp;
436 }
437 return 0;
438}
439
Douglas Gregor788cd062009-11-11 01:00:40 +0000440static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
441 const ParsedTemplateArgument &Arg) {
442
443 switch (Arg.getKind()) {
444 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000445 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000446 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
447 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000448 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000449 return TemplateArgumentLoc(TemplateArgument(T), DI);
450 }
451
452 case ParsedTemplateArgument::NonType: {
453 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
454 return TemplateArgumentLoc(TemplateArgument(E), E);
455 }
456
457 case ParsedTemplateArgument::Template: {
John McCall2b5289b2010-08-23 07:28:44 +0000458 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor788cd062009-11-11 01:00:40 +0000459 return TemplateArgumentLoc(TemplateArgument(Template),
460 Arg.getScopeSpec().getRange(),
461 Arg.getLocation());
462 }
463 }
464
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000465 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000466 return TemplateArgumentLoc();
467}
468
469/// \brief Translates template arguments as provided by the parser
470/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000471void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
472 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000473 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000474 TemplateArgs.addArgument(translateTemplateArgument(*this,
475 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000476}
477
Douglas Gregor72c3f312008-12-05 18:15:24 +0000478/// ActOnTypeParameter - Called when a C++ template type parameter
479/// (e.g., "typename T") has been parsed. Typename specifies whether
480/// the keyword "typename" was used to declare the type parameter
481/// (otherwise, "class" was used), and KeyLoc is the location of the
482/// "class" or "typename" keyword. ParamName is the name of the
483/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregorefed5c82010-06-16 15:23:05 +0000484/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000485/// If the type parameter has a default argument, it will be added
486/// later via ActOnTypeParameterDefault.
John McCalld226f652010-08-21 09:40:31 +0000487Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
488 SourceLocation EllipsisLoc,
489 SourceLocation KeyLoc,
490 IdentifierInfo *ParamName,
491 SourceLocation ParamNameLoc,
492 unsigned Depth, unsigned Position,
493 SourceLocation EqualLoc,
John McCallb3d87482010-08-24 05:47:05 +0000494 ParsedType DefaultArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000495 assert(S->isTemplateParamScope() &&
496 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000497 bool Invalid = false;
498
499 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000500 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000501 LookupOrdinaryName,
502 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000503 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000504 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000505 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000506 }
507
Douglas Gregorddc29e12009-02-06 22:42:48 +0000508 SourceLocation Loc = ParamNameLoc;
509 if (!ParamName)
510 Loc = KeyLoc;
511
Douglas Gregor72c3f312008-12-05 18:15:24 +0000512 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000513 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
514 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000515 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000516 if (Invalid)
517 Param->setInvalidDecl();
518
519 if (ParamName) {
520 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000521 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000522 IdResolver.AddDecl(Param);
523 }
524
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000525 // Handle the default argument, if provided.
526 if (DefaultArg) {
527 TypeSourceInfo *DefaultTInfo;
528 GetTypeFromParser(DefaultArg, &DefaultTInfo);
529
530 assert(DefaultTInfo && "expected source information for type");
531
532 // C++0x [temp.param]p9:
533 // A default template-argument may be specified for any kind of
534 // template-parameter that is not a template parameter pack.
535 if (Ellipsis) {
536 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
John McCalld226f652010-08-21 09:40:31 +0000537 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000538 }
539
540 // Check the template argument itself.
541 if (CheckTemplateArgument(Param, DefaultTInfo)) {
542 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000543 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000544 }
545
546 Param->setDefaultArgument(DefaultTInfo, false);
547 }
548
John McCalld226f652010-08-21 09:40:31 +0000549 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000550}
551
Douglas Gregor2943aed2009-03-03 04:44:36 +0000552/// \brief Check that the type of a non-type template parameter is
553/// well-formed.
554///
555/// \returns the (possibly-promoted) parameter type if valid;
556/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000557QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000558Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000559 // We don't allow variably-modified types as the type of non-type template
560 // parameters.
561 if (T->isVariablyModifiedType()) {
562 Diag(Loc, diag::err_variably_modified_nontype_template_param)
563 << T;
564 return QualType();
565 }
566
Douglas Gregor2943aed2009-03-03 04:44:36 +0000567 // C++ [temp.param]p4:
568 //
569 // A non-type template-parameter shall have one of the following
570 // (optionally cv-qualified) types:
571 //
572 // -- integral or enumeration type,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000573 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000574 // -- pointer to object or pointer to function,
Eli Friedman13578692010-08-05 02:49:48 +0000575 T->isPointerType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000576 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000577 T->isReferenceType() ||
578 // -- pointer to member.
579 T->isMemberPointerType() ||
580 // If T is a dependent type, we can't do the check now, so we
581 // assume that it is well-formed.
582 T->isDependentType())
583 return T;
584 // C++ [temp.param]p8:
585 //
586 // A non-type template-parameter of type "array of T" or
587 // "function returning T" is adjusted to be of type "pointer to
588 // T" or "pointer to function returning T", respectively.
589 else if (T->isArrayType())
590 // FIXME: Keep the type prior to promotion?
591 return Context.getArrayDecayedType(T);
592 else if (T->isFunctionType())
593 // FIXME: Keep the type prior to promotion?
594 return Context.getPointerType(T);
Douglas Gregor0fddb972010-05-22 16:17:30 +0000595
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596 Diag(Loc, diag::err_template_nontype_parm_bad_type)
597 << T;
598
599 return QualType();
600}
601
John McCalld226f652010-08-21 09:40:31 +0000602Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
603 unsigned Depth,
604 unsigned Position,
605 SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000606 Expr *Default) {
John McCallbf1a0282010-06-04 23:28:52 +0000607 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
608 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000609
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000610 assert(S->isTemplateParamScope() &&
611 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000612 bool Invalid = false;
613
614 IdentifierInfo *ParamName = D.getIdentifier();
615 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000616 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000617 LookupOrdinaryName,
618 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000619 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000620 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000621 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000622 }
623
Douglas Gregor2943aed2009-03-03 04:44:36 +0000624 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000625 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000626 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000627 Invalid = true;
628 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000629
Douglas Gregor72c3f312008-12-05 18:15:24 +0000630 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000631 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
632 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000633 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000634 if (Invalid)
635 Param->setInvalidDecl();
636
637 if (D.getIdentifier()) {
638 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000639 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000640 IdResolver.AddDecl(Param);
641 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000642
643 // Check the well-formedness of the default template argument, if provided.
John McCall9ae2f072010-08-23 23:25:46 +0000644 if (Default) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000645 TemplateArgument Converted;
646 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
647 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000648 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000649 }
650
John McCall9ae2f072010-08-23 23:25:46 +0000651 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000652 }
653
John McCalld226f652010-08-21 09:40:31 +0000654 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000655}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000656
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000657/// ActOnTemplateTemplateParameter - Called when a C++ template template
658/// parameter (e.g. T in template <template <typename> class T> class array)
659/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000660Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
661 SourceLocation TmpLoc,
662 TemplateParamsTy *Params,
663 IdentifierInfo *Name,
664 SourceLocation NameLoc,
665 unsigned Depth,
666 unsigned Position,
667 SourceLocation EqualLoc,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000668 const ParsedTemplateArgument &Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000669 assert(S->isTemplateParamScope() &&
670 "Template template parameter not in template parameter scope!");
671
672 // Construct the parameter object.
673 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000674 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000675 NameLoc.isInvalid()? TmpLoc : NameLoc,
676 Depth, Position, Name,
Douglas Gregor369ea272010-10-21 17:26:49 +0000677 Params);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000678
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000679 // If the template template parameter has a name, then link the identifier
680 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000681 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000682 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000683 IdResolver.AddDecl(Param);
684 }
685
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000686 if (!Default.isInvalid()) {
687 // Check only that we have a template template argument. We don't want to
688 // try to check well-formedness now, because our template template parameter
689 // might have dependent types in its template parameters, which we wouldn't
690 // be able to match now.
691 //
692 // If none of the template template parameter's template arguments mention
693 // other template parameters, we could actually perform more checking here.
694 // However, it isn't worth doing.
695 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
696 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
697 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
698 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000699 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000700 }
701
702 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000703 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000704
Douglas Gregor369ea272010-10-21 17:26:49 +0000705 if (Params->size() == 0) {
706 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
707 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
708 Param->setInvalidDecl();
709 }
John McCalld226f652010-08-21 09:40:31 +0000710 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000711}
712
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000713/// ActOnTemplateParameterList - Builds a TemplateParameterList that
714/// contains the template parameters in Params/NumParams.
715Sema::TemplateParamsTy *
716Sema::ActOnTemplateParameterList(unsigned Depth,
717 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000718 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000719 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000720 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000721 SourceLocation RAngleLoc) {
722 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000723 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000724
Douglas Gregorddc29e12009-02-06 22:42:48 +0000725 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000726 (NamedDecl**)Params, NumParams,
727 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000728}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000729
John McCallb6217662010-03-15 10:12:16 +0000730static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
731 if (SS.isSet())
732 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
733 SS.getRange());
734}
735
John McCallf312b1e2010-08-26 23:41:50 +0000736DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000737Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000738 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000739 IdentifierInfo *Name, SourceLocation NameLoc,
740 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000741 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000742 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000743 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000744 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000745 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000746 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000747
748 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000749 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000750 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000751
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000752 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
753 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000754
755 // There is no such thing as an unnamed class template.
756 if (!Name) {
757 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000758 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000759 }
760
761 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000762 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000763 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000764 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000765 if (SS.isNotEmpty() && !SS.isInvalid()) {
766 SemanticContext = computeDeclContext(SS, true);
767 if (!SemanticContext) {
768 // FIXME: Produce a reasonable diagnostic here
769 return true;
770 }
Mike Stump1eb44332009-09-09 15:08:12 +0000771
John McCall77bb1aa2010-05-01 00:40:08 +0000772 if (RequireCompleteDeclContext(SS, SemanticContext))
773 return true;
774
John McCalla24dc2e2009-11-17 02:14:36 +0000775 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000776 } else {
777 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000778 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000779 }
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Douglas Gregor57265e32010-04-12 16:00:01 +0000781 if (Previous.isAmbiguous())
782 return true;
783
Douglas Gregorddc29e12009-02-06 22:42:48 +0000784 NamedDecl *PrevDecl = 0;
785 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000786 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000787
Douglas Gregorddc29e12009-02-06 22:42:48 +0000788 // If there is a previous declaration with the same name, check
789 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000790 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000791 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000792
793 // We may have found the injected-class-name of a class template,
794 // class template partial specialization, or class template specialization.
795 // In these cases, grab the template that is being defined or specialized.
796 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
797 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
798 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
799 PrevClassTemplate
800 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
801 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
802 PrevClassTemplate
803 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
804 ->getSpecializedTemplate();
805 }
806 }
807
John McCall65c49462009-12-18 11:25:59 +0000808 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000809 // C++ [namespace.memdef]p3:
810 // [...] When looking for a prior declaration of a class or a function
811 // declared as a friend, and when the name of the friend class or
812 // function is neither a qualified name nor a template-id, scopes outside
813 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000814 if (!SS.isSet()) {
815 DeclContext *OutermostContext = CurContext;
816 while (!OutermostContext->isFileContext())
817 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000818
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000819 if (PrevDecl &&
820 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
821 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
822 SemanticContext = PrevDecl->getDeclContext();
823 } else {
824 // Declarations in outer scopes don't matter. However, the outermost
825 // context we computed is the semantic context for our new
826 // declaration.
827 PrevDecl = PrevClassTemplate = 0;
828 SemanticContext = OutermostContext;
829 }
John McCalle129d442009-12-17 23:21:11 +0000830 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000831
John McCalle129d442009-12-17 23:21:11 +0000832 if (CurContext->isDependentContext()) {
833 // If this is a dependent context, we don't want to link the friend
834 // class template to the template in scope, because that would perform
835 // checking of the template parameter lists that can't be performed
836 // until the outer context is instantiated.
837 PrevDecl = PrevClassTemplate = 0;
838 }
839 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
840 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000841
Douglas Gregorddc29e12009-02-06 22:42:48 +0000842 if (PrevClassTemplate) {
843 // Ensure that the template parameter lists are compatible.
844 if (!TemplateParameterListsAreEqual(TemplateParams,
845 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000846 /*Complain=*/true,
847 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000848 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000849
850 // C++ [temp.class]p4:
851 // In a redeclaration, partial specialization, explicit
852 // specialization or explicit instantiation of a class template,
853 // the class-key shall agree in kind with the original class
854 // template declaration (7.1.5.3).
855 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000856 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000857 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000858 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000859 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000860 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000861 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000862 }
863
Douglas Gregorddc29e12009-02-06 22:42:48 +0000864 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000865 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000866 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000867 Diag(NameLoc, diag::err_redefinition) << Name;
868 Diag(Def->getLocation(), diag::note_previous_definition);
869 // FIXME: Would it make sense to try to "forget" the previous
870 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000871 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000872 }
873 }
874 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
875 // Maybe we will complain about the shadowed template parameter.
876 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
877 // Just pretend that we didn't see the previous declaration.
878 PrevDecl = 0;
879 } else if (PrevDecl) {
880 // C++ [temp]p5:
881 // A class template shall not have the same name as any other
882 // template, class, function, object, enumeration, enumerator,
883 // namespace, or type in the same scope (3.3), except as specified
884 // in (14.5.4).
885 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
886 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000887 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000888 }
889
Douglas Gregord684b002009-02-10 19:49:53 +0000890 // Check the template parameter list of this declaration, possibly
891 // merging in the template parameter list from the previous class
892 // template declaration.
893 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000894 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
895 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000896 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Douglas Gregor57265e32010-04-12 16:00:01 +0000898 if (SS.isSet()) {
899 // If the name of the template was qualified, we must be defining the
900 // template out-of-line.
901 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
902 !(TUK == TUK_Friend && CurContext->isDependentContext()))
903 Diag(NameLoc, diag::err_member_def_does_not_match)
904 << Name << SemanticContext << SS.getRange();
905 }
906
Mike Stump1eb44332009-09-09 15:08:12 +0000907 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000908 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000909 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000910 PrevClassTemplate->getTemplatedDecl() : 0,
911 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000912 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000913
914 ClassTemplateDecl *NewTemplate
915 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
916 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000917 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000918 NewClass->setDescribedClassTemplate(NewTemplate);
919
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000920 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +0000921 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +0000922 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000923 assert(T->isDependentType() && "Class template type is not dependent?");
924 (void)T;
925
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000926 // If we are providing an explicit specialization of a member that is a
927 // class template, make a note of that.
928 if (PrevClassTemplate &&
929 PrevClassTemplate->getInstantiatedFromMemberTemplate())
930 PrevClassTemplate->setMemberSpecialization();
931
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000932 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000933 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000934 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Douglas Gregorddc29e12009-02-06 22:42:48 +0000936 // Set the lexical context of these templates
937 NewClass->setLexicalDeclContext(CurContext);
938 NewTemplate->setLexicalDeclContext(CurContext);
939
John McCall0f434ec2009-07-31 02:45:11 +0000940 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000941 NewClass->startDefinition();
942
943 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000944 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000945
John McCall05b23ea2009-09-14 21:59:20 +0000946 if (TUK != TUK_Friend)
947 PushOnScopeChains(NewTemplate, S);
948 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000949 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000950 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000951 NewClass->setAccess(PrevClassTemplate->getAccess());
952 }
John McCall05b23ea2009-09-14 21:59:20 +0000953
Douglas Gregord85bea22009-09-26 06:47:28 +0000954 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
955 PrevClassTemplate != NULL);
956
John McCall05b23ea2009-09-14 21:59:20 +0000957 // Friend templates are visible in fairly strange ways.
958 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +0000959 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall05b23ea2009-09-14 21:59:20 +0000960 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
961 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
962 PushOnScopeChains(NewTemplate, EnclosingScope,
963 /* AddToContext = */ false);
964 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000965
966 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
967 NewClass->getLocation(),
968 NewTemplate,
969 /*FIXME:*/NewClass->getLocation());
970 Friend->setAccess(AS_public);
971 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000972 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000973
Douglas Gregord684b002009-02-10 19:49:53 +0000974 if (Invalid) {
975 NewTemplate->setInvalidDecl();
976 NewClass->setInvalidDecl();
977 }
John McCalld226f652010-08-21 09:40:31 +0000978 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000979}
980
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000981/// \brief Diagnose the presence of a default template argument on a
982/// template parameter, which is ill-formed in certain contexts.
983///
984/// \returns true if the default template argument should be dropped.
985static bool DiagnoseDefaultTemplateArgument(Sema &S,
986 Sema::TemplateParamListContext TPC,
987 SourceLocation ParamLoc,
988 SourceRange DefArgRange) {
989 switch (TPC) {
990 case Sema::TPC_ClassTemplate:
991 return false;
992
993 case Sema::TPC_FunctionTemplate:
994 // C++ [temp.param]p9:
995 // A default template-argument shall not be specified in a
996 // function template declaration or a function template
997 // definition [...]
998 // (This sentence is not in C++0x, per DR226).
999 if (!S.getLangOptions().CPlusPlus0x)
1000 S.Diag(ParamLoc,
1001 diag::err_template_parameter_default_in_function_template)
1002 << DefArgRange;
1003 return false;
1004
1005 case Sema::TPC_ClassTemplateMember:
1006 // C++0x [temp.param]p9:
1007 // A default template-argument shall not be specified in the
1008 // template-parameter-lists of the definition of a member of a
1009 // class template that appears outside of the member's class.
1010 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1011 << DefArgRange;
1012 return true;
1013
1014 case Sema::TPC_FriendFunctionTemplate:
1015 // C++ [temp.param]p9:
1016 // A default template-argument shall not be specified in a
1017 // friend template declaration.
1018 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1019 << DefArgRange;
1020 return true;
1021
1022 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1023 // for friend function templates if there is only a single
1024 // declaration (and it is a definition). Strange!
1025 }
1026
1027 return false;
1028}
1029
Douglas Gregord684b002009-02-10 19:49:53 +00001030/// \brief Checks the validity of a template parameter list, possibly
1031/// considering the template parameter list from a previous
1032/// declaration.
1033///
1034/// If an "old" template parameter list is provided, it must be
1035/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1036/// template parameter list.
1037///
1038/// \param NewParams Template parameter list for a new template
1039/// declaration. This template parameter list will be updated with any
1040/// default arguments that are carried through from the previous
1041/// template parameter list.
1042///
1043/// \param OldParams If provided, template parameter list from a
1044/// previous declaration of the same template. Default template
1045/// arguments will be merged from the old template parameter list to
1046/// the new template parameter list.
1047///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001048/// \param TPC Describes the context in which we are checking the given
1049/// template parameter list.
1050///
Douglas Gregord684b002009-02-10 19:49:53 +00001051/// \returns true if an error occurred, false otherwise.
1052bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001053 TemplateParameterList *OldParams,
1054 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001055 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Douglas Gregord684b002009-02-10 19:49:53 +00001057 // C++ [temp.param]p10:
1058 // The set of default template-arguments available for use with a
1059 // template declaration or definition is obtained by merging the
1060 // default arguments from the definition (if in scope) and all
1061 // declarations in scope in the same way default function
1062 // arguments are (8.3.6).
1063 bool SawDefaultArgument = false;
1064 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001065
Anders Carlsson49d25572009-06-12 23:20:15 +00001066 bool SawParameterPack = false;
1067 SourceLocation ParameterPackLoc;
1068
Mike Stump1a35fde2009-02-11 23:03:27 +00001069 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001070 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001071 if (OldParams)
1072 OldParam = OldParams->begin();
1073
1074 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1075 NewParamEnd = NewParams->end();
1076 NewParam != NewParamEnd; ++NewParam) {
1077 // Variables used to diagnose redundant default arguments
1078 bool RedundantDefaultArg = false;
1079 SourceLocation OldDefaultLoc;
1080 SourceLocation NewDefaultLoc;
1081
1082 // Variables used to diagnose missing default arguments
1083 bool MissingDefaultArg = false;
1084
Anders Carlsson49d25572009-06-12 23:20:15 +00001085 // C++0x [temp.param]p11:
1086 // If a template parameter of a class template is a template parameter pack,
1087 // it must be the last template parameter.
1088 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001089 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001090 diag::err_template_param_pack_must_be_last_template_parameter);
1091 Invalid = true;
1092 }
1093
Douglas Gregord684b002009-02-10 19:49:53 +00001094 if (TemplateTypeParmDecl *NewTypeParm
1095 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001096 // Check the presence of a default argument here.
1097 if (NewTypeParm->hasDefaultArgument() &&
1098 DiagnoseDefaultTemplateArgument(*this, TPC,
1099 NewTypeParm->getLocation(),
1100 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001101 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001102 NewTypeParm->removeDefaultArgument();
1103
1104 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001105 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001106 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Anders Carlsson49d25572009-06-12 23:20:15 +00001108 if (NewTypeParm->isParameterPack()) {
1109 assert(!NewTypeParm->hasDefaultArgument() &&
1110 "Parameter packs can't have a default argument!");
1111 SawParameterPack = true;
1112 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001113 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001114 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001115 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1116 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1117 SawDefaultArgument = true;
1118 RedundantDefaultArg = true;
1119 PreviousDefaultArgLoc = NewDefaultLoc;
1120 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1121 // Merge the default argument from the old declaration to the
1122 // new declaration.
1123 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001124 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001125 true);
1126 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1127 } else if (NewTypeParm->hasDefaultArgument()) {
1128 SawDefaultArgument = true;
1129 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1130 } else if (SawDefaultArgument)
1131 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001132 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001133 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001134 // Check the presence of a default argument here.
1135 if (NewNonTypeParm->hasDefaultArgument() &&
1136 DiagnoseDefaultTemplateArgument(*this, TPC,
1137 NewNonTypeParm->getLocation(),
1138 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001139 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001140 }
1141
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001142 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001143 NonTypeTemplateParmDecl *OldNonTypeParm
1144 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001145 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001146 NewNonTypeParm->hasDefaultArgument()) {
1147 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1148 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1149 SawDefaultArgument = true;
1150 RedundantDefaultArg = true;
1151 PreviousDefaultArgLoc = NewDefaultLoc;
1152 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1153 // Merge the default argument from the old declaration to the
1154 // new declaration.
1155 SawDefaultArgument = true;
1156 // FIXME: We need to create a new kind of "default argument"
1157 // expression that points to a previous template template
1158 // parameter.
1159 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001160 OldNonTypeParm->getDefaultArgument(),
1161 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001162 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1163 } else if (NewNonTypeParm->hasDefaultArgument()) {
1164 SawDefaultArgument = true;
1165 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1166 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001167 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001168 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001169 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001170 TemplateTemplateParmDecl *NewTemplateParm
1171 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001172 if (NewTemplateParm->hasDefaultArgument() &&
1173 DiagnoseDefaultTemplateArgument(*this, TPC,
1174 NewTemplateParm->getLocation(),
1175 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001176 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001177
1178 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001179 TemplateTemplateParmDecl *OldTemplateParm
1180 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001181 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001182 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001183 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1184 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001185 SawDefaultArgument = true;
1186 RedundantDefaultArg = true;
1187 PreviousDefaultArgLoc = NewDefaultLoc;
1188 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1189 // Merge the default argument from the old declaration to the
1190 // new declaration.
1191 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001192 // FIXME: We need to create a new kind of "default argument" expression
1193 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001194 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001195 OldTemplateParm->getDefaultArgument(),
1196 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001197 PreviousDefaultArgLoc
1198 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001199 } else if (NewTemplateParm->hasDefaultArgument()) {
1200 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001201 PreviousDefaultArgLoc
1202 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001203 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001204 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001205 }
1206
1207 if (RedundantDefaultArg) {
1208 // C++ [temp.param]p12:
1209 // A template-parameter shall not be given default arguments
1210 // by two different declarations in the same scope.
1211 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1212 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1213 Invalid = true;
1214 } else if (MissingDefaultArg) {
1215 // C++ [temp.param]p11:
1216 // If a template-parameter has a default template-argument,
1217 // all subsequent template-parameters shall have a default
1218 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001219 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001220 diag::err_template_param_default_arg_missing);
1221 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1222 Invalid = true;
1223 }
1224
1225 // If we have an old template parameter list that we're merging
1226 // in, move on to the next parameter.
1227 if (OldParams)
1228 ++OldParam;
1229 }
1230
1231 return Invalid;
1232}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001233
John McCall4e2cbb22010-10-20 05:44:58 +00001234namespace {
1235
1236/// A class which looks for a use of a certain level of template
1237/// parameter.
1238struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1239 typedef RecursiveASTVisitor<DependencyChecker> super;
1240
1241 unsigned Depth;
1242 bool Match;
1243
1244 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1245 NamedDecl *ND = Params->getParam(0);
1246 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1247 Depth = PD->getDepth();
1248 } else if (NonTypeTemplateParmDecl *PD =
1249 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1250 Depth = PD->getDepth();
1251 } else {
1252 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1253 }
1254 }
1255
1256 bool Matches(unsigned ParmDepth) {
1257 if (ParmDepth >= Depth) {
1258 Match = true;
1259 return true;
1260 }
1261 return false;
1262 }
1263
1264 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1265 return !Matches(T->getDepth());
1266 }
1267
1268 bool TraverseTemplateName(TemplateName N) {
1269 if (TemplateTemplateParmDecl *PD =
1270 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1271 if (Matches(PD->getDepth())) return false;
1272 return super::TraverseTemplateName(N);
1273 }
1274
1275 bool VisitDeclRefExpr(DeclRefExpr *E) {
1276 if (NonTypeTemplateParmDecl *PD =
1277 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1278 if (PD->getDepth() == Depth) {
1279 Match = true;
1280 return false;
1281 }
1282 }
1283 return super::VisitDeclRefExpr(E);
1284 }
1285};
1286}
1287
1288/// Determines whether a template-id depends on the given parameter
1289/// list.
1290static bool
1291DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId,
1292 TemplateParameterList *Params) {
1293 DependencyChecker Checker(Params);
1294 Checker.TraverseType(QualType(TemplateId, 0));
1295 return Checker.Match;
1296}
1297
Mike Stump1eb44332009-09-09 15:08:12 +00001298/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001299/// specifier, returning the template parameter list that applies to the
1300/// name.
1301///
1302/// \param DeclStartLoc the start of the declaration that has a scope
1303/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001304///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001305/// \param SS the scope specifier that will be matched to the given template
1306/// parameter lists. This scope specifier precedes a qualified name that is
1307/// being declared.
1308///
1309/// \param ParamLists the template parameter lists, from the outermost to the
1310/// innermost template parameter lists.
1311///
1312/// \param NumParamLists the number of template parameter lists in ParamLists.
1313///
John McCall77e8b112010-04-13 20:37:33 +00001314/// \param IsFriend Whether to apply the slightly different rules for
1315/// matching template parameters to scope specifiers in friend
1316/// declarations.
1317///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001318/// \param IsExplicitSpecialization will be set true if the entity being
1319/// declared is an explicit specialization, false otherwise.
1320///
Mike Stump1eb44332009-09-09 15:08:12 +00001321/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001322/// name that is preceded by the scope specifier @p SS. This template
1323/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001324/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001325/// template specialization), or may be NULL (if we were's declaring isn't
1326/// itself a template).
1327TemplateParameterList *
1328Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1329 const CXXScopeSpec &SS,
1330 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001331 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001332 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001333 bool &IsExplicitSpecialization,
1334 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001335 IsExplicitSpecialization = false;
1336
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001337 // Find the template-ids that occur within the nested-name-specifier. These
1338 // template-ids will match up with the template parameter lists.
1339 llvm::SmallVector<const TemplateSpecializationType *, 4>
1340 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001341 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1342 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001343 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1344 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001345 const Type *T = NNS->getAsType();
1346 if (!T) break;
1347
1348 // C++0x [temp.expl.spec]p17:
1349 // A member or a member template may be nested within many
1350 // enclosing class templates. In an explicit specialization for
1351 // such a member, the member declaration shall be preceded by a
1352 // template<> for each enclosing class template that is
1353 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001354 //
1355 // Following the existing practice of GNU and EDG, we allow a typedef of a
1356 // template specialization type.
John McCall49f4e1c2010-12-10 11:01:00 +00001357 while (const TypedefType *TT = dyn_cast<TypedefType>(T))
1358 T = TT->getDecl()->getUnderlyingType().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001359
Mike Stump1eb44332009-09-09 15:08:12 +00001360 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001361 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001362 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1363 if (!Template)
1364 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Ted Kremenek6217b802009-07-29 21:53:49 +00001366 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001367 ClassTemplateSpecializationDecl *SpecDecl
1368 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1369 // If the nested name specifier refers to an explicit specialization,
1370 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001371 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1372 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001373 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001374 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001375 }
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001377 TemplateIdsInSpecifier.push_back(SpecType);
1378 }
1379 }
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001381 // Reverse the list of template-ids in the scope specifier, so that we can
1382 // more easily match up the template-ids and the template parameter lists.
1383 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001385 SourceLocation FirstTemplateLoc = DeclStartLoc;
1386 if (NumParamLists)
1387 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001389 // Match the template-ids found in the specifier to the template parameter
1390 // lists.
John McCall4e2cbb22010-10-20 05:44:58 +00001391 unsigned ParamIdx = 0, TemplateIdx = 0;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001392 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
John McCall4e2cbb22010-10-20 05:44:58 +00001393 TemplateIdx != NumTemplateIds; ++TemplateIdx) {
1394 const TemplateSpecializationType *TemplateId
1395 = TemplateIdsInSpecifier[TemplateIdx];
Douglas Gregorb88e8882009-07-30 17:40:51 +00001396 bool DependentTemplateId = TemplateId->isDependentType();
John McCall4e2cbb22010-10-20 05:44:58 +00001397
1398 // In friend declarations we can have template-ids which don't
1399 // depend on the corresponding template parameter lists. But
1400 // assume that empty parameter lists are supposed to match this
1401 // template-id.
1402 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) {
1403 if (!DependentTemplateId ||
1404 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx]))
1405 continue;
1406 }
1407
1408 if (ParamIdx >= NumParamLists) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001409 // We have a template-id without a corresponding template parameter
1410 // list.
John McCall77e8b112010-04-13 20:37:33 +00001411
1412 // ...which is fine if this is a friend declaration.
1413 if (IsFriend) {
1414 IsExplicitSpecialization = true;
1415 break;
1416 }
1417
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001418 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001419 // FIXME: the location information here isn't great.
1420 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001421 diag::err_template_spec_needs_template_parameters)
John McCall4e2cbb22010-10-20 05:44:58 +00001422 << QualType(TemplateId, 0)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001423 << SS.getRange();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001424 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001425 } else {
1426 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1427 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001428 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001429 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001430 }
1431 return 0;
1432 }
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001434 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001435 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001436 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001437
John McCall31f17ec2010-04-27 00:57:59 +00001438 // Are there cases in (e.g.) friends where this won't match?
1439 if (const InjectedClassNameType *Injected
1440 = TemplateId->getAs<InjectedClassNameType>()) {
1441 CXXRecordDecl *Record = Injected->getDecl();
1442 if (ClassTemplatePartialSpecializationDecl *Partial =
1443 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1444 ExpectedTemplateParams = Partial->getTemplateParameters();
1445 else
1446 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1447 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001448 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001449
John McCall31f17ec2010-04-27 00:57:59 +00001450 if (ExpectedTemplateParams)
John McCall4e2cbb22010-10-20 05:44:58 +00001451 TemplateParameterListsAreEqual(ParamLists[ParamIdx],
John McCall31f17ec2010-04-27 00:57:59 +00001452 ExpectedTemplateParams,
1453 true, TPL_TemplateMatch);
1454
John McCall4e2cbb22010-10-20 05:44:58 +00001455 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1456 TPC_ClassTemplateMember);
1457 } else if (ParamLists[ParamIdx]->size() > 0)
1458 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001459 diag::err_template_param_list_matches_nontemplate)
1460 << TemplateId
John McCall4e2cbb22010-10-20 05:44:58 +00001461 << ParamLists[ParamIdx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001462 else
1463 IsExplicitSpecialization = true;
John McCall4e2cbb22010-10-20 05:44:58 +00001464
1465 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001466 }
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001468 // If there were at least as many template-ids as there were template
1469 // parameter lists, then there are no template parameter lists remaining for
1470 // the declaration itself.
John McCall4e2cbb22010-10-20 05:44:58 +00001471 if (ParamIdx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001472 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001474 // If there were too many template parameter lists, complain about that now.
John McCall4e2cbb22010-10-20 05:44:58 +00001475 if (ParamIdx != NumParamLists - 1) {
1476 while (ParamIdx < NumParamLists - 1) {
1477 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0;
1478 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001479 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1480 : diag::err_template_spec_extra_headers)
John McCall4e2cbb22010-10-20 05:44:58 +00001481 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1482 ParamLists[ParamIdx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001483
1484 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1485 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1486 diag::note_explicit_template_spec_does_not_need_header)
1487 << ExplicitSpecializationsInSpecifier.back();
1488 ExplicitSpecializationsInSpecifier.pop_back();
1489 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001490
1491 // We have a template parameter list with no corresponding scope, which
1492 // means that the resulting template declaration can't be instantiated
1493 // properly (we'll end up with dependent nodes when we shouldn't).
1494 if (!isExplicitSpecHeader)
1495 Invalid = true;
1496
John McCall4e2cbb22010-10-20 05:44:58 +00001497 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001498 }
1499 }
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001501 // Return the last template parameter list, which corresponds to the
1502 // entity being declared.
1503 return ParamLists[NumParamLists - 1];
1504}
1505
Douglas Gregor7532dc62009-03-30 22:58:21 +00001506QualType Sema::CheckTemplateIdType(TemplateName Name,
1507 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001508 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001509 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001510 if (!Template) {
1511 // The template name does not resolve to a template, so we just
1512 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001513 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001514 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001515
Douglas Gregor40808ce2009-03-09 23:48:35 +00001516 // Check that the template argument list is well-formed for this
1517 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001518 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00001519 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001520 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001521 return QualType();
1522
Douglas Gregor910f8002010-11-07 23:05:16 +00001523 assert((Converted.size() == Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001524 "Converted template argument list is too short!");
1525
1526 QualType CanonType;
1527
Douglas Gregorcaddba02009-11-12 18:38:13 +00001528 if (Name.isDependent() ||
1529 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001530 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001531 // This class template specialization is a dependent
1532 // type. Therefore, its canonical type is another class template
1533 // specialization type that contains all of the converted
1534 // arguments in canonical form. This ensures that, e.g., A<T> and
1535 // A<T, T> have identical types when A is declared as:
1536 //
1537 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001538 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001539 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor910f8002010-11-07 23:05:16 +00001540 Converted.data(),
1541 Converted.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Douglas Gregor1275ae02009-07-28 23:00:59 +00001543 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001544 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001545 // In the future, we need to teach getTemplateSpecializationType to only
1546 // build the canonical type and return that to us.
1547 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001548
1549 // This might work out to be a current instantiation, in which
1550 // case the canonical type needs to be the InjectedClassNameType.
1551 //
1552 // TODO: in theory this could be a simple hashtable lookup; most
1553 // changes to CurContext don't change the set of current
1554 // instantiations.
1555 if (isa<ClassTemplateDecl>(Template)) {
1556 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1557 // If we get out to a namespace, we're done.
1558 if (Ctx->isFileContext()) break;
1559
1560 // If this isn't a record, keep looking.
1561 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1562 if (!Record) continue;
1563
1564 // Look for one of the two cases with InjectedClassNameTypes
1565 // and check whether it's the same template.
1566 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1567 !Record->getDescribedClassTemplate())
1568 continue;
1569
1570 // Fetch the injected class name type and check whether its
1571 // injected type is equal to the type we just built.
1572 QualType ICNT = Context.getTypeDeclType(Record);
1573 QualType Injected = cast<InjectedClassNameType>(ICNT)
1574 ->getInjectedSpecializationType();
1575
1576 if (CanonType != Injected->getCanonicalTypeInternal())
1577 continue;
1578
1579 // If so, the canonical type of this TST is the injected
1580 // class name type of the record we just found.
1581 assert(ICNT.isCanonical());
1582 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00001583 break;
1584 }
1585 }
Mike Stump1eb44332009-09-09 15:08:12 +00001586 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001587 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001588 // Find the class template specialization declaration that
1589 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001590 void *InsertPos = 0;
1591 ClassTemplateSpecializationDecl *Decl
Douglas Gregor910f8002010-11-07 23:05:16 +00001592 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
1593 InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001594 if (!Decl) {
1595 // This is the first time we have referenced this class template
1596 // specialization. Create the canonical declaration and add it to
1597 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001598 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001599 ClassTemplate->getTemplatedDecl()->getTagKind(),
1600 ClassTemplate->getDeclContext(),
1601 ClassTemplate->getLocation(),
Douglas Gregor910f8002010-11-07 23:05:16 +00001602 ClassTemplate,
1603 Converted.data(),
1604 Converted.size(), 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001605 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001606 Decl->setLexicalDeclContext(CurContext);
1607 }
1608
1609 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001610 assert(isa<RecordType>(CanonType) &&
1611 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001612 }
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Douglas Gregor40808ce2009-03-09 23:48:35 +00001614 // Build the fully-sugared type for this class template
1615 // specialization, which refers back to the class template
1616 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00001617 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001618}
1619
John McCallf312b1e2010-08-26 23:41:50 +00001620TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001621Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001622 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001623 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001624 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001625 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001626
Douglas Gregor40808ce2009-03-09 23:48:35 +00001627 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001628 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001629 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001630
John McCalld5532b62009-11-23 01:53:49 +00001631 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001632 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001633
1634 if (Result.isNull())
1635 return true;
1636
John McCalla93c9342009-12-07 02:54:59 +00001637 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001638 TemplateSpecializationTypeLoc TL
1639 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1640 TL.setTemplateNameLoc(TemplateLoc);
1641 TL.setLAngleLoc(LAngleLoc);
1642 TL.setRAngleLoc(RAngleLoc);
1643 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1644 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1645
John McCallb3d87482010-08-24 05:47:05 +00001646 return CreateParsedType(Result, DI);
John McCall6b2becf2009-09-08 17:47:29 +00001647}
John McCallf1bbbb42009-09-04 01:14:41 +00001648
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001649TypeResult Sema::ActOnTagTemplateIdType(CXXScopeSpec &SS,
1650 TypeResult TypeResult,
John McCallf312b1e2010-08-26 23:41:50 +00001651 TagUseKind TUK,
1652 TypeSpecifierType TagSpec,
1653 SourceLocation TagLoc) {
John McCall6b2becf2009-09-08 17:47:29 +00001654 if (TypeResult.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001655 return ::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001656
John McCalla93c9342009-12-07 02:54:59 +00001657 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001658 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001659
John McCall6b2becf2009-09-08 17:47:29 +00001660 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001661 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001662
John McCall6b2becf2009-09-08 17:47:29 +00001663 if (const RecordType *RT = Type->getAs<RecordType>()) {
1664 RecordDecl *D = RT->getDecl();
1665
1666 IdentifierInfo *Id = D->getIdentifier();
1667 assert(Id && "templated class must have an identifier");
1668
1669 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1670 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001671 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001672 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001673 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001674 }
1675 }
1676
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001677 ElaboratedTypeKeyword Keyword
1678 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1679 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001680
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001681 TypeSourceInfo *ElabDI = Context.CreateTypeSourceInfo(ElabType);
1682 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(ElabDI->getTypeLoc());
1683 TL.setKeywordLoc(TagLoc);
1684 TL.setQualifierRange(SS.getRange());
1685 TL.getNamedTypeLoc().initializeFullCopy(DI->getTypeLoc());
1686 return CreateParsedType(ElabType, ElabDI);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001687}
1688
John McCall60d7b3a2010-08-24 06:29:42 +00001689ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001690 LookupResult &R,
1691 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001692 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001693 // FIXME: Can we do any checking at this point? I guess we could check the
1694 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001695 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001696 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001697
1698 // These should be filtered out by our callers.
1699 assert(!R.empty() && "empty lookup results when building templateid");
1700 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1701
1702 NestedNameSpecifier *Qualifier = 0;
1703 SourceRange QualifierRange;
1704 if (SS.isSet()) {
1705 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1706 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001707 }
John McCallc373d482010-01-27 01:50:18 +00001708
1709 // We don't want lookup warnings at this point.
1710 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001711
John McCallf7a1a742009-11-24 19:00:30 +00001712 bool Dependent
1713 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1714 &TemplateArgs);
1715 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001716 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001717 Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00001718 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001719 RequiresADL, TemplateArgs,
1720 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001721
1722 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001723}
1724
John McCallf7a1a742009-11-24 19:00:30 +00001725// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00001726ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001727Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001728 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +00001729 const TemplateArgumentListInfo &TemplateArgs) {
1730 DeclContext *DC;
1731 if (!(DC = computeDeclContext(SS, false)) ||
1732 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001733 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara25777432010-08-11 22:01:17 +00001734 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001736 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00001737 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001738 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1739 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001740
John McCallf7a1a742009-11-24 19:00:30 +00001741 if (R.isAmbiguous())
1742 return ExprError();
1743
1744 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001745 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1746 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001747 return ExprError();
1748 }
1749
1750 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001751 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1752 << (NestedNameSpecifier*) SS.getScopeRep()
1753 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001754 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1755 return ExprError();
1756 }
1757
1758 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001759}
1760
Douglas Gregorc45c2322009-03-31 00:43:58 +00001761/// \brief Form a dependent template name.
1762///
1763/// This action forms a dependent template name given the template
1764/// name and its (presumably dependent) scope specifier. For
1765/// example, given "MetaFun::template apply", the scope specifier \p
1766/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1767/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001768TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1769 SourceLocation TemplateKWLoc,
1770 CXXScopeSpec &SS,
1771 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00001772 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001773 bool EnteringContext,
1774 TemplateTy &Result) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00001775 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1776 !getLangOptions().CPlusPlus0x)
1777 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1778 << FixItHint::CreateRemoval(TemplateKWLoc);
1779
Douglas Gregor0707bc52010-01-19 16:01:07 +00001780 DeclContext *LookupCtx = 0;
1781 if (SS.isSet())
1782 LookupCtx = computeDeclContext(SS, EnteringContext);
1783 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00001784 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00001785 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001786 // C++0x [temp.names]p5:
1787 // If a name prefixed by the keyword template is not the name of
1788 // a template, the program is ill-formed. [Note: the keyword
1789 // template may not be applied to non-template members of class
1790 // templates. -end note ] [ Note: as is the case with the
1791 // typename prefix, the template prefix is allowed in cases
1792 // where it is not strictly necessary; i.e., when the
1793 // nested-name-specifier or the expression on the left of the ->
1794 // or . is not dependent on a template-parameter, or the use
1795 // does not appear in the scope of a template. -end note]
1796 //
1797 // Note: C++03 was more strict here, because it banned the use of
1798 // the "template" keyword prior to a template-name that was not a
1799 // dependent name. C++ DR468 relaxed this requirement (the
1800 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00001801 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001802 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001803 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1804 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001805 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001806 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1807 isa<CXXRecordDecl>(LookupCtx) &&
1808 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00001809 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001810 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001811 Diag(Name.getSourceRange().getBegin(),
1812 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001813 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001814 << Name.getSourceRange()
1815 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001816 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001817 } else {
1818 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001819 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001820 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001821 }
1822
Mike Stump1eb44332009-09-09 15:08:12 +00001823 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001824 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001825
1826 switch (Name.getKind()) {
1827 case UnqualifiedId::IK_Identifier:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001828 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1829 Name.Identifier));
1830 return TNK_Dependent_template_name;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001831
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001832 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001833 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001834 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00001835 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00001836
1837 case UnqualifiedId::IK_LiteralOperatorId:
1838 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1839
Douglas Gregor014e88d2009-11-03 23:16:33 +00001840 default:
1841 break;
1842 }
1843
1844 Diag(Name.getSourceRange().getBegin(),
1845 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001846 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001847 << Name.getSourceRange()
1848 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001849 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001850}
1851
Mike Stump1eb44332009-09-09 15:08:12 +00001852bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001853 const TemplateArgumentLoc &AL,
Douglas Gregor910f8002010-11-07 23:05:16 +00001854 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001855 const TemplateArgument &Arg = AL.getArgument();
1856
Anders Carlsson436b1562009-06-13 00:33:33 +00001857 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001858 switch(Arg.getKind()) {
1859 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001860 // C++ [temp.arg.type]p1:
1861 // A template-argument for a template-parameter which is a
1862 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001863 break;
1864 case TemplateArgument::Template: {
1865 // We have a template type parameter but the template argument
1866 // is a template without any arguments.
1867 SourceRange SR = AL.getSourceRange();
1868 TemplateName Name = Arg.getAsTemplate();
1869 Diag(SR.getBegin(), diag::err_template_missing_args)
1870 << Name << SR;
1871 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1872 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001873
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001874 return true;
1875 }
1876 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001877 // We have a template type parameter but the template argument
1878 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001879 SourceRange SR = AL.getSourceRange();
1880 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001881 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Anders Carlsson436b1562009-06-13 00:33:33 +00001883 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001884 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001885 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001886
John McCalla93c9342009-12-07 02:54:59 +00001887 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001888 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001889
Anders Carlsson436b1562009-06-13 00:33:33 +00001890 // Add the converted template type argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001891 Converted.push_back(
John McCall833ca992009-10-29 08:12:44 +00001892 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001893 return false;
1894}
1895
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001896/// \brief Substitute template arguments into the default template argument for
1897/// the given template type parameter.
1898///
1899/// \param SemaRef the semantic analysis object for which we are performing
1900/// the substitution.
1901///
1902/// \param Template the template that we are synthesizing template arguments
1903/// for.
1904///
1905/// \param TemplateLoc the location of the template name that started the
1906/// template-id we are checking.
1907///
1908/// \param RAngleLoc the location of the right angle bracket ('>') that
1909/// terminates the template-id.
1910///
1911/// \param Param the template template parameter whose default we are
1912/// substituting into.
1913///
1914/// \param Converted the list of template arguments provided for template
1915/// parameters that precede \p Param in the template parameter list.
1916///
1917/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001918static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001919SubstDefaultTemplateArgument(Sema &SemaRef,
1920 TemplateDecl *Template,
1921 SourceLocation TemplateLoc,
1922 SourceLocation RAngleLoc,
1923 TemplateTypeParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00001924 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001925 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001926
1927 // If the argument type is dependent, instantiate it now based
1928 // on the previously-computed template arguments.
1929 if (ArgType->getType()->isDependentType()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001930 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1931 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001932
1933 MultiLevelTemplateArgumentList AllTemplateArgs
1934 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1935
1936 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00001937 Template, Converted.data(),
1938 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001939 SourceRange(TemplateLoc, RAngleLoc));
1940
1941 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1942 Param->getDefaultArgumentLoc(),
1943 Param->getDeclName());
1944 }
1945
1946 return ArgType;
1947}
1948
1949/// \brief Substitute template arguments into the default template argument for
1950/// the given non-type template parameter.
1951///
1952/// \param SemaRef the semantic analysis object for which we are performing
1953/// the substitution.
1954///
1955/// \param Template the template that we are synthesizing template arguments
1956/// for.
1957///
1958/// \param TemplateLoc the location of the template name that started the
1959/// template-id we are checking.
1960///
1961/// \param RAngleLoc the location of the right angle bracket ('>') that
1962/// terminates the template-id.
1963///
Douglas Gregor788cd062009-11-11 01:00:40 +00001964/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001965/// substituting into.
1966///
1967/// \param Converted the list of template arguments provided for template
1968/// parameters that precede \p Param in the template parameter list.
1969///
1970/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00001971static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001972SubstDefaultTemplateArgument(Sema &SemaRef,
1973 TemplateDecl *Template,
1974 SourceLocation TemplateLoc,
1975 SourceLocation RAngleLoc,
1976 NonTypeTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00001977 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
1978 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1979 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001980
1981 MultiLevelTemplateArgumentList AllTemplateArgs
1982 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1983
1984 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00001985 Template, Converted.data(),
1986 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001987 SourceRange(TemplateLoc, RAngleLoc));
1988
1989 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1990}
1991
Douglas Gregor788cd062009-11-11 01:00:40 +00001992/// \brief Substitute template arguments into the default template argument for
1993/// the given template template parameter.
1994///
1995/// \param SemaRef the semantic analysis object for which we are performing
1996/// the substitution.
1997///
1998/// \param Template the template that we are synthesizing template arguments
1999/// for.
2000///
2001/// \param TemplateLoc the location of the template name that started the
2002/// template-id we are checking.
2003///
2004/// \param RAngleLoc the location of the right angle bracket ('>') that
2005/// terminates the template-id.
2006///
2007/// \param Param the template template parameter whose default we are
2008/// substituting into.
2009///
2010/// \param Converted the list of template arguments provided for template
2011/// parameters that precede \p Param in the template parameter list.
2012///
2013/// \returns the substituted template argument, or NULL if an error occurred.
2014static TemplateName
2015SubstDefaultTemplateArgument(Sema &SemaRef,
2016 TemplateDecl *Template,
2017 SourceLocation TemplateLoc,
2018 SourceLocation RAngleLoc,
2019 TemplateTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002020 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2021 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2022 Converted.data(), Converted.size());
Douglas Gregor788cd062009-11-11 01:00:40 +00002023
2024 MultiLevelTemplateArgumentList AllTemplateArgs
2025 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2026
2027 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002028 Template, Converted.data(),
2029 Converted.size(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002030 SourceRange(TemplateLoc, RAngleLoc));
2031
2032 return SemaRef.SubstTemplateName(
2033 Param->getDefaultArgument().getArgument().getAsTemplate(),
2034 Param->getDefaultArgument().getTemplateNameLoc(),
2035 AllTemplateArgs);
2036}
2037
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002038/// \brief If the given template parameter has a default template
2039/// argument, substitute into that default template argument and
2040/// return the corresponding template argument.
2041TemplateArgumentLoc
2042Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2043 SourceLocation TemplateLoc,
2044 SourceLocation RAngleLoc,
2045 Decl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002046 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2047 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002048 if (!TypeParm->hasDefaultArgument())
2049 return TemplateArgumentLoc();
2050
John McCalla93c9342009-12-07 02:54:59 +00002051 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002052 TemplateLoc,
2053 RAngleLoc,
2054 TypeParm,
2055 Converted);
2056 if (DI)
2057 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2058
2059 return TemplateArgumentLoc();
2060 }
2061
2062 if (NonTypeTemplateParmDecl *NonTypeParm
2063 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2064 if (!NonTypeParm->hasDefaultArgument())
2065 return TemplateArgumentLoc();
2066
John McCall60d7b3a2010-08-24 06:29:42 +00002067 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002068 TemplateLoc,
2069 RAngleLoc,
2070 NonTypeParm,
2071 Converted);
2072 if (Arg.isInvalid())
2073 return TemplateArgumentLoc();
2074
2075 Expr *ArgE = Arg.takeAs<Expr>();
2076 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2077 }
2078
2079 TemplateTemplateParmDecl *TempTempParm
2080 = cast<TemplateTemplateParmDecl>(Param);
2081 if (!TempTempParm->hasDefaultArgument())
2082 return TemplateArgumentLoc();
2083
2084 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2085 TemplateLoc,
2086 RAngleLoc,
2087 TempTempParm,
2088 Converted);
2089 if (TName.isNull())
2090 return TemplateArgumentLoc();
2091
2092 return TemplateArgumentLoc(TemplateArgument(TName),
2093 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2094 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2095}
2096
Douglas Gregore7526412009-11-11 19:31:23 +00002097/// \brief Check that the given template argument corresponds to the given
2098/// template parameter.
2099bool Sema::CheckTemplateArgument(NamedDecl *Param,
2100 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00002101 TemplateDecl *Template,
2102 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002103 SourceLocation RAngleLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002104 llvm::SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor02024a92010-03-28 02:42:43 +00002105 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002106 // Check template type parameters.
2107 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002108 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002109
Douglas Gregord9e15302009-11-11 19:41:09 +00002110 // Check non-type template parameters.
2111 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002112 // Do substitution on the type of the non-type template parameter
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002113 // with the template arguments we've seen thus far. But if the
2114 // template has a dependent context then we cannot substitute yet.
Douglas Gregore7526412009-11-11 19:31:23 +00002115 QualType NTTPType = NTTP->getType();
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002116 if (NTTPType->isDependentType() &&
2117 !isa<TemplateTemplateParmDecl>(Template) &&
2118 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002119 // Do substitution on the type of the non-type template parameter.
2120 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002121 NTTP, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002122 SourceRange(TemplateLoc, RAngleLoc));
2123
Douglas Gregor910f8002010-11-07 23:05:16 +00002124 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2125 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002126 NTTPType = SubstType(NTTPType,
2127 MultiLevelTemplateArgumentList(TemplateArgs),
2128 NTTP->getLocation(),
2129 NTTP->getDeclName());
2130 // If that worked, check the non-type template parameter type
2131 // for validity.
2132 if (!NTTPType.isNull())
2133 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2134 NTTP->getLocation());
2135 if (NTTPType.isNull())
2136 return true;
2137 }
2138
2139 switch (Arg.getArgument().getKind()) {
2140 case TemplateArgument::Null:
2141 assert(false && "Should never see a NULL template argument here");
2142 return true;
2143
2144 case TemplateArgument::Expression: {
2145 Expr *E = Arg.getArgument().getAsExpr();
2146 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002147 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002148 return true;
2149
Douglas Gregor910f8002010-11-07 23:05:16 +00002150 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002151 break;
2152 }
2153
2154 case TemplateArgument::Declaration:
2155 case TemplateArgument::Integral:
2156 // We've already checked this template argument, so just copy
2157 // it to the list of converted arguments.
Douglas Gregor910f8002010-11-07 23:05:16 +00002158 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002159 break;
2160
2161 case TemplateArgument::Template:
2162 // We were given a template template argument. It may not be ill-formed;
2163 // see below.
2164 if (DependentTemplateName *DTN
2165 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2166 // We have a template argument such as \c T::template X, which we
2167 // parsed as a template template argument. However, since we now
2168 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002169 // template name into an expression.
2170
2171 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2172 Arg.getTemplateNameLoc());
2173
John McCallf7a1a742009-11-24 19:00:30 +00002174 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2175 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002176 Arg.getTemplateQualifierRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002177 NameInfo);
Douglas Gregore7526412009-11-11 19:31:23 +00002178
2179 TemplateArgument Result;
2180 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2181 return true;
2182
Douglas Gregor910f8002010-11-07 23:05:16 +00002183 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002184 break;
2185 }
2186
2187 // We have a template argument that actually does refer to a class
2188 // template, template alias, or template template parameter, and
2189 // therefore cannot be a non-type template argument.
2190 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2191 << Arg.getSourceRange();
2192
2193 Diag(Param->getLocation(), diag::note_template_param_here);
2194 return true;
2195
2196 case TemplateArgument::Type: {
2197 // We have a non-type template parameter but the template
2198 // argument is a type.
2199
2200 // C++ [temp.arg]p2:
2201 // In a template-argument, an ambiguity between a type-id and
2202 // an expression is resolved to a type-id, regardless of the
2203 // form of the corresponding template-parameter.
2204 //
2205 // We warn specifically about this case, since it can be rather
2206 // confusing for users.
2207 QualType T = Arg.getArgument().getAsType();
2208 SourceRange SR = Arg.getSourceRange();
2209 if (T->isFunctionType())
2210 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2211 else
2212 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2213 Diag(Param->getLocation(), diag::note_template_param_here);
2214 return true;
2215 }
2216
2217 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002218 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002219 break;
2220 }
2221
2222 return false;
2223 }
2224
2225
2226 // Check template template parameters.
2227 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2228
2229 // Substitute into the template parameter list of the template
2230 // template parameter, since previously-supplied template arguments
2231 // may appear within the template template parameter.
2232 {
2233 // Set up a template instantiation context.
2234 LocalInstantiationScope Scope(*this);
2235 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002236 TempParm, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002237 SourceRange(TemplateLoc, RAngleLoc));
2238
Douglas Gregor910f8002010-11-07 23:05:16 +00002239 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2240 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002241 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2242 SubstDecl(TempParm, CurContext,
2243 MultiLevelTemplateArgumentList(TemplateArgs)));
2244 if (!TempParm)
2245 return true;
2246
2247 // FIXME: TempParam is leaked.
2248 }
2249
2250 switch (Arg.getArgument().getKind()) {
2251 case TemplateArgument::Null:
2252 assert(false && "Should never see a NULL template argument here");
2253 return true;
2254
2255 case TemplateArgument::Template:
2256 if (CheckTemplateArgument(TempParm, Arg))
2257 return true;
2258
Douglas Gregor910f8002010-11-07 23:05:16 +00002259 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002260 break;
2261
2262 case TemplateArgument::Expression:
2263 case TemplateArgument::Type:
2264 // We have a template template parameter but the template
2265 // argument does not refer to a template.
2266 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2267 return true;
2268
2269 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002270 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002271 "Declaration argument with template template parameter");
2272 break;
2273 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002274 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002275 "Integral argument with template template parameter");
2276 break;
2277
2278 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002279 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002280 break;
2281 }
2282
2283 return false;
2284}
2285
Douglas Gregorc15cb382009-02-09 23:23:08 +00002286/// \brief Check that the given template argument list is well-formed
2287/// for specializing the given template.
2288bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2289 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002290 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002291 bool PartialTemplateArgs,
Douglas Gregor910f8002010-11-07 23:05:16 +00002292 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002293 TemplateParameterList *Params = Template->getTemplateParameters();
2294 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002295 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002296 bool Invalid = false;
2297
John McCalld5532b62009-11-23 01:53:49 +00002298 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2299
Mike Stump1eb44332009-09-09 15:08:12 +00002300 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002301 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002302
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002303 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002304 (NumArgs < Params->getMinRequiredArguments() &&
2305 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002306 // FIXME: point at either the first arg beyond what we can handle,
2307 // or the '>', depending on whether we have too many or too few
2308 // arguments.
2309 SourceRange Range;
2310 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002311 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002312 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2313 << (NumArgs > NumParams)
2314 << (isa<ClassTemplateDecl>(Template)? 0 :
2315 isa<FunctionTemplateDecl>(Template)? 1 :
2316 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2317 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002318 Diag(Template->getLocation(), diag::note_template_decl_here)
2319 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002320 Invalid = true;
2321 }
Mike Stump1eb44332009-09-09 15:08:12 +00002322
2323 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002324 // [...] The type and form of each template-argument specified in
2325 // a template-id shall match the type and form specified for the
2326 // corresponding parameter declared by the template in its
2327 // template-parameter-list.
2328 unsigned ArgIdx = 0;
2329 for (TemplateParameterList::iterator Param = Params->begin(),
2330 ParamEnd = Params->end();
2331 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002332 if (ArgIdx > NumArgs && PartialTemplateArgs)
2333 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Douglas Gregord9e15302009-11-11 19:41:09 +00002335 // If we have a template parameter pack, check every remaining template
2336 // argument against that template parameter pack.
2337 if ((*Param)->isTemplateParameterPack()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002338 Diag(TemplateLoc, diag::err_variadic_templates_unsupported);
2339 return true;
Douglas Gregord9e15302009-11-11 19:41:09 +00002340 }
2341
Douglas Gregorf35f8282009-11-11 21:54:23 +00002342 if (ArgIdx < NumArgs) {
2343 // Check the template argument we were given.
2344 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2345 TemplateLoc, RAngleLoc, Converted))
2346 return true;
2347
2348 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002349 }
Douglas Gregore7526412009-11-11 19:31:23 +00002350
Douglas Gregorf35f8282009-11-11 21:54:23 +00002351 // We have a default template argument that we will use.
2352 TemplateArgumentLoc Arg;
2353
2354 // Retrieve the default template argument from the template
2355 // parameter. For each kind of template parameter, we substitute the
2356 // template arguments provided thus far and any "outer" template arguments
2357 // (when the template parameter was part of a nested template) into
2358 // the default argument.
2359 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2360 if (!TTP->hasDefaultArgument()) {
2361 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2362 break;
2363 }
2364
John McCalla93c9342009-12-07 02:54:59 +00002365 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002366 Template,
2367 TemplateLoc,
2368 RAngleLoc,
2369 TTP,
2370 Converted);
2371 if (!ArgType)
2372 return true;
2373
2374 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2375 ArgType);
2376 } else if (NonTypeTemplateParmDecl *NTTP
2377 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2378 if (!NTTP->hasDefaultArgument()) {
2379 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2380 break;
2381 }
2382
John McCall60d7b3a2010-08-24 06:29:42 +00002383 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002384 TemplateLoc,
2385 RAngleLoc,
2386 NTTP,
2387 Converted);
2388 if (E.isInvalid())
2389 return true;
2390
2391 Expr *Ex = E.takeAs<Expr>();
2392 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2393 } else {
2394 TemplateTemplateParmDecl *TempParm
2395 = cast<TemplateTemplateParmDecl>(*Param);
2396
2397 if (!TempParm->hasDefaultArgument()) {
2398 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2399 break;
2400 }
2401
2402 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2403 TemplateLoc,
2404 RAngleLoc,
2405 TempParm,
2406 Converted);
2407 if (Name.isNull())
2408 return true;
2409
2410 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2411 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2412 TempParm->getDefaultArgument().getTemplateNameLoc());
2413 }
2414
2415 // Introduce an instantiation record that describes where we are using
2416 // the default template argument.
2417 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002418 Converted.data(), Converted.size(),
Douglas Gregorf35f8282009-11-11 21:54:23 +00002419 SourceRange(TemplateLoc, RAngleLoc));
2420
2421 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002422 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002423 RAngleLoc, Converted))
2424 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002425 }
2426
2427 return Invalid;
2428}
2429
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002430namespace {
2431 class UnnamedLocalNoLinkageFinder
2432 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2433 {
2434 Sema &S;
2435 SourceRange SR;
2436
2437 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2438
2439 public:
2440 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2441
2442 bool Visit(QualType T) {
2443 return inherited::Visit(T.getTypePtr());
2444 }
2445
2446#define TYPE(Class, Parent) \
2447 bool Visit##Class##Type(const Class##Type *);
2448#define ABSTRACT_TYPE(Class, Parent) \
2449 bool Visit##Class##Type(const Class##Type *) { return false; }
2450#define NON_CANONICAL_TYPE(Class, Parent) \
2451 bool Visit##Class##Type(const Class##Type *) { return false; }
2452#include "clang/AST/TypeNodes.def"
2453
2454 bool VisitTagDecl(const TagDecl *Tag);
2455 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2456 };
2457}
2458
2459bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2460 return false;
2461}
2462
2463bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2464 return Visit(T->getElementType());
2465}
2466
2467bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2468 return Visit(T->getPointeeType());
2469}
2470
2471bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2472 const BlockPointerType* T) {
2473 return Visit(T->getPointeeType());
2474}
2475
2476bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2477 const LValueReferenceType* T) {
2478 return Visit(T->getPointeeType());
2479}
2480
2481bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2482 const RValueReferenceType* T) {
2483 return Visit(T->getPointeeType());
2484}
2485
2486bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2487 const MemberPointerType* T) {
2488 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2489}
2490
2491bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2492 const ConstantArrayType* T) {
2493 return Visit(T->getElementType());
2494}
2495
2496bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2497 const IncompleteArrayType* T) {
2498 return Visit(T->getElementType());
2499}
2500
2501bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2502 const VariableArrayType* T) {
2503 return Visit(T->getElementType());
2504}
2505
2506bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2507 const DependentSizedArrayType* T) {
2508 return Visit(T->getElementType());
2509}
2510
2511bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2512 const DependentSizedExtVectorType* T) {
2513 return Visit(T->getElementType());
2514}
2515
2516bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2517 return Visit(T->getElementType());
2518}
2519
2520bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2521 return Visit(T->getElementType());
2522}
2523
2524bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2525 const FunctionProtoType* T) {
2526 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2527 AEnd = T->arg_type_end();
2528 A != AEnd; ++A) {
2529 if (Visit(*A))
2530 return true;
2531 }
2532
2533 return Visit(T->getResultType());
2534}
2535
2536bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2537 const FunctionNoProtoType* T) {
2538 return Visit(T->getResultType());
2539}
2540
2541bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2542 const UnresolvedUsingType*) {
2543 return false;
2544}
2545
2546bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2547 return false;
2548}
2549
2550bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2551 return Visit(T->getUnderlyingType());
2552}
2553
2554bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2555 return false;
2556}
2557
2558bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2559 return VisitTagDecl(T->getDecl());
2560}
2561
2562bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2563 return VisitTagDecl(T->getDecl());
2564}
2565
2566bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2567 const TemplateTypeParmType*) {
2568 return false;
2569}
2570
2571bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2572 const TemplateSpecializationType*) {
2573 return false;
2574}
2575
2576bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2577 const InjectedClassNameType* T) {
2578 return VisitTagDecl(T->getDecl());
2579}
2580
2581bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2582 const DependentNameType* T) {
2583 return VisitNestedNameSpecifier(T->getQualifier());
2584}
2585
2586bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2587 const DependentTemplateSpecializationType* T) {
2588 return VisitNestedNameSpecifier(T->getQualifier());
2589}
2590
2591bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2592 return false;
2593}
2594
2595bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2596 const ObjCInterfaceType *) {
2597 return false;
2598}
2599
2600bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2601 const ObjCObjectPointerType *) {
2602 return false;
2603}
2604
2605bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2606 if (Tag->getDeclContext()->isFunctionOrMethod()) {
2607 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2608 << S.Context.getTypeDeclType(Tag) << SR;
2609 return true;
2610 }
2611
2612 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2613 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2614 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2615 return true;
2616 }
2617
2618 return false;
2619}
2620
2621bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2622 NestedNameSpecifier *NNS) {
2623 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2624 return true;
2625
2626 switch (NNS->getKind()) {
2627 case NestedNameSpecifier::Identifier:
2628 case NestedNameSpecifier::Namespace:
2629 case NestedNameSpecifier::Global:
2630 return false;
2631
2632 case NestedNameSpecifier::TypeSpec:
2633 case NestedNameSpecifier::TypeSpecWithTemplate:
2634 return Visit(QualType(NNS->getAsType(), 0));
2635 }
Fariborz Jahanian7b1ec6c2010-10-13 16:19:16 +00002636 return false;
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002637}
2638
2639
Douglas Gregorc15cb382009-02-09 23:23:08 +00002640/// \brief Check a template argument against its corresponding
2641/// template type parameter.
2642///
2643/// This routine implements the semantics of C++ [temp.arg.type]. It
2644/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002645bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002646 TypeSourceInfo *ArgInfo) {
2647 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002648 QualType Arg = ArgInfo->getType();
Douglas Gregor0fddb972010-05-22 16:17:30 +00002649 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth17fb8552010-09-03 21:12:34 +00002650
2651 if (Arg->isVariablyModifiedType()) {
2652 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002653 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00002654 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002655 }
2656
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002657 // C++03 [temp.arg.type]p2:
2658 // A local type, a type with no linkage, an unnamed type or a type
2659 // compounded from any of these types shall not be used as a
2660 // template-argument for a template type-parameter.
2661 //
2662 // C++0x allows these, and even in C++03 we allow them as an extension with
2663 // a warning.
Douglas Gregordb4d4bb2010-10-13 18:05:20 +00002664 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002665 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2666 (void)Finder.Visit(Context.getCanonicalType(Arg));
2667 }
2668
Douglas Gregorc15cb382009-02-09 23:23:08 +00002669 return false;
2670}
2671
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002672/// \brief Checks whether the given template argument is the address
2673/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002674static bool
2675CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2676 NonTypeTemplateParmDecl *Param,
2677 QualType ParamType,
2678 Expr *ArgIn,
2679 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002680 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002681 Expr *Arg = ArgIn;
2682 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002683
2684 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002685 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002686 Arg = Cast->getSubExpr();
2687
2688 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002689 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002690 // A template-argument for a non-type, non-template
2691 // template-parameter shall be one of: [...]
2692 //
2693 // -- the address of an object or function with external
2694 // linkage, including function templates and function
2695 // template-ids but excluding non-static class members,
2696 // expressed as & id-expression where the & is optional if
2697 // the name refers to a function or array, or if the
2698 // corresponding template-parameter is a reference; or
2699 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002700
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002701 // In C++98/03 mode, give an extension warning on any extra parentheses.
2702 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2703 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002704 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002705 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002706 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002707 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002708 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002709 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002710 }
2711
2712 Arg = Parens->getSubExpr();
2713 }
2714
Douglas Gregorb7a09262010-04-01 18:32:35 +00002715 bool AddressTaken = false;
2716 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002717 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002718 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002719 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002720 AddressTaken = true;
2721 AddrOpLoc = UnOp->getOperatorLoc();
2722 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002723 } else
2724 DRE = dyn_cast<DeclRefExpr>(Arg);
2725
Douglas Gregorb7a09262010-04-01 18:32:35 +00002726 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002727 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2728 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002729 S.Diag(Param->getLocation(), diag::note_template_param_here);
2730 return true;
2731 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002732
2733 // Stop checking the precise nature of the argument if it is value dependent,
2734 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002735 if (Arg->isValueDependent()) {
John McCall3fa5cae2010-10-26 07:05:15 +00002736 Converted = TemplateArgument(ArgIn);
Chandler Carruth038cc392010-01-31 10:01:20 +00002737 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002738 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002739
Douglas Gregorb7a09262010-04-01 18:32:35 +00002740 if (!isa<ValueDecl>(DRE->getDecl())) {
2741 S.Diag(Arg->getSourceRange().getBegin(),
2742 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002743 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002744 S.Diag(Param->getLocation(), diag::note_template_param_here);
2745 return true;
2746 }
2747
2748 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002749
2750 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002751 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2752 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002753 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002754 S.Diag(Param->getLocation(), diag::note_template_param_here);
2755 return true;
2756 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002757
2758 // Cannot refer to non-static member functions
2759 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002760 if (!Method->isStatic()) {
2761 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002762 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002763 S.Diag(Param->getLocation(), diag::note_template_param_here);
2764 return true;
2765 }
Mike Stump1eb44332009-09-09 15:08:12 +00002766
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002767 // Functions must have external linkage.
2768 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002769 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002770 S.Diag(Arg->getSourceRange().getBegin(),
2771 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002772 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002773 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002774 << true;
2775 return true;
2776 }
2777
2778 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002779 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002780
Douglas Gregorb7a09262010-04-01 18:32:35 +00002781 // If the template parameter has pointer type, the function decays.
2782 if (ParamType->isPointerType() && !AddressTaken)
2783 ArgType = S.Context.getPointerType(Func->getType());
2784 else if (AddressTaken && ParamType->isReferenceType()) {
2785 // If we originally had an address-of operator, but the
2786 // parameter has reference type, complain and (if things look
2787 // like they will work) drop the address-of operator.
2788 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2789 ParamType.getNonReferenceType())) {
2790 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2791 << ParamType;
2792 S.Diag(Param->getLocation(), diag::note_template_param_here);
2793 return true;
2794 }
2795
2796 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2797 << ParamType
2798 << FixItHint::CreateRemoval(AddrOpLoc);
2799 S.Diag(Param->getLocation(), diag::note_template_param_here);
2800
2801 ArgType = Func->getType();
2802 }
2803 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002804 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002805 S.Diag(Arg->getSourceRange().getBegin(),
2806 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002807 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002808 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002809 << true;
2810 return true;
2811 }
2812
Douglas Gregorb7a09262010-04-01 18:32:35 +00002813 // A value of reference type is not an object.
2814 if (Var->getType()->isReferenceType()) {
2815 S.Diag(Arg->getSourceRange().getBegin(),
2816 diag::err_template_arg_reference_var)
2817 << Var->getType() << Arg->getSourceRange();
2818 S.Diag(Param->getLocation(), diag::note_template_param_here);
2819 return true;
2820 }
2821
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002822 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002823 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002824
2825 // If the template parameter has pointer type, we must have taken
2826 // the address of this object.
2827 if (ParamType->isReferenceType()) {
2828 if (AddressTaken) {
2829 // If we originally had an address-of operator, but the
2830 // parameter has reference type, complain and (if things look
2831 // like they will work) drop the address-of operator.
2832 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2833 ParamType.getNonReferenceType())) {
2834 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2835 << ParamType;
2836 S.Diag(Param->getLocation(), diag::note_template_param_here);
2837 return true;
2838 }
2839
2840 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2841 << ParamType
2842 << FixItHint::CreateRemoval(AddrOpLoc);
2843 S.Diag(Param->getLocation(), diag::note_template_param_here);
2844
2845 ArgType = Var->getType();
2846 }
2847 } else if (!AddressTaken && ParamType->isPointerType()) {
2848 if (Var->getType()->isArrayType()) {
2849 // Array-to-pointer decay.
2850 ArgType = S.Context.getArrayDecayedType(Var->getType());
2851 } else {
2852 // If the template parameter has pointer type but the address of
2853 // this object was not taken, complain and (possibly) recover by
2854 // taking the address of the entity.
2855 ArgType = S.Context.getPointerType(Var->getType());
2856 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2857 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2858 << ParamType;
2859 S.Diag(Param->getLocation(), diag::note_template_param_here);
2860 return true;
2861 }
2862
2863 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2864 << ParamType
2865 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2866
2867 S.Diag(Param->getLocation(), diag::note_template_param_here);
2868 }
2869 }
2870 } else {
2871 // We found something else, but we don't know specifically what it is.
2872 S.Diag(Arg->getSourceRange().getBegin(),
2873 diag::err_template_arg_not_object_or_func)
2874 << Arg->getSourceRange();
2875 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2876 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002877 }
Mike Stump1eb44332009-09-09 15:08:12 +00002878
Douglas Gregorb7a09262010-04-01 18:32:35 +00002879 if (ParamType->isPointerType() &&
2880 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2881 S.IsQualificationConversion(ArgType, ParamType)) {
2882 // For pointer-to-object types, qualification conversions are
2883 // permitted.
2884 } else {
2885 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2886 if (!ParamRef->getPointeeType()->isFunctionType()) {
2887 // C++ [temp.arg.nontype]p5b3:
2888 // For a non-type template-parameter of type reference to
2889 // object, no conversions apply. The type referred to by the
2890 // reference may be more cv-qualified than the (otherwise
2891 // identical) type of the template- argument. The
2892 // template-parameter is bound directly to the
2893 // template-argument, which shall be an lvalue.
2894
2895 // FIXME: Other qualifiers?
2896 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2897 unsigned ArgQuals = ArgType.getCVRQualifiers();
2898
2899 if ((ParamQuals | ArgQuals) != ParamQuals) {
2900 S.Diag(Arg->getSourceRange().getBegin(),
2901 diag::err_template_arg_ref_bind_ignores_quals)
2902 << ParamType << Arg->getType()
2903 << Arg->getSourceRange();
2904 S.Diag(Param->getLocation(), diag::note_template_param_here);
2905 return true;
2906 }
2907 }
2908 }
2909
2910 // At this point, the template argument refers to an object or
2911 // function with external linkage. We now need to check whether the
2912 // argument and parameter types are compatible.
2913 if (!S.Context.hasSameUnqualifiedType(ArgType,
2914 ParamType.getNonReferenceType())) {
2915 // We can't perform this conversion or binding.
2916 if (ParamType->isReferenceType())
2917 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2918 << ParamType << Arg->getType() << Arg->getSourceRange();
2919 else
2920 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2921 << Arg->getType() << ParamType << Arg->getSourceRange();
2922 S.Diag(Param->getLocation(), diag::note_template_param_here);
2923 return true;
2924 }
2925 }
2926
2927 // Create the template argument.
2928 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00002929 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00002930 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002931}
2932
2933/// \brief Checks whether the given template argument is a pointer to
2934/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002935bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2936 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002937 bool Invalid = false;
2938
2939 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002940 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002941 Arg = Cast->getSubExpr();
2942
2943 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002944 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002945 // A template-argument for a non-type, non-template
2946 // template-parameter shall be one of: [...]
2947 //
2948 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002949 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002950
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002951 // In C++98/03 mode, give an extension warning on any extra parentheses.
2952 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2953 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002954 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002955 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00002956 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002957 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002958 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002959 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002960 }
2961
2962 Arg = Parens->getSubExpr();
2963 }
2964
Douglas Gregorcaddba02009-11-12 18:38:13 +00002965 // A pointer-to-member constant written &Class::member.
2966 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002967 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002968 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2969 if (DRE && !DRE->getQualifier())
2970 DRE = 0;
2971 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002972 }
2973 // A constant of pointer-to-member type.
2974 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2975 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2976 if (VD->getType()->isMemberPointerType()) {
2977 if (isa<NonTypeTemplateParmDecl>(VD) ||
2978 (isa<VarDecl>(VD) &&
2979 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2980 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00002981 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00002982 else
2983 Converted = TemplateArgument(VD->getCanonicalDecl());
2984 return Invalid;
2985 }
2986 }
2987 }
2988
2989 DRE = 0;
2990 }
2991
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002992 if (!DRE)
2993 return Diag(Arg->getSourceRange().getBegin(),
2994 diag::err_template_arg_not_pointer_to_member_form)
2995 << Arg->getSourceRange();
2996
2997 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2998 assert((isa<FieldDecl>(DRE->getDecl()) ||
2999 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3000 "Only non-static member pointers can make it here");
3001
3002 // Okay: this is the address of a non-static member, and therefore
3003 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003004 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003005 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003006 else
3007 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003008 return Invalid;
3009 }
3010
3011 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00003012 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003013 diag::err_template_arg_not_pointer_to_member_form)
3014 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003015 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003016 diag::note_template_arg_refers_here);
3017 return true;
3018}
3019
Douglas Gregorc15cb382009-02-09 23:23:08 +00003020/// \brief Check a template argument against its corresponding
3021/// non-type template parameter.
3022///
Douglas Gregor2943aed2009-03-03 04:44:36 +00003023/// This routine implements the semantics of C++ [temp.arg.nontype].
3024/// It returns true if an error occurred, and false otherwise. \p
3025/// InstantiatedParamType is the type of the non-type template
3026/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003027///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003028/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00003029bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00003030 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00003031 TemplateArgument &Converted,
3032 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00003033 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3034
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003035 // If either the parameter has a dependent type or the argument is
3036 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00003037 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3038 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003039 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003040 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00003041 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003042
3043 // C++ [temp.arg.nontype]p5:
3044 // The following conversions are performed on each expression used
3045 // as a non-type template-argument. If a non-type
3046 // template-argument cannot be converted to the type of the
3047 // corresponding template-parameter then the program is
3048 // ill-formed.
3049 //
3050 // -- for a non-type template-parameter of integral or
3051 // enumeration type, integral promotions (4.5) and integral
3052 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00003053 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00003054 QualType ArgType = Arg->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003055 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003056 // C++ [temp.arg.nontype]p1:
3057 // A template-argument for a non-type, non-template
3058 // template-parameter shall be one of:
3059 //
3060 // -- an integral constant-expression of integral or enumeration
3061 // type; or
3062 // -- the name of a non-type template-parameter; or
3063 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003064 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003065 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003066 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003067 diag::err_template_arg_not_integral_or_enumeral)
3068 << ArgType << Arg->getSourceRange();
3069 Diag(Param->getLocation(), diag::note_template_param_here);
3070 return true;
3071 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003072 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003073 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3074 << ArgType << Arg->getSourceRange();
3075 return true;
3076 }
3077
Douglas Gregor02024a92010-03-28 02:42:43 +00003078 // From here on out, all we care about are the unqualified forms
3079 // of the parameter and argument types.
3080 ParamType = ParamType.getUnqualifiedType();
3081 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003082
3083 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00003084 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003085 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00003086 } else if (CTAK == CTAK_Deduced) {
3087 // C++ [temp.deduct.type]p17:
3088 // If, in the declaration of a function template with a non-type
3089 // template-parameter, the non-type template- parameter is used
3090 // in an expression in the function parameter-list and, if the
3091 // corresponding template-argument is deduced, the
3092 // template-argument type shall match the type of the
3093 // template-parameter exactly, except that a template-argument
3094 // deduced from an array bound may be of any integral type.
3095 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3096 << ArgType << ParamType;
3097 Diag(Param->getLocation(), diag::note_template_param_here);
John McCalldaa8e4e2010-11-15 09:13:47 +00003098 return true;
3099 } else if (ParamType->isBooleanType()) {
3100 // This is an integral-to-boolean conversion.
3101 ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003102 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3103 !ParamType->isEnumeralType()) {
3104 // This is an integral promotion or conversion.
John McCall2de56d12010-08-25 11:45:40 +00003105 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003106 } else {
3107 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003108 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003109 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003110 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003111 Diag(Param->getLocation(), diag::note_template_param_here);
3112 return true;
3113 }
3114
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003115 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00003116 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003117 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003118
3119 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003120 llvm::APSInt OldValue = Value;
3121
3122 // Coerce the template argument's value to the value it will have
3123 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003124 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003125 if (Value.getBitWidth() != AllowedBits)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003126 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003127 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003128
3129 // Complain if an unsigned parameter received a negative value.
3130 if (IntegerType->isUnsignedIntegerType()
3131 && (OldValue.isSigned() && OldValue.isNegative())) {
3132 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3133 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3134 << Arg->getSourceRange();
3135 Diag(Param->getLocation(), diag::note_template_param_here);
3136 }
3137
3138 // Complain if we overflowed the template parameter's type.
3139 unsigned RequiredBits;
3140 if (IntegerType->isUnsignedIntegerType())
3141 RequiredBits = OldValue.getActiveBits();
3142 else if (OldValue.isUnsigned())
3143 RequiredBits = OldValue.getActiveBits() + 1;
3144 else
3145 RequiredBits = OldValue.getMinSignedBits();
3146 if (RequiredBits > AllowedBits) {
3147 Diag(Arg->getSourceRange().getBegin(),
3148 diag::warn_template_arg_too_large)
3149 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3150 << Arg->getSourceRange();
3151 Diag(Param->getLocation(), diag::note_template_param_here);
3152 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003153 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003154
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003155 // Add the value of this argument to the list of converted
3156 // arguments. We use the bitwidth and signedness of the template
3157 // parameter.
3158 if (Arg->isValueDependent()) {
3159 // The argument is value-dependent. Create a new
3160 // TemplateArgument with the converted expression.
3161 Converted = TemplateArgument(Arg);
3162 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003163 }
3164
John McCall833ca992009-10-29 08:12:44 +00003165 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00003166 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003167 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003168 return false;
3169 }
Douglas Gregora35284b2009-02-11 00:19:33 +00003170
John McCall6bb80172010-03-30 21:47:33 +00003171 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3172
Douglas Gregorb7a09262010-04-01 18:32:35 +00003173 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3174 // from a template argument of type std::nullptr_t to a non-type
3175 // template parameter of type pointer to object, pointer to
3176 // function, or pointer-to-member, respectively.
3177 if (ArgType->isNullPtrType() &&
3178 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3179 Converted = TemplateArgument((NamedDecl *)0);
3180 return false;
3181 }
3182
Douglas Gregorb86b0572009-02-11 01:18:59 +00003183 // Handle pointer-to-function, reference-to-function, and
3184 // pointer-to-member-function all in (roughly) the same way.
3185 if (// -- For a non-type template-parameter of type pointer to
3186 // function, only the function-to-pointer conversion (4.3) is
3187 // applied. If the template-argument represents a set of
3188 // overloaded functions (or a pointer to such), the matching
3189 // function is selected from the set (13.4).
3190 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003191 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003192 // -- For a non-type template-parameter of type reference to
3193 // function, no conversions apply. If the template-argument
3194 // represents a set of overloaded functions, the matching
3195 // function is selected from the set (13.4).
3196 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003197 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003198 // -- For a non-type template-parameter of type pointer to
3199 // member function, no conversions apply. If the
3200 // template-argument represents a set of overloaded member
3201 // functions, the matching member function is selected from
3202 // the set (13.4).
3203 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003204 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00003205 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003206
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003207 if (Arg->getType() == Context.OverloadTy) {
3208 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3209 true,
3210 FoundResult)) {
3211 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3212 return true;
3213
3214 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3215 ArgType = Arg->getType();
3216 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003217 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00003218 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003219
Douglas Gregorb7a09262010-04-01 18:32:35 +00003220 if (!ParamType->isMemberPointerType())
3221 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3222 ParamType,
3223 Arg, Converted);
3224
3225 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCall2de56d12010-08-25 11:45:40 +00003226 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb7a09262010-04-01 18:32:35 +00003227 } else if (!Context.hasSameUnqualifiedType(ArgType,
3228 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00003229 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003230 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00003231 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003232 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00003233 Diag(Param->getLocation(), diag::note_template_param_here);
3234 return true;
3235 }
Mike Stump1eb44332009-09-09 15:08:12 +00003236
Douglas Gregorb7a09262010-04-01 18:32:35 +00003237 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00003238 }
3239
Chris Lattnerfe90de72009-02-20 21:37:53 +00003240 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003241 // -- for a non-type template-parameter of type pointer to
3242 // object, qualification conversions (4.4) and the
3243 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00003244 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00003245 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003246 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003247
Douglas Gregorb7a09262010-04-01 18:32:35 +00003248 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3249 ParamType,
3250 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003251 }
Mike Stump1eb44332009-09-09 15:08:12 +00003252
Ted Kremenek6217b802009-07-29 21:53:49 +00003253 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003254 // -- For a non-type template-parameter of type reference to
3255 // object, no conversions apply. The type referred to by the
3256 // reference may be more cv-qualified than the (otherwise
3257 // identical) type of the template-argument. The
3258 // template-parameter is bound directly to the
3259 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00003260 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003261 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003262
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003263 if (Arg->getType() == Context.OverloadTy) {
3264 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3265 ParamRefType->getPointeeType(),
3266 true,
3267 FoundResult)) {
3268 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3269 return true;
3270
3271 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3272 ArgType = Arg->getType();
3273 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00003274 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00003275 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003276
Douglas Gregorb7a09262010-04-01 18:32:35 +00003277 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3278 ParamType,
3279 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00003280 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00003281
3282 // -- For a non-type template-parameter of type pointer to data
3283 // member, qualification conversions (4.4) are applied.
3284 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3285
Douglas Gregor8e6563b2009-02-11 18:22:40 +00003286 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00003287 // Types match exactly: nothing more to do here.
3288 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCall2de56d12010-08-25 11:45:40 +00003289 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor658bbb52009-02-11 16:16:59 +00003290 } else {
3291 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003292 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00003293 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003294 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00003295 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00003296 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00003297 }
3298
Douglas Gregorcaddba02009-11-12 18:38:13 +00003299 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00003300}
3301
3302/// \brief Check a template argument against its corresponding
3303/// template template parameter.
3304///
3305/// This routine implements the semantics of C++ [temp.arg.template].
3306/// It returns true if an error occurred, and false otherwise.
3307bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003308 const TemplateArgumentLoc &Arg) {
3309 TemplateName Name = Arg.getArgument().getAsTemplate();
3310 TemplateDecl *Template = Name.getAsTemplateDecl();
3311 if (!Template) {
3312 // Any dependent template name is fine.
3313 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3314 return false;
3315 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003316
3317 // C++ [temp.arg.template]p1:
3318 // A template-argument for a template template-parameter shall be
3319 // the name of a class template, expressed as id-expression. Only
3320 // primary class templates are considered when matching the
3321 // template template argument with the corresponding parameter;
3322 // partial specializations are not considered even if their
3323 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003324 //
3325 // Note that we also allow template template parameters here, which
3326 // will happen when we are dealing with, e.g., class template
3327 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003328 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003329 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003330 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003331 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003332 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003333 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003334 << Template;
3335 }
3336
3337 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3338 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003339 true,
3340 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003341 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003342}
3343
Douglas Gregor02024a92010-03-28 02:42:43 +00003344/// \brief Given a non-type template argument that refers to a
3345/// declaration and the type of its corresponding non-type template
3346/// parameter, produce an expression that properly refers to that
3347/// declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00003348ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003349Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3350 QualType ParamType,
3351 SourceLocation Loc) {
3352 assert(Arg.getKind() == TemplateArgument::Declaration &&
3353 "Only declaration template arguments permitted here");
3354 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3355
3356 if (VD->getDeclContext()->isRecord() &&
3357 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3358 // If the value is a class member, we might have a pointer-to-member.
3359 // Determine whether the non-type template template parameter is of
3360 // pointer-to-member type. If so, we need to build an appropriate
3361 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3362 // would refer to the member itself.
3363 if (ParamType->isMemberPointerType()) {
3364 QualType ClassType
3365 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3366 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00003367 = NestedNameSpecifier::Create(Context, 0, false,
3368 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00003369 CXXScopeSpec SS;
3370 SS.setScopeRep(Qualifier);
John McCalldfa1edb2010-11-23 20:48:44 +00003371
3372 // The actual value-ness of this is unimportant, but for
3373 // internal consistency's sake, references to instance methods
3374 // are r-values.
3375 ExprValueKind VK = VK_LValue;
3376 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
3377 VK = VK_RValue;
3378
John McCall60d7b3a2010-08-24 06:29:42 +00003379 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCallf89e55a2010-11-18 06:31:45 +00003380 VD->getType().getNonReferenceType(),
John McCalldfa1edb2010-11-23 20:48:44 +00003381 VK,
John McCallf89e55a2010-11-18 06:31:45 +00003382 Loc,
3383 &SS);
Douglas Gregor02024a92010-03-28 02:42:43 +00003384 if (RefExpr.isInvalid())
3385 return ExprError();
3386
John McCall2de56d12010-08-25 11:45:40 +00003387 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorc0c83002010-04-30 21:46:38 +00003388
3389 // We might need to perform a trailing qualification conversion, since
3390 // the element type on the parameter could be more qualified than the
3391 // element type in the expression we constructed.
3392 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3393 ParamType.getUnqualifiedType())) {
3394 Expr *RefE = RefExpr.takeAs<Expr>();
John McCall2de56d12010-08-25 11:45:40 +00003395 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorc0c83002010-04-30 21:46:38 +00003396 RefExpr = Owned(RefE);
3397 }
3398
Douglas Gregor02024a92010-03-28 02:42:43 +00003399 assert(!RefExpr.isInvalid() &&
3400 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003401 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003402 return move(RefExpr);
3403 }
3404 }
3405
3406 QualType T = VD->getType().getNonReferenceType();
3407 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003408 // When the non-type template parameter is a pointer, take the
3409 // address of the declaration.
John McCallf89e55a2010-11-18 06:31:45 +00003410 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003411 if (RefExpr.isInvalid())
3412 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003413
3414 if (T->isFunctionType() || T->isArrayType()) {
3415 // Decay functions and arrays.
3416 Expr *RefE = (Expr *)RefExpr.get();
3417 DefaultFunctionArrayConversion(RefE);
3418 if (RefE != RefExpr.get()) {
3419 RefExpr.release();
3420 RefExpr = Owned(RefE);
3421 }
3422
3423 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003424 }
3425
Douglas Gregorb7a09262010-04-01 18:32:35 +00003426 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00003427 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00003428 }
3429
John McCallf89e55a2010-11-18 06:31:45 +00003430 ExprValueKind VK = VK_RValue;
3431
Douglas Gregor02024a92010-03-28 02:42:43 +00003432 // If the non-type template parameter has reference type, qualify the
3433 // resulting declaration reference with the extra qualifiers on the
3434 // type that the reference refers to.
John McCallf89e55a2010-11-18 06:31:45 +00003435 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
3436 VK = VK_LValue;
3437 T = Context.getQualifiedType(T,
3438 TargetRef->getPointeeType().getQualifiers());
3439 }
Douglas Gregor02024a92010-03-28 02:42:43 +00003440
John McCallf89e55a2010-11-18 06:31:45 +00003441 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003442}
3443
3444/// \brief Construct a new expression that refers to the given
3445/// integral template argument with the given source-location
3446/// information.
3447///
3448/// This routine takes care of the mapping from an integral template
3449/// argument (which may have any integral type) to the appropriate
3450/// literal value.
John McCall60d7b3a2010-08-24 06:29:42 +00003451ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003452Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3453 SourceLocation Loc) {
3454 assert(Arg.getKind() == TemplateArgument::Integral &&
3455 "Operation is only value for integral template arguments");
3456 QualType T = Arg.getIntegralType();
3457 if (T->isCharType() || T->isWideCharType())
3458 return Owned(new (Context) CharacterLiteral(
3459 Arg.getAsIntegral()->getZExtValue(),
3460 T->isWideCharType(),
3461 T,
3462 Loc));
3463 if (T->isBooleanType())
3464 return Owned(new (Context) CXXBoolLiteralExpr(
3465 Arg.getAsIntegral()->getBoolValue(),
3466 T,
3467 Loc));
3468
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003469 return Owned(IntegerLiteral::Create(Context, *Arg.getAsIntegral(), T, Loc));
Douglas Gregor02024a92010-03-28 02:42:43 +00003470}
3471
3472
Douglas Gregorddc29e12009-02-06 22:42:48 +00003473/// \brief Determine whether the given template parameter lists are
3474/// equivalent.
3475///
Mike Stump1eb44332009-09-09 15:08:12 +00003476/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003477/// source code as part of a new template declaration.
3478///
3479/// \param Old The old template parameter list, typically found via
3480/// name lookup of the template declared with this template parameter
3481/// list.
3482///
3483/// \param Complain If true, this routine will produce a diagnostic if
3484/// the template parameter lists are not equivalent.
3485///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003486/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003487///
3488/// \param TemplateArgLoc If this source location is valid, then we
3489/// are actually checking the template parameter list of a template
3490/// argument (New) against the template parameter list of its
3491/// corresponding template template parameter (Old). We produce
3492/// slightly different diagnostics in this scenario.
3493///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003494/// \returns True if the template parameter lists are equal, false
3495/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003496bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003497Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3498 TemplateParameterList *Old,
3499 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003500 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003501 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003502 if (Old->size() != New->size()) {
3503 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003504 unsigned NextDiag = diag::err_template_param_list_different_arity;
3505 if (TemplateArgLoc.isValid()) {
3506 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3507 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003508 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003509 Diag(New->getTemplateLoc(), NextDiag)
3510 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003511 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003512 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003513 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003514 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003515 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3516 }
3517
3518 return false;
3519 }
3520
3521 for (TemplateParameterList::iterator OldParm = Old->begin(),
3522 OldParmEnd = Old->end(), NewParm = New->begin();
3523 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3524 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003525 if (Complain) {
3526 unsigned NextDiag = diag::err_template_param_different_kind;
3527 if (TemplateArgLoc.isValid()) {
3528 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3529 NextDiag = diag::note_template_param_different_kind;
3530 }
3531 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003532 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003533 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003534 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003535 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003536 return false;
3537 }
3538
Douglas Gregora417b872010-06-04 08:34:32 +00003539 if (TemplateTypeParmDecl *OldTTP
3540 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3541 // Template type parameters are equivalent if either both are template
3542 // type parameter packs or neither are (since we know we're at the same
3543 // index).
3544 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3545 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3546 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3547 // allow one to match a template parameter pack in the template
3548 // parameter list of a template template parameter to one or more
3549 // template parameters in the template parameter list of the
3550 // corresponding template template argument.
3551 if (Complain) {
3552 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3553 if (TemplateArgLoc.isValid()) {
3554 Diag(TemplateArgLoc,
3555 diag::err_template_arg_template_params_mismatch);
3556 NextDiag = diag::note_template_parameter_pack_non_pack;
3557 }
3558 Diag(NewTTP->getLocation(), NextDiag)
3559 << 0 << NewTTP->isParameterPack();
3560 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3561 << 0 << OldTTP->isParameterPack();
3562 }
3563 return false;
3564 }
Mike Stump1eb44332009-09-09 15:08:12 +00003565 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003566 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3567 // The types of non-type template parameters must agree.
3568 NonTypeTemplateParmDecl *NewNTTP
3569 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003570
3571 // If we are matching a template template argument to a template
3572 // template parameter and one of the non-type template parameter types
3573 // is dependent, then we must wait until template instantiation time
3574 // to actually compare the arguments.
3575 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3576 (OldNTTP->getType()->isDependentType() ||
3577 NewNTTP->getType()->isDependentType()))
3578 continue;
3579
Douglas Gregorddc29e12009-02-06 22:42:48 +00003580 if (Context.getCanonicalType(OldNTTP->getType()) !=
3581 Context.getCanonicalType(NewNTTP->getType())) {
3582 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003583 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3584 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003585 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003586 diag::err_template_arg_template_params_mismatch);
3587 NextDiag = diag::note_template_nontype_parm_different_type;
3588 }
3589 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003590 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003591 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003592 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003593 diag::note_template_nontype_parm_prev_declaration)
3594 << OldNTTP->getType();
3595 }
3596 return false;
3597 }
3598 } else {
3599 // The template parameter lists of template template
3600 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003601 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003602 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003603 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003604 = cast<TemplateTemplateParmDecl>(*OldParm);
3605 TemplateTemplateParmDecl *NewTTP
3606 = cast<TemplateTemplateParmDecl>(*NewParm);
3607 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3608 OldTTP->getTemplateParameters(),
3609 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003610 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003611 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003612 return false;
3613 }
3614 }
3615
3616 return true;
3617}
3618
3619/// \brief Check whether a template can be declared within this scope.
3620///
3621/// If the template declaration is valid in this scope, returns
3622/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003623bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003624Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003625 // Find the nearest enclosing declaration scope.
3626 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3627 (S->getFlags() & Scope::TemplateParamScope) != 0)
3628 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003629
Douglas Gregorddc29e12009-02-06 22:42:48 +00003630 // C++ [temp]p2:
3631 // A template-declaration can appear only as a namespace scope or
3632 // class scope declaration.
3633 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003634 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3635 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003636 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003637 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003638
Eli Friedman1503f772009-07-31 01:43:05 +00003639 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003640 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003641
3642 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3643 return false;
3644
Mike Stump1eb44332009-09-09 15:08:12 +00003645 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003646 diag::err_template_outside_namespace_or_class_scope)
3647 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003648}
Douglas Gregorcc636682009-02-17 23:15:12 +00003649
Douglas Gregord5cb8762009-10-07 00:13:32 +00003650/// \brief Determine what kind of template specialization the given declaration
3651/// is.
3652static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3653 if (!D)
3654 return TSK_Undeclared;
3655
Douglas Gregorf6b11852009-10-08 15:14:33 +00003656 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3657 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003658 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3659 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003660 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3661 return Var->getTemplateSpecializationKind();
3662
Douglas Gregord5cb8762009-10-07 00:13:32 +00003663 return TSK_Undeclared;
3664}
3665
Douglas Gregor9302da62009-10-14 23:50:59 +00003666/// \brief Check whether a specialization is well-formed in the current
3667/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003668///
Douglas Gregor9302da62009-10-14 23:50:59 +00003669/// This routine determines whether a template specialization can be declared
3670/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003671///
3672/// \param S the semantic analysis object for which this check is being
3673/// performed.
3674///
3675/// \param Specialized the entity being specialized or instantiated, which
3676/// may be a kind of template (class template, function template, etc.) or
3677/// a member of a class template (member function, static data member,
3678/// member class).
3679///
3680/// \param PrevDecl the previous declaration of this entity, if any.
3681///
3682/// \param Loc the location of the explicit specialization or instantiation of
3683/// this entity.
3684///
3685/// \param IsPartialSpecialization whether this is a partial specialization of
3686/// a class template.
3687///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003688/// \returns true if there was an error that we cannot recover from, false
3689/// otherwise.
3690static bool CheckTemplateSpecializationScope(Sema &S,
3691 NamedDecl *Specialized,
3692 NamedDecl *PrevDecl,
3693 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003694 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003695 // Keep these "kind" numbers in sync with the %select statements in the
3696 // various diagnostics emitted by this routine.
3697 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003698 bool isTemplateSpecialization = false;
3699 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003700 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003701 isTemplateSpecialization = true;
3702 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003703 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003704 isTemplateSpecialization = true;
3705 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003706 EntityKind = 3;
3707 else if (isa<VarDecl>(Specialized))
3708 EntityKind = 4;
3709 else if (isa<RecordDecl>(Specialized))
3710 EntityKind = 5;
3711 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003712 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3713 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003714 return true;
3715 }
3716
Douglas Gregor88b70942009-02-25 22:02:03 +00003717 // C++ [temp.expl.spec]p2:
3718 // An explicit specialization shall be declared in the namespace
3719 // of which the template is a member, or, for member templates, in
3720 // the namespace of which the enclosing class or enclosing class
3721 // template is a member. An explicit specialization of a member
3722 // function, member class or static data member of a class
3723 // template shall be declared in the namespace of which the class
3724 // template is a member. Such a declaration may also be a
3725 // definition. If the declaration is not a definition, the
3726 // specialization may be defined later in the name- space in which
3727 // the explicit specialization was declared, or in a namespace
3728 // that encloses the one in which the explicit specialization was
3729 // declared.
Sebastian Redl7a126a42010-08-31 00:36:30 +00003730 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003731 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003732 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003733 return true;
3734 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003735
Douglas Gregor0a407472009-10-07 17:30:37 +00003736 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3737 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003738 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003739 return true;
3740 }
3741
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003742 // C++ [temp.class.spec]p6:
3743 // A class template partial specialization may be declared or redeclared
3744 // in any namespace scope in which its definition may be defined (14.5.1
3745 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003746 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003747 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003748 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003749 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003750 if ((!PrevDecl ||
3751 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3752 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregor121dc9a2010-09-12 05:08:28 +00003753 // C++ [temp.exp.spec]p2:
3754 // An explicit specialization shall be declared in the namespace of which
3755 // the template is a member, or, for member templates, in the namespace
3756 // of which the enclosing class or enclosing class template is a member.
3757 // An explicit specialization of a member function, member class or
3758 // static data member of a class template shall be declared in the
3759 // namespace of which the class template is a member.
3760 //
3761 // C++0x [temp.expl.spec]p2:
3762 // An explicit specialization shall be declared in a namespace enclosing
3763 // the specialized template.
3764 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3765 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregora4d5de52010-09-12 05:24:55 +00003766 bool IsCPlusPlus0xExtension
3767 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003768 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003769 S.Diag(Loc, IsCPlusPlus0xExtension
3770 ? diag::ext_template_spec_decl_out_of_scope_global
3771 : diag::err_template_spec_decl_out_of_scope_global)
3772 << EntityKind << Specialized;
Douglas Gregor9302da62009-10-14 23:50:59 +00003773 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003774 S.Diag(Loc, IsCPlusPlus0xExtension
3775 ? diag::ext_template_spec_decl_out_of_scope
3776 : diag::err_template_spec_decl_out_of_scope)
3777 << EntityKind << Specialized
3778 << cast<NamedDecl>(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003779
3780 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3781 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003782 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003783 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003784
3785 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003786 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003787 // Note that HandleDeclarator() performs this check for explicit
3788 // specializations of function templates, static data members, and member
3789 // functions, so we skip the check here for those kinds of entities.
3790 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003791 // Should we refactor that check, so that it occurs later?
3792 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003793 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3794 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003795 if (isa<TranslationUnitDecl>(SpecializedContext))
3796 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3797 << EntityKind << Specialized;
3798 else if (isa<NamespaceDecl>(SpecializedContext))
3799 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3800 << EntityKind << Specialized
3801 << cast<NamedDecl>(SpecializedContext);
3802
Douglas Gregor9302da62009-10-14 23:50:59 +00003803 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003804 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003805
3806 // FIXME: check for specialization-after-instantiation errors and such.
3807
Douglas Gregor88b70942009-02-25 22:02:03 +00003808 return false;
3809}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003810
Douglas Gregore94866f2009-06-12 21:21:02 +00003811/// \brief Check the non-type template arguments of a class template
3812/// partial specialization according to C++ [temp.class.spec]p9.
3813///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003814/// \param TemplateParams the template parameters of the primary class
3815/// template.
3816///
3817/// \param TemplateArg the template arguments of the class template
3818/// partial specialization.
3819///
3820/// \param MirrorsPrimaryTemplate will be set true if the class
3821/// template partial specialization arguments are identical to the
3822/// implicit template arguments of the primary template. This is not
3823/// necessarily an error (C++0x), and it is left to the caller to diagnose
3824/// this condition when it is an error.
3825///
Douglas Gregore94866f2009-06-12 21:21:02 +00003826/// \returns true if there was an error, false otherwise.
3827bool Sema::CheckClassTemplatePartialSpecializationArgs(
3828 TemplateParameterList *TemplateParams,
Douglas Gregor910f8002010-11-07 23:05:16 +00003829 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003830 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003831 // FIXME: the interface to this function will have to change to
3832 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003833 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003834
Douglas Gregor910f8002010-11-07 23:05:16 +00003835 const TemplateArgument *ArgList = TemplateArgs.data();
Mike Stump1eb44332009-09-09 15:08:12 +00003836
Douglas Gregore94866f2009-06-12 21:21:02 +00003837 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003838 // Determine whether the template argument list of the partial
3839 // specialization is identical to the implicit argument list of
3840 // the primary template. The caller may need to diagnostic this as
3841 // an error per C++ [temp.class.spec]p9b3.
3842 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003843 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003844 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3845 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003846 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003847 MirrorsPrimaryTemplate = false;
3848 } else if (TemplateTemplateParmDecl *TTP
3849 = dyn_cast<TemplateTemplateParmDecl>(
3850 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003851 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003852 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003853 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003854 if (!ArgDecl ||
3855 ArgDecl->getIndex() != TTP->getIndex() ||
3856 ArgDecl->getDepth() != TTP->getDepth())
3857 MirrorsPrimaryTemplate = false;
3858 }
3859 }
3860
Mike Stump1eb44332009-09-09 15:08:12 +00003861 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003862 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003863 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003864 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003865 }
3866
Anders Carlsson6360be72009-06-13 18:20:51 +00003867 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003868 if (!ArgExpr) {
3869 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003870 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003871 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003872
3873 // C++ [temp.class.spec]p8:
3874 // A non-type argument is non-specialized if it is the name of a
3875 // non-type parameter. All other non-type arguments are
3876 // specialized.
3877 //
3878 // Below, we check the two conditions that only apply to
3879 // specialized non-type arguments, so skip any non-specialized
3880 // arguments.
3881 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003882 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003883 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003884 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003885 (Param->getIndex() != NTTP->getIndex() ||
3886 Param->getDepth() != NTTP->getDepth()))
3887 MirrorsPrimaryTemplate = false;
3888
Douglas Gregore94866f2009-06-12 21:21:02 +00003889 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003890 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003891
3892 // C++ [temp.class.spec]p9:
3893 // Within the argument list of a class template partial
3894 // specialization, the following restrictions apply:
3895 // -- A partially specialized non-type argument expression
3896 // shall not involve a template parameter of the partial
3897 // specialization except when the argument expression is a
3898 // simple identifier.
3899 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003900 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003901 diag::err_dependent_non_type_arg_in_partial_spec)
3902 << ArgExpr->getSourceRange();
3903 return true;
3904 }
3905
3906 // -- The type of a template parameter corresponding to a
3907 // specialized non-type argument shall not be dependent on a
3908 // parameter of the specialization.
3909 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003910 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003911 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3912 << Param->getType()
3913 << ArgExpr->getSourceRange();
3914 Diag(Param->getLocation(), diag::note_template_param_here);
3915 return true;
3916 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003917
3918 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003919 }
3920
3921 return false;
3922}
3923
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003924/// \brief Retrieve the previous declaration of the given declaration.
3925static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3926 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3927 return VD->getPreviousDeclaration();
3928 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3929 return FD->getPreviousDeclaration();
3930 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3931 return TD->getPreviousDeclaration();
3932 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3933 return TD->getPreviousDeclaration();
3934 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3935 return FTD->getPreviousDeclaration();
3936 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3937 return CTD->getPreviousDeclaration();
3938 return 0;
3939}
3940
John McCalld226f652010-08-21 09:40:31 +00003941DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003942Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3943 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003944 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003945 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003946 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003947 SourceLocation TemplateNameLoc,
3948 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003949 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003950 SourceLocation RAngleLoc,
3951 AttributeList *Attr,
3952 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003953 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003954
Douglas Gregorcc636682009-02-17 23:15:12 +00003955 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003956 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003957 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003958 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3959
3960 if (!ClassTemplate) {
3961 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3962 << (Name.getAsTemplateDecl() &&
3963 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3964 return true;
3965 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003966
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003967 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003968 bool isPartialSpecialization = false;
3969
Douglas Gregor88b70942009-02-25 22:02:03 +00003970 // Check the validity of the template headers that introduce this
3971 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003972 // FIXME: We probably shouldn't complain about these headers for
3973 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003974 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00003975 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003976 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3977 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003978 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00003979 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003980 isExplicitSpecialization,
3981 Invalid);
3982 if (Invalid)
3983 return true;
3984
Abramo Bagnara9b934882010-06-12 08:15:14 +00003985 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3986 if (TemplateParams)
3987 --NumMatchedTemplateParamLists;
3988
Douglas Gregor05396e22009-08-25 17:23:04 +00003989 if (TemplateParams && TemplateParams->size() > 0) {
3990 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003991
Douglas Gregor05396e22009-08-25 17:23:04 +00003992 // C++ [temp.class.spec]p10:
3993 // The template parameter list of a specialization shall not
3994 // contain default template argument values.
3995 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3996 Decl *Param = TemplateParams->getParam(I);
3997 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3998 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003999 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004000 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00004001 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004002 }
4003 } else if (NonTypeTemplateParmDecl *NTTP
4004 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4005 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004006 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004007 diag::err_default_arg_in_partial_spec)
4008 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004009 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004010 }
4011 } else {
4012 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00004013 if (TTP->hasDefaultArgument()) {
4014 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004015 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00004016 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004017 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004018 }
4019 }
4020 }
Douglas Gregora735b202009-10-13 14:39:41 +00004021 } else if (TemplateParams) {
4022 if (TUK == TUK_Friend)
4023 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00004024 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00004025 SourceRange(TemplateParams->getTemplateLoc(),
4026 TemplateParams->getRAngleLoc()))
4027 << SourceRange(LAngleLoc, RAngleLoc);
4028 else
4029 isExplicitSpecialization = true;
4030 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00004031 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00004032 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004033 isExplicitSpecialization = true;
4034 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004035
Douglas Gregorcc636682009-02-17 23:15:12 +00004036 // Check that the specialization uses the same tag kind as the
4037 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004038 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4039 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004040 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004041 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004042 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004043 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00004044 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004045 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00004046 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004047 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004048 diag::note_previous_use);
4049 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4050 }
4051
Douglas Gregor40808ce2009-03-09 23:48:35 +00004052 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004053 TemplateArgumentListInfo TemplateArgs;
4054 TemplateArgs.setLAngleLoc(LAngleLoc);
4055 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004056 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00004057
Douglas Gregorcc636682009-02-17 23:15:12 +00004058 // Check that the template argument list is well-formed for this
4059 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00004060 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00004061 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4062 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004063 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004064
Douglas Gregor910f8002010-11-07 23:05:16 +00004065 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregorcc636682009-02-17 23:15:12 +00004066 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004067
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004068 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00004069 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004070 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004071 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00004072 if (CheckClassTemplatePartialSpecializationArgs(
4073 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00004074 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00004075 return true;
4076
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004077 if (MirrorsPrimaryTemplate) {
4078 // C++ [temp.class.spec]p9b3:
4079 //
Mike Stump1eb44332009-09-09 15:08:12 +00004080 // -- The argument list of the specialization shall not be identical
4081 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004082 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00004083 << (TUK == TUK_Definition)
Douglas Gregor849b2432010-03-31 17:46:05 +00004084 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00004085 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004086 ClassTemplate->getIdentifier(),
4087 TemplateNameLoc,
4088 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00004089 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004090 AS_none);
4091 }
4092
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004093 // FIXME: Diagnose friend partial specializations
4094
Douglas Gregorde090962010-02-09 00:37:32 +00004095 if (!Name.isDependent() &&
4096 !TemplateSpecializationType::anyDependentTemplateArguments(
4097 TemplateArgs.getArgumentArray(),
4098 TemplateArgs.size())) {
4099 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4100 << ClassTemplate->getDeclName();
4101 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00004102 }
4103 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004104
Douglas Gregorcc636682009-02-17 23:15:12 +00004105 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004106 ClassTemplateSpecializationDecl *PrevDecl = 0;
4107
4108 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004109 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004110 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004111 = ClassTemplate->findPartialSpecialization(Converted.data(),
4112 Converted.size(),
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004113 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004114 else
4115 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004116 = ClassTemplate->findSpecialization(Converted.data(),
4117 Converted.size(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00004118
4119 ClassTemplateSpecializationDecl *Specialization = 0;
4120
Douglas Gregor88b70942009-02-25 22:02:03 +00004121 // Check whether we can declare a class template specialization in
4122 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004123 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00004124 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00004125 TemplateNameLoc,
4126 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004127 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004128
Douglas Gregorb88e8882009-07-30 17:40:51 +00004129 // The canonical type
4130 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004131 if (PrevDecl &&
4132 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00004133 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004134 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004135 // arguments was referenced but not declared, or we're only
4136 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00004137 // declaration node as our own, updating its source location to
4138 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004139 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004140 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00004141 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00004142 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004143 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00004144 // Build the canonical type that describes the converted template
4145 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00004146 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4147 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004148 Converted.data(),
4149 Converted.size());
Douglas Gregorb88e8882009-07-30 17:40:51 +00004150
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004151 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004152 ClassTemplatePartialSpecializationDecl *PrevPartial
4153 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004154 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004155 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00004156 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00004157 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004158 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00004159 TemplateNameLoc,
4160 TemplateParams,
4161 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004162 Converted.data(),
4163 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00004164 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00004165 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004166 PrevPartial,
4167 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00004168 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004169 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004170 Partial->setTemplateParameterListsInfo(Context,
4171 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004172 (TemplateParameterList**) TemplateParameterLists.release());
4173 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004174
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004175 if (!PrevPartial)
4176 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004177 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00004178
Douglas Gregored9c0f92009-10-29 00:04:11 +00004179 // If we are providing an explicit specialization of a member class
4180 // template specialization, make a note of that.
4181 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4182 PrevPartial->setMemberSpecialization();
4183
Douglas Gregor031a5882009-06-13 00:26:55 +00004184 // Check that all of the template parameters of the class template
4185 // partial specialization are deducible from the template
4186 // arguments. If not, this class template partial specialization
4187 // will never be used.
4188 llvm::SmallVector<bool, 8> DeducibleParams;
4189 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00004190 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004191 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00004192 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00004193 unsigned NumNonDeducible = 0;
4194 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4195 if (!DeducibleParams[I])
4196 ++NumNonDeducible;
4197
4198 if (NumNonDeducible) {
4199 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4200 << (NumNonDeducible > 1)
4201 << SourceRange(TemplateNameLoc, RAngleLoc);
4202 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4203 if (!DeducibleParams[I]) {
4204 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4205 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00004206 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004207 diag::note_partial_spec_unused_parameter)
4208 << Param->getDeclName();
4209 else
Mike Stump1eb44332009-09-09 15:08:12 +00004210 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004211 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00004212 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00004213 }
4214 }
4215 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004216 } else {
4217 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004218 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004219 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004220 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00004221 ClassTemplate->getDeclContext(),
4222 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004223 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004224 Converted.data(),
4225 Converted.size(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004226 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004227 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004228 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004229 Specialization->setTemplateParameterListsInfo(Context,
4230 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004231 (TemplateParameterList**) TemplateParameterLists.release());
4232 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004233
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004234 if (!PrevDecl)
4235 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00004236
4237 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004238 }
4239
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004240 // C++ [temp.expl.spec]p6:
4241 // If a template, a member template or the member of a class template is
4242 // explicitly specialized then that specialization shall be declared
4243 // before the first use of that specialization that would cause an implicit
4244 // instantiation to take place, in every translation unit in which such a
4245 // use occurs; no diagnostic is required.
4246 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004247 bool Okay = false;
4248 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4249 // Is there any previous explicit specialization declaration?
4250 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4251 Okay = true;
4252 break;
4253 }
4254 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004255
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004256 if (!Okay) {
4257 SourceRange Range(TemplateNameLoc, RAngleLoc);
4258 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4259 << Context.getTypeDeclType(Specialization) << Range;
4260
4261 Diag(PrevDecl->getPointOfInstantiation(),
4262 diag::note_instantiation_required_here)
4263 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004264 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004265 return true;
4266 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004267 }
4268
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004269 // If this is not a friend, note that this is an explicit specialization.
4270 if (TUK != TUK_Friend)
4271 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004272
4273 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004274 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00004275 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004276 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004277 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004278 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00004279 Diag(Def->getLocation(), diag::note_previous_definition);
4280 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00004281 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004282 }
4283 }
4284
Douglas Gregorfc705b82009-02-26 22:19:44 +00004285 // Build the fully-sugared type for this class template
4286 // specialization as the user wrote in the specialization
4287 // itself. This means that we'll pretty-print the type retrieved
4288 // from the specialization's declaration the way that the user
4289 // actually wrote the specialization, rather than formatting the
4290 // name based on the "canonical" representation used to store the
4291 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004292 TypeSourceInfo *WrittenTy
4293 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4294 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004295 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004296 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor7e9b57b2010-07-06 18:33:12 +00004297 if (TemplateParams)
4298 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004299 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00004300 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00004301
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004302 // C++ [temp.expl.spec]p9:
4303 // A template explicit specialization is in the scope of the
4304 // namespace in which the template was defined.
4305 //
4306 // We actually implement this paragraph where we set the semantic
4307 // context (in the creation of the ClassTemplateSpecializationDecl),
4308 // but we also maintain the lexical context where the actual
4309 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00004310 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004311
Douglas Gregorcc636682009-02-17 23:15:12 +00004312 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004313 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00004314 Specialization->startDefinition();
4315
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004316 if (TUK == TUK_Friend) {
4317 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4318 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00004319 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004320 /*FIXME:*/KWLoc);
4321 Friend->setAccess(AS_public);
4322 CurContext->addDecl(Friend);
4323 } else {
4324 // Add the specialization into its lexical context, so that it can
4325 // be seen when iterating through the list of declarations in that
4326 // context. However, specializations are not found by name lookup.
4327 CurContext->addDecl(Specialization);
4328 }
John McCalld226f652010-08-21 09:40:31 +00004329 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00004330}
Douglas Gregord57959a2009-03-27 23:10:48 +00004331
John McCalld226f652010-08-21 09:40:31 +00004332Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00004333 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004334 Declarator &D) {
Douglas Gregore542c862009-06-23 23:11:28 +00004335 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4336}
4337
John McCalld226f652010-08-21 09:40:31 +00004338Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004339 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004340 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00004341 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004342 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00004343
Douglas Gregor52591bf2009-06-24 00:54:41 +00004344 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004345 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00004346 }
Mike Stump1eb44332009-09-09 15:08:12 +00004347
Douglas Gregor52591bf2009-06-24 00:54:41 +00004348 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004349
John McCalld226f652010-08-21 09:40:31 +00004350 Decl *DP = HandleDeclarator(ParentScope, D,
4351 move(TemplateParameterLists),
4352 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004353 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00004354 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00004355 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00004356 FunctionTemplate->getTemplatedDecl());
4357 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4358 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4359 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00004360}
4361
John McCall75042392010-02-11 01:33:53 +00004362/// \brief Strips various properties off an implicit instantiation
4363/// that has just been explicitly specialized.
4364static void StripImplicitInstantiation(NamedDecl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00004365 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00004366
4367 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4368 FD->setInlineSpecified(false);
4369 }
4370}
4371
Douglas Gregor454885e2009-10-15 15:54:05 +00004372/// \brief Diagnose cases where we have an explicit template specialization
4373/// before/after an explicit template instantiation, producing diagnostics
4374/// for those cases where they are required and determining whether the
4375/// new specialization/instantiation will have any effect.
4376///
Douglas Gregor454885e2009-10-15 15:54:05 +00004377/// \param NewLoc the location of the new explicit specialization or
4378/// instantiation.
4379///
4380/// \param NewTSK the kind of the new explicit specialization or instantiation.
4381///
4382/// \param PrevDecl the previous declaration of the entity.
4383///
4384/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4385///
4386/// \param PrevPointOfInstantiation if valid, indicates where the previus
4387/// declaration was instantiated (either implicitly or explicitly).
4388///
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004389/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00004390/// specialization or instantiation has no effect and should be ignored.
4391///
4392/// \returns true if there was an error that should prevent the introduction of
4393/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004394bool
4395Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4396 TemplateSpecializationKind NewTSK,
4397 NamedDecl *PrevDecl,
4398 TemplateSpecializationKind PrevTSK,
4399 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004400 bool &HasNoEffect) {
4401 HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004402
4403 switch (NewTSK) {
4404 case TSK_Undeclared:
4405 case TSK_ImplicitInstantiation:
4406 assert(false && "Don't check implicit instantiations here");
4407 return false;
4408
4409 case TSK_ExplicitSpecialization:
4410 switch (PrevTSK) {
4411 case TSK_Undeclared:
4412 case TSK_ExplicitSpecialization:
4413 // Okay, we're just specializing something that is either already
4414 // explicitly specialized or has merely been mentioned without any
4415 // instantiation.
4416 return false;
4417
4418 case TSK_ImplicitInstantiation:
4419 if (PrevPointOfInstantiation.isInvalid()) {
4420 // The declaration itself has not actually been instantiated, so it is
4421 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004422 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004423 return false;
4424 }
4425 // Fall through
4426
4427 case TSK_ExplicitInstantiationDeclaration:
4428 case TSK_ExplicitInstantiationDefinition:
4429 assert((PrevTSK == TSK_ImplicitInstantiation ||
4430 PrevPointOfInstantiation.isValid()) &&
4431 "Explicit instantiation without point of instantiation?");
4432
4433 // C++ [temp.expl.spec]p6:
4434 // If a template, a member template or the member of a class template
4435 // is explicitly specialized then that specialization shall be declared
4436 // before the first use of that specialization that would cause an
4437 // implicit instantiation to take place, in every translation unit in
4438 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004439 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4440 // Is there any previous explicit specialization declaration?
4441 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4442 return false;
4443 }
4444
Douglas Gregor0d035142009-10-27 18:42:08 +00004445 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004446 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004447 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004448 << (PrevTSK != TSK_ImplicitInstantiation);
4449
4450 return true;
4451 }
4452 break;
4453
4454 case TSK_ExplicitInstantiationDeclaration:
4455 switch (PrevTSK) {
4456 case TSK_ExplicitInstantiationDeclaration:
4457 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004458 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004459 return false;
4460
4461 case TSK_Undeclared:
4462 case TSK_ImplicitInstantiation:
4463 // We're explicitly instantiating something that may have already been
4464 // implicitly instantiated; that's fine.
4465 return false;
4466
4467 case TSK_ExplicitSpecialization:
4468 // C++0x [temp.explicit]p4:
4469 // For a given set of template parameters, if an explicit instantiation
4470 // of a template appears after a declaration of an explicit
4471 // specialization for that template, the explicit instantiation has no
4472 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004473 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004474 return false;
4475
4476 case TSK_ExplicitInstantiationDefinition:
4477 // C++0x [temp.explicit]p10:
4478 // If an entity is the subject of both an explicit instantiation
4479 // declaration and an explicit instantiation definition in the same
4480 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004481 Diag(NewLoc,
4482 diag::err_explicit_instantiation_declaration_after_definition);
4483 Diag(PrevPointOfInstantiation,
4484 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004485 assert(PrevPointOfInstantiation.isValid() &&
4486 "Explicit instantiation without point of instantiation?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004487 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004488 return false;
4489 }
4490 break;
4491
4492 case TSK_ExplicitInstantiationDefinition:
4493 switch (PrevTSK) {
4494 case TSK_Undeclared:
4495 case TSK_ImplicitInstantiation:
4496 // We're explicitly instantiating something that may have already been
4497 // implicitly instantiated; that's fine.
4498 return false;
4499
4500 case TSK_ExplicitSpecialization:
4501 // C++ DR 259, C++0x [temp.explicit]p4:
4502 // For a given set of template parameters, if an explicit
4503 // instantiation of a template appears after a declaration of
4504 // an explicit specialization for that template, the explicit
4505 // instantiation has no effect.
4506 //
4507 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004508 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004509 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004510 if (!getLangOptions().CPlusPlus0x) {
4511 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004512 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004513 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004514 diag::note_previous_template_specialization);
4515 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004516 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004517 return false;
4518
4519 case TSK_ExplicitInstantiationDeclaration:
4520 // We're explicity instantiating a definition for something for which we
4521 // were previously asked to suppress instantiations. That's fine.
4522 return false;
4523
4524 case TSK_ExplicitInstantiationDefinition:
4525 // C++0x [temp.spec]p5:
4526 // For a given template and a given set of template-arguments,
4527 // - an explicit instantiation definition shall appear at most once
4528 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004529 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004530 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004531 Diag(PrevPointOfInstantiation,
4532 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004533 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004534 return false;
4535 }
4536 break;
4537 }
4538
4539 assert(false && "Missing specialization/instantiation case?");
4540
4541 return false;
4542}
4543
John McCallaf2094e2010-04-08 09:05:18 +00004544/// \brief Perform semantic analysis for the given dependent function
4545/// template specialization. The only possible way to get a dependent
4546/// function template specialization is with a friend declaration,
4547/// like so:
4548///
4549/// template <class T> void foo(T);
4550/// template <class T> class A {
4551/// friend void foo<>(T);
4552/// };
4553///
4554/// There really isn't any useful analysis we can do here, so we
4555/// just store the information.
4556bool
4557Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4558 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4559 LookupResult &Previous) {
4560 // Remove anything from Previous that isn't a function template in
4561 // the correct context.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004562 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallaf2094e2010-04-08 09:05:18 +00004563 LookupResult::Filter F = Previous.makeFilter();
4564 while (F.hasNext()) {
4565 NamedDecl *D = F.next()->getUnderlyingDecl();
4566 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl7a126a42010-08-31 00:36:30 +00004567 !FDLookupContext->InEnclosingNamespaceSetOf(
4568 D->getDeclContext()->getRedeclContext()))
John McCallaf2094e2010-04-08 09:05:18 +00004569 F.erase();
4570 }
4571 F.done();
4572
4573 // Should this be diagnosed here?
4574 if (Previous.empty()) return true;
4575
4576 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4577 ExplicitTemplateArgs);
4578 return false;
4579}
4580
Abramo Bagnarae03db982010-05-20 15:32:11 +00004581/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004582/// specialization.
4583///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004584/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004585/// explicit function template specialization. On successful completion,
4586/// the function declaration \p FD will become a function template
4587/// specialization.
4588///
4589/// \param FD the function declaration, which will be updated to become a
4590/// function template specialization.
4591///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004592/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4593/// if any. Note that this may be valid info even when 0 arguments are
4594/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4595/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004596///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004597/// \param PrevDecl the set of declarations that may be specialized by
4598/// this function specialization.
4599bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004600Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004601 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004602 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004603 // The set of function template specializations that could match this
4604 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004605 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004606
Sebastian Redl7a126a42010-08-31 00:36:30 +00004607 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall68263142009-11-18 22:49:29 +00004608 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4609 I != E; ++I) {
4610 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4611 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004612 // Only consider templates found within the same semantic lookup scope as
4613 // FD.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004614 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4615 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004616 continue;
4617
4618 // C++ [temp.expl.spec]p11:
4619 // A trailing template-argument can be left unspecified in the
4620 // template-id naming an explicit function template specialization
4621 // provided it can be deduced from the function argument type.
4622 // Perform template argument deduction to determine whether we may be
4623 // specializing this template.
4624 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004625 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004626 FunctionDecl *Specialization = 0;
4627 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004628 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004629 FD->getType(),
4630 Specialization,
4631 Info)) {
4632 // FIXME: Template argument deduction failed; record why it failed, so
4633 // that we can provide nifty diagnostics.
4634 (void)TDK;
4635 continue;
4636 }
4637
4638 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004639 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004640 }
4641 }
4642
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004643 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004644 UnresolvedSetIterator Result
4645 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4646 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004647 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004648 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004649 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004650 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004651 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004652 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004653 return true;
John McCallc373d482010-01-27 01:50:18 +00004654
4655 // Ignore access information; it doesn't figure into redeclaration checking.
4656 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004657 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004658
4659 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004660 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004661
4662 // If this is a friend declaration, then we're not really declaring
4663 // an explicit specialization.
4664 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004665
Douglas Gregord5cb8762009-10-07 00:13:32 +00004666 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004667 if (!isFriend &&
4668 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004669 Specialization->getPrimaryTemplate(),
4670 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004671 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004672 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004673
4674 // C++ [temp.expl.spec]p6:
4675 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004676 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004677 // before the first use of that specialization that would cause an implicit
4678 // instantiation to take place, in every translation unit in which such a
4679 // use occurs; no diagnostic is required.
4680 FunctionTemplateSpecializationInfo *SpecInfo
4681 = Specialization->getTemplateSpecializationInfo();
4682 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004683
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004684 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00004685 if (!isFriend &&
4686 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004687 TSK_ExplicitSpecialization,
4688 Specialization,
4689 SpecInfo->getTemplateSpecializationKind(),
4690 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004691 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004692 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004693
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004694 // Mark the prior declaration as an explicit specialization, so that later
4695 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004696 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00004697 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004698 MarkUnusedFileScopedDecl(Specialization);
4699 }
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004700
4701 // Turn the given function declaration into a function template
4702 // specialization, with the template arguments from the previous
4703 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004704 // Take copies of (semantic and syntactic) template argument lists.
4705 const TemplateArgumentList* TemplArgs = new (Context)
4706 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4707 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4708 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004709 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004710 TemplArgs, /*InsertPos=*/0,
4711 SpecInfo->getTemplateSpecializationKind(),
4712 TemplArgsAsWritten);
4713
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004714 // The "previous declaration" for this function template specialization is
4715 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004716 Previous.clear();
4717 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004718 return false;
4719}
4720
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004721/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004722/// specialization.
4723///
4724/// This routine performs all of the semantic analysis required for an
4725/// explicit member function specialization. On successful completion,
4726/// the function declaration \p FD will become a member function
4727/// specialization.
4728///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004729/// \param Member the member declaration, which will be updated to become a
4730/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004731///
John McCall68263142009-11-18 22:49:29 +00004732/// \param Previous the set of declarations, one of which may be specialized
4733/// by this function specialization; the set will be modified to contain the
4734/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004735bool
John McCall68263142009-11-18 22:49:29 +00004736Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004737 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004738
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004739 // Try to find the member we are instantiating.
4740 NamedDecl *Instantiation = 0;
4741 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004742 MemberSpecializationInfo *MSInfo = 0;
4743
John McCall68263142009-11-18 22:49:29 +00004744 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004745 // Nowhere to look anyway.
4746 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004747 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4748 I != E; ++I) {
4749 NamedDecl *D = (*I)->getUnderlyingDecl();
4750 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004751 if (Context.hasSameType(Function->getType(), Method->getType())) {
4752 Instantiation = Method;
4753 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004754 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004755 break;
4756 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004757 }
4758 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004759 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004760 VarDecl *PrevVar;
4761 if (Previous.isSingleResult() &&
4762 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004763 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004764 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004765 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004766 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004767 }
4768 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004769 CXXRecordDecl *PrevRecord;
4770 if (Previous.isSingleResult() &&
4771 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4772 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004773 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004774 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004775 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004776 }
4777
4778 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004779 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004780 // specializations are always out-of-line, the caller will complain about
4781 // this mismatch later.
4782 return false;
4783 }
John McCall77e8b112010-04-13 20:37:33 +00004784
4785 // If this is a friend, just bail out here before we start turning
4786 // things into explicit specializations.
4787 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4788 // Preserve instantiation information.
4789 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4790 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4791 cast<CXXMethodDecl>(InstantiatedFrom),
4792 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4793 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4794 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4795 cast<CXXRecordDecl>(InstantiatedFrom),
4796 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4797 }
4798
4799 Previous.clear();
4800 Previous.addDecl(Instantiation);
4801 return false;
4802 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004803
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004804 // Make sure that this is a specialization of a member.
4805 if (!InstantiatedFrom) {
4806 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4807 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004808 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4809 return true;
4810 }
4811
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004812 // C++ [temp.expl.spec]p6:
4813 // If a template, a member template or the member of a class template is
4814 // explicitly specialized then that spe- cialization shall be declared
4815 // before the first use of that specialization that would cause an implicit
4816 // instantiation to take place, in every translation unit in which such a
4817 // use occurs; no diagnostic is required.
4818 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004819
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004820 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00004821 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4822 TSK_ExplicitSpecialization,
4823 Instantiation,
4824 MSInfo->getTemplateSpecializationKind(),
4825 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004826 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004827 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004828
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004829 // Check the scope of this explicit specialization.
4830 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004831 InstantiatedFrom,
4832 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004833 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004834 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004835
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004836 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004837 // the original declaration to note that it is an explicit specialization
4838 // (if it was previously an implicit instantiation). This latter step
4839 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004840 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004841 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4842 if (InstantiationFunction->getTemplateSpecializationKind() ==
4843 TSK_ImplicitInstantiation) {
4844 InstantiationFunction->setTemplateSpecializationKind(
4845 TSK_ExplicitSpecialization);
4846 InstantiationFunction->setLocation(Member->getLocation());
4847 }
4848
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004849 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4850 cast<CXXMethodDecl>(InstantiatedFrom),
4851 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004852 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004853 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004854 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4855 if (InstantiationVar->getTemplateSpecializationKind() ==
4856 TSK_ImplicitInstantiation) {
4857 InstantiationVar->setTemplateSpecializationKind(
4858 TSK_ExplicitSpecialization);
4859 InstantiationVar->setLocation(Member->getLocation());
4860 }
4861
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004862 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4863 cast<VarDecl>(InstantiatedFrom),
4864 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004865 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004866 } else {
4867 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004868 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4869 if (InstantiationClass->getTemplateSpecializationKind() ==
4870 TSK_ImplicitInstantiation) {
4871 InstantiationClass->setTemplateSpecializationKind(
4872 TSK_ExplicitSpecialization);
4873 InstantiationClass->setLocation(Member->getLocation());
4874 }
4875
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004876 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004877 cast<CXXRecordDecl>(InstantiatedFrom),
4878 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004879 }
4880
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004881 // Save the caller the trouble of having to figure out which declaration
4882 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004883 Previous.clear();
4884 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004885 return false;
4886}
4887
Douglas Gregor558c0322009-10-14 23:41:34 +00004888/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00004889///
4890/// \returns true if a serious error occurs, false otherwise.
4891static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00004892 SourceLocation InstLoc,
4893 bool WasQualifiedName) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00004894 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
4895 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregor558c0322009-10-14 23:41:34 +00004896
Douglas Gregor669eed82010-07-13 00:10:04 +00004897 if (CurContext->isRecord()) {
4898 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4899 << D;
4900 return true;
4901 }
4902
Douglas Gregor558c0322009-10-14 23:41:34 +00004903 // C++0x [temp.explicit]p2:
4904 // An explicit instantiation shall appear in an enclosing namespace of its
4905 // template.
4906 //
4907 // This is DR275, which we do not retroactively apply to C++98/03.
4908 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004909 !CurContext->Encloses(OrigContext)) {
4910 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00004911 S.Diag(InstLoc,
4912 S.getLangOptions().CPlusPlus0x?
4913 diag::err_explicit_instantiation_out_of_scope
4914 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004915 << D << NS;
4916 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00004917 S.Diag(InstLoc,
4918 S.getLangOptions().CPlusPlus0x?
4919 diag::err_explicit_instantiation_must_be_global
4920 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004921 << D;
4922 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00004923 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00004924 }
Sebastian Redl7a126a42010-08-31 00:36:30 +00004925
Douglas Gregor558c0322009-10-14 23:41:34 +00004926 // C++0x [temp.explicit]p2:
4927 // If the name declared in the explicit instantiation is an unqualified
4928 // name, the explicit instantiation shall appear in the namespace where
4929 // its template is declared or, if that namespace is inline (7.3.1), any
4930 // namespace from its enclosing namespace set.
4931 if (WasQualifiedName)
Douglas Gregor669eed82010-07-13 00:10:04 +00004932 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004933
4934 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor669eed82010-07-13 00:10:04 +00004935 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004936
Douglas Gregor2166beb2010-05-11 17:39:34 +00004937 S.Diag(InstLoc,
4938 S.getLangOptions().CPlusPlus0x?
4939 diag::err_explicit_instantiation_unqualified_wrong_namespace
4940 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl7a126a42010-08-31 00:36:30 +00004941 << D << OrigContext;
Douglas Gregor558c0322009-10-14 23:41:34 +00004942 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00004943 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00004944}
4945
4946/// \brief Determine whether the given scope specifier has a template-id in it.
4947static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4948 if (!SS.isSet())
4949 return false;
4950
4951 // C++0x [temp.explicit]p2:
4952 // If the explicit instantiation is for a member function, a member class
4953 // or a static data member of a class template specialization, the name of
4954 // the class template specialization in the qualified-id for the member
4955 // name shall be a simple-template-id.
4956 //
4957 // C++98 has the same restriction, just worded differently.
4958 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4959 NNS; NNS = NNS->getPrefix())
4960 if (Type *T = NNS->getAsType())
4961 if (isa<TemplateSpecializationType>(T))
4962 return true;
4963
4964 return false;
4965}
4966
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004967// Explicit instantiation of a class template specialization
John McCallf312b1e2010-08-26 23:41:50 +00004968DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004969Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004970 SourceLocation ExternLoc,
4971 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004972 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004973 SourceLocation KWLoc,
4974 const CXXScopeSpec &SS,
4975 TemplateTy TemplateD,
4976 SourceLocation TemplateNameLoc,
4977 SourceLocation LAngleLoc,
4978 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004979 SourceLocation RAngleLoc,
4980 AttributeList *Attr) {
4981 // Find the class template we're specializing
4982 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004983 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004984 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4985
4986 // Check that the specialization uses the same tag kind as the
4987 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004988 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4989 assert(Kind != TTK_Enum &&
4990 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004991 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004992 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004993 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004994 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004995 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004996 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004997 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004998 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004999 diag::note_previous_use);
5000 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5001 }
5002
Douglas Gregor558c0322009-10-14 23:41:34 +00005003 // C++0x [temp.explicit]p2:
5004 // There are two forms of explicit instantiation: an explicit instantiation
5005 // definition and an explicit instantiation declaration. An explicit
5006 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00005007 TemplateSpecializationKind TSK
5008 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5009 : TSK_ExplicitInstantiationDeclaration;
5010
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005011 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00005012 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00005013 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005014
5015 // Check that the template argument list is well-formed for this
5016 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00005017 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00005018 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5019 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005020 return true;
5021
Douglas Gregor910f8002010-11-07 23:05:16 +00005022 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005023 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00005024
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005025 // Find the class template specialization declaration that
5026 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005027 void *InsertPos = 0;
5028 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00005029 = ClassTemplate->findSpecialization(Converted.data(),
5030 Converted.size(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005031
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005032 TemplateSpecializationKind PrevDecl_TSK
5033 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5034
Douglas Gregord5cb8762009-10-07 00:13:32 +00005035 // C++0x [temp.explicit]p2:
5036 // [...] An explicit instantiation shall appear in an enclosing
5037 // namespace of its template. [...]
5038 //
5039 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00005040 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5041 SS.isSet()))
5042 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00005043
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005044 ClassTemplateSpecializationDecl *Specialization = 0;
5045
Douglas Gregord78f5982009-11-25 06:01:46 +00005046 bool ReusedDecl = false;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005047 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005048 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00005049 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005050 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005051 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005052 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00005053 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005054
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005055 // Even though HasNoEffect == true means that this explicit instantiation
5056 // has no effect on semantics, we go on to put its syntax in the AST.
5057
5058 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5059 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00005060 // Since the only prior class template specialization with these
5061 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005062 // declaration node as our own, updating the source location
5063 // for the template name to reflect our new declaration.
5064 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00005065 Specialization = PrevDecl;
5066 Specialization->setLocation(TemplateNameLoc);
5067 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00005068 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00005069 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005070 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005071
Douglas Gregor52604ab2009-09-11 21:19:12 +00005072 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005073 // Create a new class template specialization declaration node for
5074 // this explicit specialization.
5075 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00005076 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005077 ClassTemplate->getDeclContext(),
5078 TemplateNameLoc,
5079 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005080 Converted.data(),
5081 Converted.size(),
5082 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00005083 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005084
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005085 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005086 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005087 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005088 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005089 }
5090
5091 // Build the fully-sugared type for this explicit instantiation as
5092 // the user wrote in the explicit instantiation itself. This means
5093 // that we'll pretty-print the type retrieved from the
5094 // specialization's declaration the way that the user actually wrote
5095 // the explicit instantiation, rather than formatting the name based
5096 // on the "canonical" representation used to store the template
5097 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00005098 TypeSourceInfo *WrittenTy
5099 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5100 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005101 Context.getTypeDeclType(Specialization));
5102 Specialization->setTypeAsWritten(WrittenTy);
5103 TemplateArgsIn.release();
5104
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005105 // Set source locations for keywords.
5106 Specialization->setExternLoc(ExternLoc);
5107 Specialization->setTemplateKeywordLoc(TemplateLoc);
5108
5109 // Add the explicit instantiation into its lexical context. However,
5110 // since explicit instantiations are never found by name lookup, we
5111 // just put it into the declaration context directly.
5112 Specialization->setLexicalDeclContext(CurContext);
5113 CurContext->addDecl(Specialization);
5114
5115 // Syntax is now OK, so return if it has no other effect on semantics.
5116 if (HasNoEffect) {
5117 // Set the template specialization kind.
5118 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005119 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00005120 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005121
5122 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005123 // A definition of a class template or class member template
5124 // shall be in scope at the point of the explicit instantiation of
5125 // the class template or class member template.
5126 //
5127 // This check comes when we actually try to perform the
5128 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005129 ClassTemplateSpecializationDecl *Def
5130 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005131 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005132 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005133 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005134 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005135 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005136 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5137 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005138
Douglas Gregor0d035142009-10-27 18:42:08 +00005139 // Instantiate the members of this class template specialization.
5140 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005141 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005142 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00005143 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5144
5145 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5146 // TSK_ExplicitInstantiationDefinition
5147 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5148 TSK == TSK_ExplicitInstantiationDefinition)
5149 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005150
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005151 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005152 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005153
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005154 // Set the template specialization kind.
5155 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005156 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005157}
5158
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005159// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00005160DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005161Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005162 SourceLocation ExternLoc,
5163 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005164 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005165 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005166 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005167 IdentifierInfo *Name,
5168 SourceLocation NameLoc,
5169 AttributeList *Attr) {
5170
Douglas Gregor402abb52009-05-28 23:31:59 +00005171 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00005172 bool IsDependent = false;
John McCallf312b1e2010-08-26 23:41:50 +00005173 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCalld226f652010-08-21 09:40:31 +00005174 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5175 MultiTemplateParamsArg(*this, 0, 0),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00005176 Owned, IsDependent, false, false,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005177 TypeResult());
John McCallc4e70192009-09-11 04:59:25 +00005178 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5179
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005180 if (!TagD)
5181 return true;
5182
John McCalld226f652010-08-21 09:40:31 +00005183 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005184 if (Tag->isEnum()) {
5185 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5186 << Context.getTypeDeclType(Tag);
5187 return true;
5188 }
5189
Douglas Gregord0c87372009-05-27 17:30:49 +00005190 if (Tag->isInvalidDecl())
5191 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00005192
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005193 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5194 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5195 if (!Pattern) {
5196 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5197 << Context.getTypeDeclType(Record);
5198 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5199 return true;
5200 }
5201
Douglas Gregor558c0322009-10-14 23:41:34 +00005202 // C++0x [temp.explicit]p2:
5203 // If the explicit instantiation is for a class or member class, the
5204 // elaborated-type-specifier in the declaration shall include a
5205 // simple-template-id.
5206 //
5207 // C++98 has the same restriction, just worded differently.
5208 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00005209 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005210 << Record << SS.getRange();
5211
5212 // C++0x [temp.explicit]p2:
5213 // There are two forms of explicit instantiation: an explicit instantiation
5214 // definition and an explicit instantiation declaration. An explicit
5215 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00005216 TemplateSpecializationKind TSK
5217 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5218 : TSK_ExplicitInstantiationDeclaration;
5219
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005220 // C++0x [temp.explicit]p2:
5221 // [...] An explicit instantiation shall appear in an enclosing
5222 // namespace of its template. [...]
5223 //
5224 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00005225 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00005226
5227 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00005228 CXXRecordDecl *PrevDecl
5229 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00005230 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00005231 PrevDecl = Record;
5232 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00005233 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005234 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00005235 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00005236 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00005237 PrevDecl,
5238 MSInfo->getTemplateSpecializationKind(),
5239 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005240 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005241 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005242 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00005243 return TagD;
5244 }
5245
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005246 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00005247 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005248 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005249 // C++ [temp.explicit]p3:
5250 // A definition of a member class of a class template shall be in scope
5251 // at the point of an explicit instantiation of the member class.
5252 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00005253 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005254 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00005255 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5256 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005257 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5258 << Pattern;
5259 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00005260 } else {
5261 if (InstantiateClass(NameLoc, Record, Def,
5262 getTemplateInstantiationArgs(Record),
5263 TSK))
5264 return true;
5265
Douglas Gregor952b0172010-02-11 01:04:33 +00005266 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00005267 if (!RecordDef)
5268 return true;
5269 }
5270 }
5271
5272 // Instantiate all of the members of the class.
5273 InstantiateClassMembers(NameLoc, RecordDef,
5274 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005275
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005276 if (TSK == TSK_ExplicitInstantiationDefinition)
5277 MarkVTableUsed(NameLoc, RecordDef, true);
5278
Mike Stump390b4cc2009-05-16 07:39:55 +00005279 // FIXME: We don't have any representation for explicit instantiations of
5280 // member classes. Such a representation is not needed for compilation, but it
5281 // should be available for clients that want to see all of the declarations in
5282 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005283 return TagD;
5284}
5285
John McCallf312b1e2010-08-26 23:41:50 +00005286DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5287 SourceLocation ExternLoc,
5288 SourceLocation TemplateLoc,
5289 Declarator &D) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005290 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00005291 // TODO: check if/when DNInfo should replace Name.
5292 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5293 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005294 if (!Name) {
5295 if (!D.isInvalidType())
5296 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5297 diag::err_explicit_instantiation_requires_name)
5298 << D.getDeclSpec().getSourceRange()
5299 << D.getSourceRange();
5300
5301 return true;
5302 }
5303
5304 // The scope passed in may not be a decl scope. Zip up the scope tree until
5305 // we find one that is.
5306 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5307 (S->getFlags() & Scope::TemplateParamScope) != 0)
5308 S = S->getParent();
5309
5310 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00005311 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5312 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005313 if (R.isNull())
5314 return true;
5315
5316 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5317 // Cannot explicitly instantiate a typedef.
5318 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5319 << Name;
5320 return true;
5321 }
5322
Douglas Gregor663b5a02009-10-14 20:14:33 +00005323 // C++0x [temp.explicit]p1:
5324 // [...] An explicit instantiation of a function template shall not use the
5325 // inline or constexpr specifiers.
5326 // Presumably, this also applies to member functions of class templates as
5327 // well.
5328 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5329 Diag(D.getDeclSpec().getInlineSpecLoc(),
5330 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00005331 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00005332
5333 // FIXME: check for constexpr specifier.
5334
Douglas Gregor558c0322009-10-14 23:41:34 +00005335 // C++0x [temp.explicit]p2:
5336 // There are two forms of explicit instantiation: an explicit instantiation
5337 // definition and an explicit instantiation declaration. An explicit
5338 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00005339 TemplateSpecializationKind TSK
5340 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5341 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00005342
Abramo Bagnara25777432010-08-11 22:01:17 +00005343 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005344 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005345
5346 if (!R->isFunctionType()) {
5347 // C++ [temp.explicit]p1:
5348 // A [...] static data member of a class template can be explicitly
5349 // instantiated from the member definition associated with its class
5350 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00005351 if (Previous.isAmbiguous())
5352 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005353
John McCall1bcee0a2009-12-02 08:25:40 +00005354 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005355 if (!Prev || !Prev->isStaticDataMember()) {
5356 // We expect to see a data data member here.
5357 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5358 << Name;
5359 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5360 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00005361 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005362 return true;
5363 }
5364
5365 if (!Prev->getInstantiatedFromStaticDataMember()) {
5366 // FIXME: Check for explicit specialization?
5367 Diag(D.getIdentifierLoc(),
5368 diag::err_explicit_instantiation_data_member_not_instantiated)
5369 << Prev;
5370 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5371 // FIXME: Can we provide a note showing where this was declared?
5372 return true;
5373 }
5374
Douglas Gregor558c0322009-10-14 23:41:34 +00005375 // C++0x [temp.explicit]p2:
5376 // If the explicit instantiation is for a member function, a member class
5377 // or a static data member of a class template specialization, the name of
5378 // the class template specialization in the qualified-id for the member
5379 // name shall be a simple-template-id.
5380 //
5381 // C++98 has the same restriction, just worded differently.
5382 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5383 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005384 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005385 << Prev << D.getCXXScopeSpec().getRange();
5386
5387 // Check the scope of this explicit instantiation.
5388 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5389
Douglas Gregor454885e2009-10-15 15:54:05 +00005390 // Verify that it is okay to explicitly instantiate here.
5391 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5392 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005393 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005394 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005395 MSInfo->getTemplateSpecializationKind(),
5396 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005397 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005398 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005399 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005400 return (Decl*) 0;
Douglas Gregor454885e2009-10-15 15:54:05 +00005401
Douglas Gregord5a423b2009-09-25 18:43:00 +00005402 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005403 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005404 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005405 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005406
5407 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00005408 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005409 }
5410
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005411 // If the declarator is a template-id, translate the parser's template
5412 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005413 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005414 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005415 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5416 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005417 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5418 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005419 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5420 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005421 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005422 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005423 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005424 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005425 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005426
Douglas Gregord5a423b2009-09-25 18:43:00 +00005427 // C++ [temp.explicit]p1:
5428 // A [...] function [...] can be explicitly instantiated from its template.
5429 // A member function [...] of a class template can be explicitly
5430 // instantiated from the member definition associated with its class
5431 // template.
John McCallc373d482010-01-27 01:50:18 +00005432 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005433 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5434 P != PEnd; ++P) {
5435 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005436 if (!HasExplicitTemplateArgs) {
5437 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5438 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5439 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005440
John McCallc373d482010-01-27 01:50:18 +00005441 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005442 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5443 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005444 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005445 }
5446 }
5447
5448 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5449 if (!FunTmpl)
5450 continue;
5451
John McCall5769d612010-02-08 23:07:23 +00005452 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005453 FunctionDecl *Specialization = 0;
5454 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005455 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005456 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005457 R, Specialization, Info)) {
5458 // FIXME: Keep track of almost-matches?
5459 (void)TDK;
5460 continue;
5461 }
5462
John McCallc373d482010-01-27 01:50:18 +00005463 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005464 }
5465
5466 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005467 UnresolvedSetIterator Result
5468 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005469 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005470 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5471 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5472 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005473
John McCallc373d482010-01-27 01:50:18 +00005474 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005475 return true;
John McCallc373d482010-01-27 01:50:18 +00005476
5477 // Ignore access control bits, we don't need them for redeclaration checking.
5478 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005479
Douglas Gregor0a897e32009-10-15 17:21:20 +00005480 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005481 Diag(D.getIdentifierLoc(),
5482 diag::err_explicit_instantiation_member_function_not_instantiated)
5483 << Specialization
5484 << (Specialization->getTemplateSpecializationKind() ==
5485 TSK_ExplicitSpecialization);
5486 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5487 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005488 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005489
Douglas Gregor0a897e32009-10-15 17:21:20 +00005490 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005491 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5492 PrevDecl = Specialization;
5493
Douglas Gregor0a897e32009-10-15 17:21:20 +00005494 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005495 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005496 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005497 PrevDecl,
5498 PrevDecl->getTemplateSpecializationKind(),
5499 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005500 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00005501 return true;
5502
5503 // FIXME: We may still want to build some representation of this
5504 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005505 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005506 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005507 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005508
5509 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005510
5511 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005512 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005513
Douglas Gregor558c0322009-10-14 23:41:34 +00005514 // C++0x [temp.explicit]p2:
5515 // If the explicit instantiation is for a member function, a member class
5516 // or a static data member of a class template specialization, the name of
5517 // the class template specialization in the qualified-id for the member
5518 // name shall be a simple-template-id.
5519 //
5520 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005521 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005522 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005523 D.getCXXScopeSpec().isSet() &&
5524 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5525 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005526 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005527 << Specialization << D.getCXXScopeSpec().getRange();
5528
5529 CheckExplicitInstantiationScope(*this,
5530 FunTmpl? (NamedDecl *)FunTmpl
5531 : Specialization->getInstantiatedFromMemberFunction(),
5532 D.getIdentifierLoc(),
5533 D.getCXXScopeSpec().isSet());
5534
Douglas Gregord5a423b2009-09-25 18:43:00 +00005535 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00005536 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005537}
5538
John McCallf312b1e2010-08-26 23:41:50 +00005539TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005540Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5541 const CXXScopeSpec &SS, IdentifierInfo *Name,
5542 SourceLocation TagLoc, SourceLocation NameLoc) {
5543 // This has to hold, because SS is expected to be defined.
5544 assert(Name && "Expected a name in a dependent tag");
5545
5546 NestedNameSpecifier *NNS
5547 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5548 if (!NNS)
5549 return true;
5550
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005551 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005552
Douglas Gregor48c89f42010-04-24 16:38:41 +00005553 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5554 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005555 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005556 return true;
5557 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005558
5559 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallb3d87482010-08-24 05:47:05 +00005560 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCallc4e70192009-09-11 04:59:25 +00005561}
5562
John McCallf312b1e2010-08-26 23:41:50 +00005563TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005564Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5565 const CXXScopeSpec &SS, const IdentifierInfo &II,
5566 SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005567 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005568 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5569 if (!NNS)
5570 return true;
5571
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005572 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5573 !getLangOptions().CPlusPlus0x)
5574 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5575 << FixItHint::CreateRemoval(TypenameLoc);
5576
Douglas Gregor107de902010-04-24 15:35:55 +00005577 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005578 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005579 if (T.isNull())
5580 return true;
John McCall63b43852010-04-29 23:50:39 +00005581
5582 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5583 if (isa<DependentNameType>(T)) {
5584 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005585 TL.setKeywordLoc(TypenameLoc);
5586 TL.setQualifierRange(SS.getRange());
5587 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005588 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005589 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005590 TL.setKeywordLoc(TypenameLoc);
5591 TL.setQualifierRange(SS.getRange());
5592 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005593 }
5594
John McCallb3d87482010-08-24 05:47:05 +00005595 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00005596}
5597
John McCallf312b1e2010-08-26 23:41:50 +00005598TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005599Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5600 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallb3d87482010-08-24 05:47:05 +00005601 ParsedType Ty) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005602 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5603 !getLangOptions().CPlusPlus0x)
5604 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5605 << FixItHint::CreateRemoval(TypenameLoc);
5606
John McCall4e449832010-05-28 23:32:21 +00005607 TypeSourceInfo *InnerTSI = 0;
5608 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCall4e449832010-05-28 23:32:21 +00005609
5610 assert(isa<TemplateSpecializationType>(T) &&
5611 "Expected a template specialization type");
Douglas Gregor17343172009-04-01 00:28:59 +00005612
Douglas Gregor6946baf2009-09-02 13:05:45 +00005613 if (computeDeclContext(SS, false)) {
5614 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005615 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005616 // track of the nested-name-specifier.
John McCall4e449832010-05-28 23:32:21 +00005617
5618 // Push the inner type, preserving its source locations if possible.
5619 TypeLocBuilder Builder;
5620 if (InnerTSI)
5621 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5622 else
5623 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5624
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005625 /* Note: NNS already embedded in template specialization type T. */
5626 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCall4e449832010-05-28 23:32:21 +00005627 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5628 TL.setKeywordLoc(TypenameLoc);
5629 TL.setQualifierRange(SS.getRange());
5630
5631 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallb3d87482010-08-24 05:47:05 +00005632 return CreateParsedType(T, TSI);
Douglas Gregor6946baf2009-09-02 13:05:45 +00005633 }
Mike Stump1eb44332009-09-09 15:08:12 +00005634
John McCall33500952010-06-11 00:33:02 +00005635 // TODO: it's really silly that we make a template specialization
5636 // type earlier only to drop it again here.
5637 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5638 DependentTemplateName *DTN =
5639 TST->getTemplateName().getAsDependentTemplateName();
5640 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005641 assert(DTN->getQualifier()
5642 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5643 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5644 DTN->getQualifier(),
John McCall33500952010-06-11 00:33:02 +00005645 DTN->getIdentifier(),
5646 TST->getNumArgs(),
5647 TST->getArgs());
John McCall63b43852010-04-29 23:50:39 +00005648 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCall33500952010-06-11 00:33:02 +00005649 DependentTemplateSpecializationTypeLoc TL =
5650 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5651 if (InnerTSI) {
5652 TemplateSpecializationTypeLoc TSTL =
5653 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5654 TL.setLAngleLoc(TSTL.getLAngleLoc());
5655 TL.setRAngleLoc(TSTL.getRAngleLoc());
5656 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5657 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5658 } else {
5659 TL.initializeLocal(SourceLocation());
5660 }
John McCall4e449832010-05-28 23:32:21 +00005661 TL.setKeywordLoc(TypenameLoc);
5662 TL.setQualifierRange(SS.getRange());
John McCallb3d87482010-08-24 05:47:05 +00005663 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00005664}
5665
Douglas Gregord57959a2009-03-27 23:10:48 +00005666/// \brief Build the type that describes a C++ typename specifier,
5667/// e.g., "typename T::type".
5668QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005669Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5670 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005671 SourceLocation KeywordLoc, SourceRange NNSRange,
5672 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005673 CXXScopeSpec SS;
5674 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005675 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005676
John McCall77bb1aa2010-05-01 00:40:08 +00005677 DeclContext *Ctx = computeDeclContext(SS);
5678 if (!Ctx) {
5679 // If the nested-name-specifier is dependent and couldn't be
5680 // resolved to a type, build a typename type.
5681 assert(NNS->isDependent());
5682 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005683 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005684
John McCall77bb1aa2010-05-01 00:40:08 +00005685 // If the nested-name-specifier refers to the current instantiation,
5686 // the "typename" keyword itself is superfluous. In C++03, the
5687 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5688 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00005689 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005690
John McCall77bb1aa2010-05-01 00:40:08 +00005691 if (RequireCompleteDeclContext(SS, Ctx))
5692 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005693
5694 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005695 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005696 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005697 unsigned DiagID = 0;
5698 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005699 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005700 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005701 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005702 break;
Douglas Gregord9545042010-12-09 00:06:27 +00005703
5704 case LookupResult::FoundUnresolvedValue: {
5705 // We found a using declaration that is a value. Most likely, the using
5706 // declaration itself is meant to have the 'typename' keyword.
5707 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5708 IILoc);
5709 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
5710 << Name << Ctx << FullRange;
5711 if (UnresolvedUsingValueDecl *Using
5712 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
5713 SourceLocation Loc = Using->getTargetNestedNameRange().getBegin();
5714 Diag(Loc, diag::note_using_value_decl_missing_typename)
5715 << FixItHint::CreateInsertion(Loc, "typename ");
5716 }
5717 }
5718 // Fall through to create a dependent typename type, from which we can recover
5719 // better.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005720
5721 case LookupResult::NotFoundInCurrentInstantiation:
5722 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005723 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005724
5725 case LookupResult::Found:
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005726 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005727 // We found a type. Build an ElaboratedType, since the
5728 // typename-specifier was just sugar.
5729 return Context.getElaboratedType(ETK_Typename, NNS,
5730 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005731 }
5732
5733 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005734 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005735 break;
5736
Douglas Gregord9545042010-12-09 00:06:27 +00005737
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005738 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005739 return QualType();
5740
Douglas Gregord57959a2009-03-27 23:10:48 +00005741 case LookupResult::FoundOverloaded:
5742 DiagID = diag::err_typename_nested_not_type;
5743 Referenced = *Result.begin();
5744 break;
5745
John McCall6e247262009-10-10 05:48:19 +00005746 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005747 return QualType();
5748 }
5749
5750 // If we get here, it's because name lookup did not find a
5751 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005752 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5753 IILoc);
5754 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005755 if (Referenced)
5756 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5757 << Name;
5758 return QualType();
5759}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005760
5761namespace {
5762 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005763 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005764 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005765 SourceLocation Loc;
5766 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005767
Douglas Gregor4a959d82009-08-06 16:20:37 +00005768 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005769 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5770
Mike Stump1eb44332009-09-09 15:08:12 +00005771 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005772 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005773 DeclarationName Entity)
5774 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005775 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005776
5777 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005778 /// transformed.
5779 ///
5780 /// For the purposes of type reconstruction, a type has already been
5781 /// transformed if it is NULL or if it is not dependent.
5782 bool AlreadyTransformed(QualType T) {
5783 return T.isNull() || !T->isDependentType();
5784 }
Mike Stump1eb44332009-09-09 15:08:12 +00005785
5786 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005787 /// rebuilt.
5788 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005789
Douglas Gregor4a959d82009-08-06 16:20:37 +00005790 /// \brief Returns the name of the entity whose type is being rebuilt.
5791 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005792
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005793 /// \brief Sets the "base" location and entity when that
5794 /// information is known based on another transformation.
5795 void setBase(SourceLocation Loc, DeclarationName Entity) {
5796 this->Loc = Loc;
5797 this->Entity = Entity;
5798 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00005799 };
5800}
5801
Douglas Gregor4a959d82009-08-06 16:20:37 +00005802/// \brief Rebuilds a type within the context of the current instantiation.
5803///
Mike Stump1eb44332009-09-09 15:08:12 +00005804/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005805/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005806/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005807/// partial specialization thereof). This routine will rebuild that type now
5808/// that we have entered the declarator's scope, which may produce different
5809/// canonical types, e.g.,
5810///
5811/// \code
5812/// template<typename T>
5813/// struct X {
5814/// typedef T* pointer;
5815/// pointer data();
5816/// };
5817///
5818/// template<typename T>
5819/// typename X<T>::pointer X<T>::data() { ... }
5820/// \endcode
5821///
Douglas Gregor4714c122010-03-31 17:34:00 +00005822/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005823/// since we do not know that we can look into X<T> when we parsed the type.
5824/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005825/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00005826/// as the canonical type of T*, allowing the return types of the out-of-line
5827/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00005828TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5829 SourceLocation Loc,
5830 DeclarationName Name) {
5831 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00005832 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005833
Douglas Gregor4a959d82009-08-06 16:20:37 +00005834 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5835 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005836}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005837
John McCall60d7b3a2010-08-24 06:29:42 +00005838ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00005839 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5840 DeclarationName());
5841 return Rebuilder.TransformExpr(E);
5842}
5843
John McCall63b43852010-04-29 23:50:39 +00005844bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5845 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00005846
5847 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5848 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5849 DeclarationName());
5850 NestedNameSpecifier *Rebuilt =
5851 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005852 if (!Rebuilt) return true;
5853
5854 SS.setScopeRep(Rebuilt);
5855 return false;
John McCall31f17ec2010-04-27 00:57:59 +00005856}
5857
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005858/// \brief Produces a formatted string that describes the binding of
5859/// template parameters to template arguments.
5860std::string
5861Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5862 const TemplateArgumentList &Args) {
Douglas Gregor910f8002010-11-07 23:05:16 +00005863 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005864}
5865
5866std::string
5867Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5868 const TemplateArgument *Args,
5869 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005870 std::string Result;
5871
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005872 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005873 return Result;
5874
5875 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005876 if (I >= NumArgs)
5877 break;
5878
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005879 if (I == 0)
5880 Result += "[with ";
5881 else
5882 Result += ", ";
5883
5884 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5885 Result += Id->getName();
5886 } else {
5887 Result += '$';
5888 Result += llvm::utostr(I);
5889 }
5890
5891 Result += " = ";
5892
5893 switch (Args[I].getKind()) {
5894 case TemplateArgument::Null:
5895 Result += "<no value>";
5896 break;
5897
5898 case TemplateArgument::Type: {
5899 std::string TypeStr;
5900 Args[I].getAsType().getAsStringInternal(TypeStr,
5901 Context.PrintingPolicy);
5902 Result += TypeStr;
5903 break;
5904 }
5905
5906 case TemplateArgument::Declaration: {
5907 bool Unnamed = true;
5908 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5909 if (ND->getDeclName()) {
5910 Unnamed = false;
5911 Result += ND->getNameAsString();
5912 }
5913 }
5914
5915 if (Unnamed) {
5916 Result += "<anonymous>";
5917 }
5918 break;
5919 }
5920
Douglas Gregor788cd062009-11-11 01:00:40 +00005921 case TemplateArgument::Template: {
5922 std::string Str;
5923 llvm::raw_string_ostream OS(Str);
5924 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5925 Result += OS.str();
5926 break;
5927 }
5928
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005929 case TemplateArgument::Integral: {
5930 Result += Args[I].getAsIntegral()->toString(10);
5931 break;
5932 }
5933
5934 case TemplateArgument::Expression: {
Douglas Gregor77e2c672010-04-29 04:55:13 +00005935 // FIXME: This is non-optimal, since we're regurgitating the
5936 // expression we were given.
5937 std::string Str;
5938 {
5939 llvm::raw_string_ostream OS(Str);
5940 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5941 Context.PrintingPolicy);
5942 }
5943 Result += Str;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005944 break;
5945 }
5946
5947 case TemplateArgument::Pack:
5948 // FIXME: Format template argument packs
5949 Result += "<template argument pack>";
5950 break;
5951 }
5952 }
5953
5954 Result += ']';
5955 return Result;
5956}
Douglas Gregord0937222010-12-13 22:49:22 +00005957
5958bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
5959 TypeSourceInfo *T,
5960 UnexpandedParameterPackContext UPPC) {
5961 // C++0x [temp.variadic]p5:
5962 // An appearance of a name of a parameter pack that is not expanded is
5963 // ill-formed.
5964 if (!T->getType()->containsUnexpandedParameterPack())
5965 return false;
5966
5967 // FIXME: Provide the names and locations of the unexpanded parameter packs.
5968 Diag(Loc, diag::err_unexpanded_parameter_pack)
5969 << (int)UPPC << T->getTypeLoc().getSourceRange();
5970 return true;
5971}
5972
5973bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
5974 UnexpandedParameterPackContext UPPC) {
5975 // C++0x [temp.variadic]p5:
5976 // An appearance of a name of a parameter pack that is not expanded is
5977 // ill-formed.
5978 if (!E->containsUnexpandedParameterPack())
5979 return false;
5980
5981 // FIXME: Provide the names and locations of the unexpanded parameter packs.
5982 Diag(E->getSourceRange().getBegin(), diag::err_unexpanded_parameter_pack)
5983 << (int)UPPC << E->getSourceRange();
5984 return true;
5985}
5986