blob: 6384e53e80b1faff55add8936d71ed38f32ce4ae [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 }
Douglas Gregor6f526752010-12-16 08:48:57 +0000539
540 // Check for unexpanded parameter packs.
541 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
542 UPPC_DefaultArgument))
543 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000544
545 // Check the template argument itself.
546 if (CheckTemplateArgument(Param, DefaultTInfo)) {
547 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000548 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000549 }
550
551 Param->setDefaultArgument(DefaultTInfo, false);
552 }
553
John McCalld226f652010-08-21 09:40:31 +0000554 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000555}
556
Douglas Gregor2943aed2009-03-03 04:44:36 +0000557/// \brief Check that the type of a non-type template parameter is
558/// well-formed.
559///
560/// \returns the (possibly-promoted) parameter type if valid;
561/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000562QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000563Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000564 // We don't allow variably-modified types as the type of non-type template
565 // parameters.
566 if (T->isVariablyModifiedType()) {
567 Diag(Loc, diag::err_variably_modified_nontype_template_param)
568 << T;
569 return QualType();
570 }
571
Douglas Gregor2943aed2009-03-03 04:44:36 +0000572 // C++ [temp.param]p4:
573 //
574 // A non-type template-parameter shall have one of the following
575 // (optionally cv-qualified) types:
576 //
577 // -- integral or enumeration type,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000578 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000579 // -- pointer to object or pointer to function,
Eli Friedman13578692010-08-05 02:49:48 +0000580 T->isPointerType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000581 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000582 T->isReferenceType() ||
583 // -- pointer to member.
584 T->isMemberPointerType() ||
585 // If T is a dependent type, we can't do the check now, so we
586 // assume that it is well-formed.
587 T->isDependentType())
588 return T;
589 // C++ [temp.param]p8:
590 //
591 // A non-type template-parameter of type "array of T" or
592 // "function returning T" is adjusted to be of type "pointer to
593 // T" or "pointer to function returning T", respectively.
594 else if (T->isArrayType())
595 // FIXME: Keep the type prior to promotion?
596 return Context.getArrayDecayedType(T);
597 else if (T->isFunctionType())
598 // FIXME: Keep the type prior to promotion?
599 return Context.getPointerType(T);
Douglas Gregor0fddb972010-05-22 16:17:30 +0000600
Douglas Gregor2943aed2009-03-03 04:44:36 +0000601 Diag(Loc, diag::err_template_nontype_parm_bad_type)
602 << T;
603
604 return QualType();
605}
606
John McCalld226f652010-08-21 09:40:31 +0000607Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
608 unsigned Depth,
609 unsigned Position,
610 SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000611 Expr *Default) {
John McCallbf1a0282010-06-04 23:28:52 +0000612 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
613 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000614
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000615 assert(S->isTemplateParamScope() &&
616 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000617 bool Invalid = false;
618
619 IdentifierInfo *ParamName = D.getIdentifier();
620 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000621 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000622 LookupOrdinaryName,
623 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000624 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000625 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000626 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000627 }
628
Douglas Gregor4d2abba2010-12-16 15:36:43 +0000629 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
630 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000631 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000632 Invalid = true;
633 }
Douglas Gregor781def02010-12-16 08:56:23 +0000634
Douglas Gregor10738d32010-12-23 23:51:58 +0000635 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000636 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000637 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
638 D.getIdentifierLoc(),
Douglas Gregor10738d32010-12-23 23:51:58 +0000639 Depth, Position, ParamName, T,
640 IsParameterPack, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000641 if (Invalid)
642 Param->setInvalidDecl();
643
644 if (D.getIdentifier()) {
645 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000646 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000647 IdResolver.AddDecl(Param);
648 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000649
650 // Check the well-formedness of the default template argument, if provided.
Douglas Gregor10738d32010-12-23 23:51:58 +0000651 if (Default) {
Douglas Gregor85374732010-12-24 00:20:52 +0000652 // C++0x [temp.param]p9:
653 // A default template-argument may be specified for any kind of
654 // template-parameter that is not a template parameter pack.
655 if (IsParameterPack) {
656 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
657 return Param;
658 }
659
Douglas Gregor6f526752010-12-16 08:48:57 +0000660 // Check for unexpanded parameter packs.
661 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
662 return Param;
663
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000664 TemplateArgument Converted;
665 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
666 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000667 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000668 }
669
John McCall9ae2f072010-08-23 23:25:46 +0000670 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000671 }
672
John McCalld226f652010-08-21 09:40:31 +0000673 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000674}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000675
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000676/// ActOnTemplateTemplateParameter - Called when a C++ template template
677/// parameter (e.g. T in template <template <typename> class T> class array)
678/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000679Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
680 SourceLocation TmpLoc,
681 TemplateParamsTy *Params,
682 IdentifierInfo *Name,
683 SourceLocation NameLoc,
684 unsigned Depth,
685 unsigned Position,
686 SourceLocation EqualLoc,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000687 const ParsedTemplateArgument &Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000688 assert(S->isTemplateParamScope() &&
689 "Template template parameter not in template parameter scope!");
690
691 // Construct the parameter object.
692 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000693 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000694 NameLoc.isInvalid()? TmpLoc : NameLoc,
695 Depth, Position, Name,
Douglas Gregor369ea272010-10-21 17:26:49 +0000696 Params);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000697
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000698 // If the template template parameter has a name, then link the identifier
699 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000700 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000701 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000702 IdResolver.AddDecl(Param);
703 }
704
Douglas Gregor6f526752010-12-16 08:48:57 +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 }
710
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000711 if (!Default.isInvalid()) {
712 // Check only that we have a template template argument. We don't want to
713 // try to check well-formedness now, because our template template parameter
714 // might have dependent types in its template parameters, which we wouldn't
715 // be able to match now.
716 //
717 // If none of the template template parameter's template arguments mention
718 // other template parameters, we could actually perform more checking here.
719 // However, it isn't worth doing.
720 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
721 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
722 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
723 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000724 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000725 }
726
Douglas Gregor6f526752010-12-16 08:48:57 +0000727 // Check for unexpanded parameter packs.
728 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
729 DefaultArg.getArgument().getAsTemplate(),
730 UPPC_DefaultArgument))
731 return Param;
732
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000733 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000734 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000735
John McCalld226f652010-08-21 09:40:31 +0000736 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000737}
738
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000739/// ActOnTemplateParameterList - Builds a TemplateParameterList that
740/// contains the template parameters in Params/NumParams.
741Sema::TemplateParamsTy *
742Sema::ActOnTemplateParameterList(unsigned Depth,
743 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000744 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000745 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000746 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000747 SourceLocation RAngleLoc) {
748 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000749 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000750
Douglas Gregorddc29e12009-02-06 22:42:48 +0000751 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000752 (NamedDecl**)Params, NumParams,
753 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000754}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000755
John McCallb6217662010-03-15 10:12:16 +0000756static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
757 if (SS.isSet())
758 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
759 SS.getRange());
760}
761
John McCallf312b1e2010-08-26 23:41:50 +0000762DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000763Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000764 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000765 IdentifierInfo *Name, SourceLocation NameLoc,
766 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000767 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000768 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000769 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000770 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000771 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000772 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000773
774 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000775 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000776 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000777
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000778 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
779 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000780
781 // There is no such thing as an unnamed class template.
782 if (!Name) {
783 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000784 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000785 }
786
787 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000788 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000789 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000790 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000791 if (SS.isNotEmpty() && !SS.isInvalid()) {
792 SemanticContext = computeDeclContext(SS, true);
793 if (!SemanticContext) {
794 // FIXME: Produce a reasonable diagnostic here
795 return true;
796 }
Mike Stump1eb44332009-09-09 15:08:12 +0000797
John McCall77bb1aa2010-05-01 00:40:08 +0000798 if (RequireCompleteDeclContext(SS, SemanticContext))
799 return true;
800
John McCalla24dc2e2009-11-17 02:14:36 +0000801 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000802 } else {
803 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000804 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000805 }
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Douglas Gregor57265e32010-04-12 16:00:01 +0000807 if (Previous.isAmbiguous())
808 return true;
809
Douglas Gregorddc29e12009-02-06 22:42:48 +0000810 NamedDecl *PrevDecl = 0;
811 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000812 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000813
Douglas Gregorddc29e12009-02-06 22:42:48 +0000814 // If there is a previous declaration with the same name, check
815 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000816 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000817 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000818
819 // We may have found the injected-class-name of a class template,
820 // class template partial specialization, or class template specialization.
821 // In these cases, grab the template that is being defined or specialized.
822 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
823 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
824 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
825 PrevClassTemplate
826 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
827 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
828 PrevClassTemplate
829 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
830 ->getSpecializedTemplate();
831 }
832 }
833
John McCall65c49462009-12-18 11:25:59 +0000834 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000835 // C++ [namespace.memdef]p3:
836 // [...] When looking for a prior declaration of a class or a function
837 // declared as a friend, and when the name of the friend class or
838 // function is neither a qualified name nor a template-id, scopes outside
839 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000840 if (!SS.isSet()) {
841 DeclContext *OutermostContext = CurContext;
842 while (!OutermostContext->isFileContext())
843 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000844
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000845 if (PrevDecl &&
846 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
847 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
848 SemanticContext = PrevDecl->getDeclContext();
849 } else {
850 // Declarations in outer scopes don't matter. However, the outermost
851 // context we computed is the semantic context for our new
852 // declaration.
853 PrevDecl = PrevClassTemplate = 0;
854 SemanticContext = OutermostContext;
855 }
John McCalle129d442009-12-17 23:21:11 +0000856 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000857
John McCalle129d442009-12-17 23:21:11 +0000858 if (CurContext->isDependentContext()) {
859 // If this is a dependent context, we don't want to link the friend
860 // class template to the template in scope, because that would perform
861 // checking of the template parameter lists that can't be performed
862 // until the outer context is instantiated.
863 PrevDecl = PrevClassTemplate = 0;
864 }
865 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
866 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000867
Douglas Gregorddc29e12009-02-06 22:42:48 +0000868 if (PrevClassTemplate) {
869 // Ensure that the template parameter lists are compatible.
870 if (!TemplateParameterListsAreEqual(TemplateParams,
871 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000872 /*Complain=*/true,
873 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000874 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000875
876 // C++ [temp.class]p4:
877 // In a redeclaration, partial specialization, explicit
878 // specialization or explicit instantiation of a class template,
879 // the class-key shall agree in kind with the original class
880 // template declaration (7.1.5.3).
881 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000882 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000883 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000884 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000885 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000886 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000887 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000888 }
889
Douglas Gregorddc29e12009-02-06 22:42:48 +0000890 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000891 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000892 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000893 Diag(NameLoc, diag::err_redefinition) << Name;
894 Diag(Def->getLocation(), diag::note_previous_definition);
895 // FIXME: Would it make sense to try to "forget" the previous
896 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000897 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000898 }
899 }
900 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
901 // Maybe we will complain about the shadowed template parameter.
902 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
903 // Just pretend that we didn't see the previous declaration.
904 PrevDecl = 0;
905 } else if (PrevDecl) {
906 // C++ [temp]p5:
907 // A class template shall not have the same name as any other
908 // template, class, function, object, enumeration, enumerator,
909 // namespace, or type in the same scope (3.3), except as specified
910 // in (14.5.4).
911 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
912 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000913 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000914 }
915
Douglas Gregord684b002009-02-10 19:49:53 +0000916 // Check the template parameter list of this declaration, possibly
917 // merging in the template parameter list from the previous class
918 // template declaration.
919 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000920 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
921 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000922 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Douglas Gregor57265e32010-04-12 16:00:01 +0000924 if (SS.isSet()) {
925 // If the name of the template was qualified, we must be defining the
926 // template out-of-line.
927 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
928 !(TUK == TUK_Friend && CurContext->isDependentContext()))
929 Diag(NameLoc, diag::err_member_def_does_not_match)
930 << Name << SemanticContext << SS.getRange();
931 }
932
Mike Stump1eb44332009-09-09 15:08:12 +0000933 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000934 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000935 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000936 PrevClassTemplate->getTemplatedDecl() : 0,
937 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000938 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000939
940 ClassTemplateDecl *NewTemplate
941 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
942 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000943 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000944 NewClass->setDescribedClassTemplate(NewTemplate);
945
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000946 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +0000947 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +0000948 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000949 assert(T->isDependentType() && "Class template type is not dependent?");
950 (void)T;
951
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000952 // If we are providing an explicit specialization of a member that is a
953 // class template, make a note of that.
954 if (PrevClassTemplate &&
955 PrevClassTemplate->getInstantiatedFromMemberTemplate())
956 PrevClassTemplate->setMemberSpecialization();
957
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000958 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000959 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000960 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Douglas Gregorddc29e12009-02-06 22:42:48 +0000962 // Set the lexical context of these templates
963 NewClass->setLexicalDeclContext(CurContext);
964 NewTemplate->setLexicalDeclContext(CurContext);
965
John McCall0f434ec2009-07-31 02:45:11 +0000966 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000967 NewClass->startDefinition();
968
969 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000970 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000971
John McCall05b23ea2009-09-14 21:59:20 +0000972 if (TUK != TUK_Friend)
973 PushOnScopeChains(NewTemplate, S);
974 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000975 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000976 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000977 NewClass->setAccess(PrevClassTemplate->getAccess());
978 }
John McCall05b23ea2009-09-14 21:59:20 +0000979
Douglas Gregord85bea22009-09-26 06:47:28 +0000980 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
981 PrevClassTemplate != NULL);
982
John McCall05b23ea2009-09-14 21:59:20 +0000983 // Friend templates are visible in fairly strange ways.
984 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +0000985 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall05b23ea2009-09-14 21:59:20 +0000986 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
987 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
988 PushOnScopeChains(NewTemplate, EnclosingScope,
989 /* AddToContext = */ false);
990 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000991
992 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
993 NewClass->getLocation(),
994 NewTemplate,
995 /*FIXME:*/NewClass->getLocation());
996 Friend->setAccess(AS_public);
997 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000998 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000999
Douglas Gregord684b002009-02-10 19:49:53 +00001000 if (Invalid) {
1001 NewTemplate->setInvalidDecl();
1002 NewClass->setInvalidDecl();
1003 }
John McCalld226f652010-08-21 09:40:31 +00001004 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +00001005}
1006
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001007/// \brief Diagnose the presence of a default template argument on a
1008/// template parameter, which is ill-formed in certain contexts.
1009///
1010/// \returns true if the default template argument should be dropped.
1011static bool DiagnoseDefaultTemplateArgument(Sema &S,
1012 Sema::TemplateParamListContext TPC,
1013 SourceLocation ParamLoc,
1014 SourceRange DefArgRange) {
1015 switch (TPC) {
1016 case Sema::TPC_ClassTemplate:
1017 return false;
1018
1019 case Sema::TPC_FunctionTemplate:
1020 // C++ [temp.param]p9:
1021 // A default template-argument shall not be specified in a
1022 // function template declaration or a function template
1023 // definition [...]
1024 // (This sentence is not in C++0x, per DR226).
1025 if (!S.getLangOptions().CPlusPlus0x)
1026 S.Diag(ParamLoc,
1027 diag::err_template_parameter_default_in_function_template)
1028 << DefArgRange;
1029 return false;
1030
1031 case Sema::TPC_ClassTemplateMember:
1032 // C++0x [temp.param]p9:
1033 // A default template-argument shall not be specified in the
1034 // template-parameter-lists of the definition of a member of a
1035 // class template that appears outside of the member's class.
1036 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1037 << DefArgRange;
1038 return true;
1039
1040 case Sema::TPC_FriendFunctionTemplate:
1041 // C++ [temp.param]p9:
1042 // A default template-argument shall not be specified in a
1043 // friend template declaration.
1044 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1045 << DefArgRange;
1046 return true;
1047
1048 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1049 // for friend function templates if there is only a single
1050 // declaration (and it is a definition). Strange!
1051 }
1052
1053 return false;
1054}
1055
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001056/// \brief Check for unexpanded parameter packs within the template parameters
1057/// of a template template parameter, recursively.
1058bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP){
1059 TemplateParameterList *Params = TTP->getTemplateParameters();
1060 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1061 NamedDecl *P = Params->getParam(I);
1062 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1063 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1064 NTTP->getTypeSourceInfo(),
1065 Sema::UPPC_NonTypeTemplateParameterType))
1066 return true;
1067
1068 continue;
1069 }
1070
1071 if (TemplateTemplateParmDecl *InnerTTP
1072 = dyn_cast<TemplateTemplateParmDecl>(P))
1073 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1074 return true;
1075 }
1076
1077 return false;
1078}
1079
Douglas Gregord684b002009-02-10 19:49:53 +00001080/// \brief Checks the validity of a template parameter list, possibly
1081/// considering the template parameter list from a previous
1082/// declaration.
1083///
1084/// If an "old" template parameter list is provided, it must be
1085/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1086/// template parameter list.
1087///
1088/// \param NewParams Template parameter list for a new template
1089/// declaration. This template parameter list will be updated with any
1090/// default arguments that are carried through from the previous
1091/// template parameter list.
1092///
1093/// \param OldParams If provided, template parameter list from a
1094/// previous declaration of the same template. Default template
1095/// arguments will be merged from the old template parameter list to
1096/// the new template parameter list.
1097///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001098/// \param TPC Describes the context in which we are checking the given
1099/// template parameter list.
1100///
Douglas Gregord684b002009-02-10 19:49:53 +00001101/// \returns true if an error occurred, false otherwise.
1102bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001103 TemplateParameterList *OldParams,
1104 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001105 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Douglas Gregord684b002009-02-10 19:49:53 +00001107 // C++ [temp.param]p10:
1108 // The set of default template-arguments available for use with a
1109 // template declaration or definition is obtained by merging the
1110 // default arguments from the definition (if in scope) and all
1111 // declarations in scope in the same way default function
1112 // arguments are (8.3.6).
1113 bool SawDefaultArgument = false;
1114 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001115
Anders Carlsson49d25572009-06-12 23:20:15 +00001116 bool SawParameterPack = false;
1117 SourceLocation ParameterPackLoc;
1118
Mike Stump1a35fde2009-02-11 23:03:27 +00001119 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001120 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001121 if (OldParams)
1122 OldParam = OldParams->begin();
1123
1124 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1125 NewParamEnd = NewParams->end();
1126 NewParam != NewParamEnd; ++NewParam) {
1127 // Variables used to diagnose redundant default arguments
1128 bool RedundantDefaultArg = false;
1129 SourceLocation OldDefaultLoc;
1130 SourceLocation NewDefaultLoc;
1131
1132 // Variables used to diagnose missing default arguments
1133 bool MissingDefaultArg = false;
1134
Anders Carlsson49d25572009-06-12 23:20:15 +00001135 // C++0x [temp.param]p11:
1136 // If a template parameter of a class template is a template parameter pack,
1137 // it must be the last template parameter.
1138 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001139 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001140 diag::err_template_param_pack_must_be_last_template_parameter);
1141 Invalid = true;
1142 }
1143
Douglas Gregord684b002009-02-10 19:49:53 +00001144 if (TemplateTypeParmDecl *NewTypeParm
1145 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001146 // Check the presence of a default argument here.
1147 if (NewTypeParm->hasDefaultArgument() &&
1148 DiagnoseDefaultTemplateArgument(*this, TPC,
1149 NewTypeParm->getLocation(),
1150 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001151 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001152 NewTypeParm->removeDefaultArgument();
1153
1154 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001155 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001156 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Anders Carlsson49d25572009-06-12 23:20:15 +00001158 if (NewTypeParm->isParameterPack()) {
1159 assert(!NewTypeParm->hasDefaultArgument() &&
1160 "Parameter packs can't have a default argument!");
1161 SawParameterPack = true;
1162 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001163 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001164 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001165 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1166 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1167 SawDefaultArgument = true;
1168 RedundantDefaultArg = true;
1169 PreviousDefaultArgLoc = NewDefaultLoc;
1170 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1171 // Merge the default argument from the old declaration to the
1172 // new declaration.
1173 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001174 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001175 true);
1176 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1177 } else if (NewTypeParm->hasDefaultArgument()) {
1178 SawDefaultArgument = true;
1179 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1180 } else if (SawDefaultArgument)
1181 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001182 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001183 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001184 // Check for unexpanded parameter packs.
1185 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1186 NewNonTypeParm->getTypeSourceInfo(),
1187 UPPC_NonTypeTemplateParameterType)) {
1188 Invalid = true;
1189 continue;
1190 }
1191
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001192 // Check the presence of a default argument here.
1193 if (NewNonTypeParm->hasDefaultArgument() &&
1194 DiagnoseDefaultTemplateArgument(*this, TPC,
1195 NewNonTypeParm->getLocation(),
1196 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001197 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001198 }
1199
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001200 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001201 NonTypeTemplateParmDecl *OldNonTypeParm
1202 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001203 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001204 NewNonTypeParm->hasDefaultArgument()) {
1205 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1206 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1207 SawDefaultArgument = true;
1208 RedundantDefaultArg = true;
1209 PreviousDefaultArgLoc = NewDefaultLoc;
1210 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1211 // Merge the default argument from the old declaration to the
1212 // new declaration.
1213 SawDefaultArgument = true;
1214 // FIXME: We need to create a new kind of "default argument"
1215 // expression that points to a previous template template
1216 // parameter.
1217 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001218 OldNonTypeParm->getDefaultArgument(),
1219 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001220 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1221 } else if (NewNonTypeParm->hasDefaultArgument()) {
1222 SawDefaultArgument = true;
1223 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1224 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001225 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001226 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001227 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001228 TemplateTemplateParmDecl *NewTemplateParm
1229 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001230
1231 // Check for unexpanded parameter packs, recursively.
1232 if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1233 Invalid = true;
1234 continue;
1235 }
1236
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001237 if (NewTemplateParm->hasDefaultArgument() &&
1238 DiagnoseDefaultTemplateArgument(*this, TPC,
1239 NewTemplateParm->getLocation(),
1240 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001241 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001242
1243 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001244 TemplateTemplateParmDecl *OldTemplateParm
1245 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001246 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001247 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001248 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1249 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001250 SawDefaultArgument = true;
1251 RedundantDefaultArg = true;
1252 PreviousDefaultArgLoc = NewDefaultLoc;
1253 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1254 // Merge the default argument from the old declaration to the
1255 // new declaration.
1256 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001257 // FIXME: We need to create a new kind of "default argument" expression
1258 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001259 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001260 OldTemplateParm->getDefaultArgument(),
1261 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001262 PreviousDefaultArgLoc
1263 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001264 } else if (NewTemplateParm->hasDefaultArgument()) {
1265 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001266 PreviousDefaultArgLoc
1267 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001268 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001269 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001270 }
1271
1272 if (RedundantDefaultArg) {
1273 // C++ [temp.param]p12:
1274 // A template-parameter shall not be given default arguments
1275 // by two different declarations in the same scope.
1276 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1277 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1278 Invalid = true;
1279 } else if (MissingDefaultArg) {
1280 // C++ [temp.param]p11:
1281 // If a template-parameter has a default template-argument,
1282 // all subsequent template-parameters shall have a default
1283 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001284 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001285 diag::err_template_param_default_arg_missing);
1286 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1287 Invalid = true;
1288 }
1289
1290 // If we have an old template parameter list that we're merging
1291 // in, move on to the next parameter.
1292 if (OldParams)
1293 ++OldParam;
1294 }
1295
1296 return Invalid;
1297}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001298
John McCall4e2cbb22010-10-20 05:44:58 +00001299namespace {
1300
1301/// A class which looks for a use of a certain level of template
1302/// parameter.
1303struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1304 typedef RecursiveASTVisitor<DependencyChecker> super;
1305
1306 unsigned Depth;
1307 bool Match;
1308
1309 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1310 NamedDecl *ND = Params->getParam(0);
1311 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1312 Depth = PD->getDepth();
1313 } else if (NonTypeTemplateParmDecl *PD =
1314 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1315 Depth = PD->getDepth();
1316 } else {
1317 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1318 }
1319 }
1320
1321 bool Matches(unsigned ParmDepth) {
1322 if (ParmDepth >= Depth) {
1323 Match = true;
1324 return true;
1325 }
1326 return false;
1327 }
1328
1329 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1330 return !Matches(T->getDepth());
1331 }
1332
1333 bool TraverseTemplateName(TemplateName N) {
1334 if (TemplateTemplateParmDecl *PD =
1335 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1336 if (Matches(PD->getDepth())) return false;
1337 return super::TraverseTemplateName(N);
1338 }
1339
1340 bool VisitDeclRefExpr(DeclRefExpr *E) {
1341 if (NonTypeTemplateParmDecl *PD =
1342 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1343 if (PD->getDepth() == Depth) {
1344 Match = true;
1345 return false;
1346 }
1347 }
1348 return super::VisitDeclRefExpr(E);
1349 }
1350};
1351}
1352
1353/// Determines whether a template-id depends on the given parameter
1354/// list.
1355static bool
1356DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId,
1357 TemplateParameterList *Params) {
1358 DependencyChecker Checker(Params);
1359 Checker.TraverseType(QualType(TemplateId, 0));
1360 return Checker.Match;
1361}
1362
Mike Stump1eb44332009-09-09 15:08:12 +00001363/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001364/// specifier, returning the template parameter list that applies to the
1365/// name.
1366///
1367/// \param DeclStartLoc the start of the declaration that has a scope
1368/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001369///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001370/// \param SS the scope specifier that will be matched to the given template
1371/// parameter lists. This scope specifier precedes a qualified name that is
1372/// being declared.
1373///
1374/// \param ParamLists the template parameter lists, from the outermost to the
1375/// innermost template parameter lists.
1376///
1377/// \param NumParamLists the number of template parameter lists in ParamLists.
1378///
John McCall77e8b112010-04-13 20:37:33 +00001379/// \param IsFriend Whether to apply the slightly different rules for
1380/// matching template parameters to scope specifiers in friend
1381/// declarations.
1382///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001383/// \param IsExplicitSpecialization will be set true if the entity being
1384/// declared is an explicit specialization, false otherwise.
1385///
Mike Stump1eb44332009-09-09 15:08:12 +00001386/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001387/// name that is preceded by the scope specifier @p SS. This template
1388/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001389/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001390/// template specialization), or may be NULL (if we were's declaring isn't
1391/// itself a template).
1392TemplateParameterList *
1393Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1394 const CXXScopeSpec &SS,
1395 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001396 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001397 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001398 bool &IsExplicitSpecialization,
1399 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001400 IsExplicitSpecialization = false;
1401
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001402 // Find the template-ids that occur within the nested-name-specifier. These
1403 // template-ids will match up with the template parameter lists.
1404 llvm::SmallVector<const TemplateSpecializationType *, 4>
1405 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001406 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1407 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001408 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1409 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001410 const Type *T = NNS->getAsType();
1411 if (!T) break;
1412
1413 // C++0x [temp.expl.spec]p17:
1414 // A member or a member template may be nested within many
1415 // enclosing class templates. In an explicit specialization for
1416 // such a member, the member declaration shall be preceded by a
1417 // template<> for each enclosing class template that is
1418 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001419 //
1420 // Following the existing practice of GNU and EDG, we allow a typedef of a
1421 // template specialization type.
John McCall49f4e1c2010-12-10 11:01:00 +00001422 while (const TypedefType *TT = dyn_cast<TypedefType>(T))
1423 T = TT->getDecl()->getUnderlyingType().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001424
Mike Stump1eb44332009-09-09 15:08:12 +00001425 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001426 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001427 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1428 if (!Template)
1429 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Ted Kremenek6217b802009-07-29 21:53:49 +00001431 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001432 ClassTemplateSpecializationDecl *SpecDecl
1433 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1434 // If the nested name specifier refers to an explicit specialization,
1435 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001436 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1437 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001438 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001439 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001440 }
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001442 TemplateIdsInSpecifier.push_back(SpecType);
1443 }
1444 }
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001446 // Reverse the list of template-ids in the scope specifier, so that we can
1447 // more easily match up the template-ids and the template parameter lists.
1448 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001450 SourceLocation FirstTemplateLoc = DeclStartLoc;
1451 if (NumParamLists)
1452 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001454 // Match the template-ids found in the specifier to the template parameter
1455 // lists.
John McCall4e2cbb22010-10-20 05:44:58 +00001456 unsigned ParamIdx = 0, TemplateIdx = 0;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001457 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
John McCall4e2cbb22010-10-20 05:44:58 +00001458 TemplateIdx != NumTemplateIds; ++TemplateIdx) {
1459 const TemplateSpecializationType *TemplateId
1460 = TemplateIdsInSpecifier[TemplateIdx];
Douglas Gregorb88e8882009-07-30 17:40:51 +00001461 bool DependentTemplateId = TemplateId->isDependentType();
John McCall4e2cbb22010-10-20 05:44:58 +00001462
1463 // In friend declarations we can have template-ids which don't
1464 // depend on the corresponding template parameter lists. But
1465 // assume that empty parameter lists are supposed to match this
1466 // template-id.
1467 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) {
1468 if (!DependentTemplateId ||
1469 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx]))
1470 continue;
1471 }
1472
1473 if (ParamIdx >= NumParamLists) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001474 // We have a template-id without a corresponding template parameter
1475 // list.
John McCall77e8b112010-04-13 20:37:33 +00001476
1477 // ...which is fine if this is a friend declaration.
1478 if (IsFriend) {
1479 IsExplicitSpecialization = true;
1480 break;
1481 }
1482
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001483 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001484 // FIXME: the location information here isn't great.
1485 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001486 diag::err_template_spec_needs_template_parameters)
John McCall4e2cbb22010-10-20 05:44:58 +00001487 << QualType(TemplateId, 0)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001488 << SS.getRange();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001489 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001490 } else {
1491 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1492 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001493 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001494 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001495 }
1496 return 0;
1497 }
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001499 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001500 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001501 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001502
John McCall31f17ec2010-04-27 00:57:59 +00001503 // Are there cases in (e.g.) friends where this won't match?
1504 if (const InjectedClassNameType *Injected
1505 = TemplateId->getAs<InjectedClassNameType>()) {
1506 CXXRecordDecl *Record = Injected->getDecl();
1507 if (ClassTemplatePartialSpecializationDecl *Partial =
1508 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1509 ExpectedTemplateParams = Partial->getTemplateParameters();
1510 else
1511 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1512 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001513 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001514
John McCall31f17ec2010-04-27 00:57:59 +00001515 if (ExpectedTemplateParams)
John McCall4e2cbb22010-10-20 05:44:58 +00001516 TemplateParameterListsAreEqual(ParamLists[ParamIdx],
John McCall31f17ec2010-04-27 00:57:59 +00001517 ExpectedTemplateParams,
1518 true, TPL_TemplateMatch);
1519
John McCall4e2cbb22010-10-20 05:44:58 +00001520 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1521 TPC_ClassTemplateMember);
1522 } else if (ParamLists[ParamIdx]->size() > 0)
1523 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001524 diag::err_template_param_list_matches_nontemplate)
1525 << TemplateId
John McCall4e2cbb22010-10-20 05:44:58 +00001526 << ParamLists[ParamIdx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001527 else
1528 IsExplicitSpecialization = true;
John McCall4e2cbb22010-10-20 05:44:58 +00001529
1530 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001531 }
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001533 // If there were at least as many template-ids as there were template
1534 // parameter lists, then there are no template parameter lists remaining for
1535 // the declaration itself.
John McCall4e2cbb22010-10-20 05:44:58 +00001536 if (ParamIdx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001537 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001539 // If there were too many template parameter lists, complain about that now.
John McCall4e2cbb22010-10-20 05:44:58 +00001540 if (ParamIdx != NumParamLists - 1) {
1541 while (ParamIdx < NumParamLists - 1) {
1542 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0;
1543 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001544 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1545 : diag::err_template_spec_extra_headers)
John McCall4e2cbb22010-10-20 05:44:58 +00001546 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1547 ParamLists[ParamIdx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001548
1549 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1550 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1551 diag::note_explicit_template_spec_does_not_need_header)
1552 << ExplicitSpecializationsInSpecifier.back();
1553 ExplicitSpecializationsInSpecifier.pop_back();
1554 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001555
1556 // We have a template parameter list with no corresponding scope, which
1557 // means that the resulting template declaration can't be instantiated
1558 // properly (we'll end up with dependent nodes when we shouldn't).
1559 if (!isExplicitSpecHeader)
1560 Invalid = true;
1561
John McCall4e2cbb22010-10-20 05:44:58 +00001562 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001563 }
1564 }
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001566 // Return the last template parameter list, which corresponds to the
1567 // entity being declared.
1568 return ParamLists[NumParamLists - 1];
1569}
1570
Douglas Gregor7532dc62009-03-30 22:58:21 +00001571QualType Sema::CheckTemplateIdType(TemplateName Name,
1572 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001573 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001574 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001575 if (!Template) {
1576 // The template name does not resolve to a template, so we just
1577 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001578 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001579 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001580
Douglas Gregor40808ce2009-03-09 23:48:35 +00001581 // Check that the template argument list is well-formed for this
1582 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001583 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00001584 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001585 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001586 return QualType();
1587
Douglas Gregor910f8002010-11-07 23:05:16 +00001588 assert((Converted.size() == Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001589 "Converted template argument list is too short!");
1590
1591 QualType CanonType;
1592
Douglas Gregorcaddba02009-11-12 18:38:13 +00001593 if (Name.isDependent() ||
1594 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001595 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001596 // This class template specialization is a dependent
1597 // type. Therefore, its canonical type is another class template
1598 // specialization type that contains all of the converted
1599 // arguments in canonical form. This ensures that, e.g., A<T> and
1600 // A<T, T> have identical types when A is declared as:
1601 //
1602 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001603 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001604 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor910f8002010-11-07 23:05:16 +00001605 Converted.data(),
1606 Converted.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Douglas Gregor1275ae02009-07-28 23:00:59 +00001608 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001609 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001610 // In the future, we need to teach getTemplateSpecializationType to only
1611 // build the canonical type and return that to us.
1612 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001613
1614 // This might work out to be a current instantiation, in which
1615 // case the canonical type needs to be the InjectedClassNameType.
1616 //
1617 // TODO: in theory this could be a simple hashtable lookup; most
1618 // changes to CurContext don't change the set of current
1619 // instantiations.
1620 if (isa<ClassTemplateDecl>(Template)) {
1621 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1622 // If we get out to a namespace, we're done.
1623 if (Ctx->isFileContext()) break;
1624
1625 // If this isn't a record, keep looking.
1626 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1627 if (!Record) continue;
1628
1629 // Look for one of the two cases with InjectedClassNameTypes
1630 // and check whether it's the same template.
1631 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1632 !Record->getDescribedClassTemplate())
1633 continue;
1634
1635 // Fetch the injected class name type and check whether its
1636 // injected type is equal to the type we just built.
1637 QualType ICNT = Context.getTypeDeclType(Record);
1638 QualType Injected = cast<InjectedClassNameType>(ICNT)
1639 ->getInjectedSpecializationType();
1640
1641 if (CanonType != Injected->getCanonicalTypeInternal())
1642 continue;
1643
1644 // If so, the canonical type of this TST is the injected
1645 // class name type of the record we just found.
1646 assert(ICNT.isCanonical());
1647 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00001648 break;
1649 }
1650 }
Mike Stump1eb44332009-09-09 15:08:12 +00001651 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001652 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001653 // Find the class template specialization declaration that
1654 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001655 void *InsertPos = 0;
1656 ClassTemplateSpecializationDecl *Decl
Douglas Gregor910f8002010-11-07 23:05:16 +00001657 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
1658 InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001659 if (!Decl) {
1660 // This is the first time we have referenced this class template
1661 // specialization. Create the canonical declaration and add it to
1662 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001663 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001664 ClassTemplate->getTemplatedDecl()->getTagKind(),
1665 ClassTemplate->getDeclContext(),
1666 ClassTemplate->getLocation(),
Douglas Gregor910f8002010-11-07 23:05:16 +00001667 ClassTemplate,
1668 Converted.data(),
1669 Converted.size(), 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001670 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001671 Decl->setLexicalDeclContext(CurContext);
1672 }
1673
1674 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001675 assert(isa<RecordType>(CanonType) &&
1676 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001677 }
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Douglas Gregor40808ce2009-03-09 23:48:35 +00001679 // Build the fully-sugared type for this class template
1680 // specialization, which refers back to the class template
1681 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00001682 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001683}
1684
John McCallf312b1e2010-08-26 23:41:50 +00001685TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001686Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001687 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001688 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001689 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001690 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001691
Douglas Gregor40808ce2009-03-09 23:48:35 +00001692 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001693 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001694 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001695
John McCalld5532b62009-11-23 01:53:49 +00001696 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001697 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001698
1699 if (Result.isNull())
1700 return true;
1701
John McCalla93c9342009-12-07 02:54:59 +00001702 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001703 TemplateSpecializationTypeLoc TL
1704 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1705 TL.setTemplateNameLoc(TemplateLoc);
1706 TL.setLAngleLoc(LAngleLoc);
1707 TL.setRAngleLoc(RAngleLoc);
1708 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1709 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1710
John McCallb3d87482010-08-24 05:47:05 +00001711 return CreateParsedType(Result, DI);
John McCall6b2becf2009-09-08 17:47:29 +00001712}
John McCallf1bbbb42009-09-04 01:14:41 +00001713
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001714TypeResult Sema::ActOnTagTemplateIdType(CXXScopeSpec &SS,
1715 TypeResult TypeResult,
John McCallf312b1e2010-08-26 23:41:50 +00001716 TagUseKind TUK,
1717 TypeSpecifierType TagSpec,
1718 SourceLocation TagLoc) {
John McCall6b2becf2009-09-08 17:47:29 +00001719 if (TypeResult.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001720 return ::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001721
John McCalla93c9342009-12-07 02:54:59 +00001722 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001723 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001724
John McCall6b2becf2009-09-08 17:47:29 +00001725 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001726 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001727
John McCall6b2becf2009-09-08 17:47:29 +00001728 if (const RecordType *RT = Type->getAs<RecordType>()) {
1729 RecordDecl *D = RT->getDecl();
1730
1731 IdentifierInfo *Id = D->getIdentifier();
1732 assert(Id && "templated class must have an identifier");
1733
1734 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1735 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001736 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001737 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001738 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001739 }
1740 }
1741
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001742 ElaboratedTypeKeyword Keyword
1743 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1744 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001745
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001746 TypeSourceInfo *ElabDI = Context.CreateTypeSourceInfo(ElabType);
1747 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(ElabDI->getTypeLoc());
1748 TL.setKeywordLoc(TagLoc);
1749 TL.setQualifierRange(SS.getRange());
1750 TL.getNamedTypeLoc().initializeFullCopy(DI->getTypeLoc());
1751 return CreateParsedType(ElabType, ElabDI);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001752}
1753
John McCall60d7b3a2010-08-24 06:29:42 +00001754ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001755 LookupResult &R,
1756 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001757 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001758 // FIXME: Can we do any checking at this point? I guess we could check the
1759 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001760 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001761 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001762
1763 // These should be filtered out by our callers.
1764 assert(!R.empty() && "empty lookup results when building templateid");
1765 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1766
1767 NestedNameSpecifier *Qualifier = 0;
1768 SourceRange QualifierRange;
1769 if (SS.isSet()) {
1770 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1771 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001772 }
John McCallc373d482010-01-27 01:50:18 +00001773
1774 // We don't want lookup warnings at this point.
1775 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001776
John McCallf7a1a742009-11-24 19:00:30 +00001777 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001778 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001779 Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00001780 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001781 RequiresADL, TemplateArgs,
1782 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001783
1784 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001785}
1786
John McCallf7a1a742009-11-24 19:00:30 +00001787// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00001788ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001789Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001790 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +00001791 const TemplateArgumentListInfo &TemplateArgs) {
1792 DeclContext *DC;
1793 if (!(DC = computeDeclContext(SS, false)) ||
1794 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001795 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara25777432010-08-11 22:01:17 +00001796 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001798 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00001799 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001800 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1801 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001802
John McCallf7a1a742009-11-24 19:00:30 +00001803 if (R.isAmbiguous())
1804 return ExprError();
1805
1806 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001807 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1808 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001809 return ExprError();
1810 }
1811
1812 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001813 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1814 << (NestedNameSpecifier*) SS.getScopeRep()
1815 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001816 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1817 return ExprError();
1818 }
1819
1820 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001821}
1822
Douglas Gregorc45c2322009-03-31 00:43:58 +00001823/// \brief Form a dependent template name.
1824///
1825/// This action forms a dependent template name given the template
1826/// name and its (presumably dependent) scope specifier. For
1827/// example, given "MetaFun::template apply", the scope specifier \p
1828/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1829/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001830TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1831 SourceLocation TemplateKWLoc,
1832 CXXScopeSpec &SS,
1833 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00001834 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001835 bool EnteringContext,
1836 TemplateTy &Result) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00001837 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1838 !getLangOptions().CPlusPlus0x)
1839 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1840 << FixItHint::CreateRemoval(TemplateKWLoc);
1841
Douglas Gregor0707bc52010-01-19 16:01:07 +00001842 DeclContext *LookupCtx = 0;
1843 if (SS.isSet())
1844 LookupCtx = computeDeclContext(SS, EnteringContext);
1845 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00001846 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00001847 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001848 // C++0x [temp.names]p5:
1849 // If a name prefixed by the keyword template is not the name of
1850 // a template, the program is ill-formed. [Note: the keyword
1851 // template may not be applied to non-template members of class
1852 // templates. -end note ] [ Note: as is the case with the
1853 // typename prefix, the template prefix is allowed in cases
1854 // where it is not strictly necessary; i.e., when the
1855 // nested-name-specifier or the expression on the left of the ->
1856 // or . is not dependent on a template-parameter, or the use
1857 // does not appear in the scope of a template. -end note]
1858 //
1859 // Note: C++03 was more strict here, because it banned the use of
1860 // the "template" keyword prior to a template-name that was not a
1861 // dependent name. C++ DR468 relaxed this requirement (the
1862 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00001863 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001864 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001865 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1866 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001867 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001868 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1869 isa<CXXRecordDecl>(LookupCtx) &&
1870 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00001871 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001872 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001873 Diag(Name.getSourceRange().getBegin(),
1874 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001875 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001876 << Name.getSourceRange()
1877 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001878 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001879 } else {
1880 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001881 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001882 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001883 }
1884
Mike Stump1eb44332009-09-09 15:08:12 +00001885 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001886 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001887
1888 switch (Name.getKind()) {
1889 case UnqualifiedId::IK_Identifier:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001890 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1891 Name.Identifier));
1892 return TNK_Dependent_template_name;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001893
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001894 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001895 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001896 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00001897 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00001898
1899 case UnqualifiedId::IK_LiteralOperatorId:
1900 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1901
Douglas Gregor014e88d2009-11-03 23:16:33 +00001902 default:
1903 break;
1904 }
1905
1906 Diag(Name.getSourceRange().getBegin(),
1907 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001908 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001909 << Name.getSourceRange()
1910 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001911 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001912}
1913
Mike Stump1eb44332009-09-09 15:08:12 +00001914bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001915 const TemplateArgumentLoc &AL,
Douglas Gregor910f8002010-11-07 23:05:16 +00001916 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001917 const TemplateArgument &Arg = AL.getArgument();
1918
Anders Carlsson436b1562009-06-13 00:33:33 +00001919 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001920 switch(Arg.getKind()) {
1921 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001922 // C++ [temp.arg.type]p1:
1923 // A template-argument for a template-parameter which is a
1924 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001925 break;
1926 case TemplateArgument::Template: {
1927 // We have a template type parameter but the template argument
1928 // is a template without any arguments.
1929 SourceRange SR = AL.getSourceRange();
1930 TemplateName Name = Arg.getAsTemplate();
1931 Diag(SR.getBegin(), diag::err_template_missing_args)
1932 << Name << SR;
1933 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1934 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001935
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001936 return true;
1937 }
1938 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001939 // We have a template type parameter but the template argument
1940 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001941 SourceRange SR = AL.getSourceRange();
1942 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001943 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Anders Carlsson436b1562009-06-13 00:33:33 +00001945 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001946 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001947 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001948
John McCalla93c9342009-12-07 02:54:59 +00001949 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001950 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Anders Carlsson436b1562009-06-13 00:33:33 +00001952 // Add the converted template type argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001953 Converted.push_back(
John McCall833ca992009-10-29 08:12:44 +00001954 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001955 return false;
1956}
1957
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001958/// \brief Substitute template arguments into the default template argument for
1959/// the given template type parameter.
1960///
1961/// \param SemaRef the semantic analysis object for which we are performing
1962/// the substitution.
1963///
1964/// \param Template the template that we are synthesizing template arguments
1965/// for.
1966///
1967/// \param TemplateLoc the location of the template name that started the
1968/// template-id we are checking.
1969///
1970/// \param RAngleLoc the location of the right angle bracket ('>') that
1971/// terminates the template-id.
1972///
1973/// \param Param the template template parameter whose default we are
1974/// substituting into.
1975///
1976/// \param Converted the list of template arguments provided for template
1977/// parameters that precede \p Param in the template parameter list.
1978///
1979/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001980static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001981SubstDefaultTemplateArgument(Sema &SemaRef,
1982 TemplateDecl *Template,
1983 SourceLocation TemplateLoc,
1984 SourceLocation RAngleLoc,
1985 TemplateTypeParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00001986 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001987 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001988
1989 // If the argument type is dependent, instantiate it now based
1990 // on the previously-computed template arguments.
1991 if (ArgType->getType()->isDependentType()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001992 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1993 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001994
1995 MultiLevelTemplateArgumentList AllTemplateArgs
1996 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1997
1998 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00001999 Template, Converted.data(),
2000 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002001 SourceRange(TemplateLoc, RAngleLoc));
2002
2003 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2004 Param->getDefaultArgumentLoc(),
2005 Param->getDeclName());
2006 }
2007
2008 return ArgType;
2009}
2010
2011/// \brief Substitute template arguments into the default template argument for
2012/// the given non-type template parameter.
2013///
2014/// \param SemaRef the semantic analysis object for which we are performing
2015/// the substitution.
2016///
2017/// \param Template the template that we are synthesizing template arguments
2018/// for.
2019///
2020/// \param TemplateLoc the location of the template name that started the
2021/// template-id we are checking.
2022///
2023/// \param RAngleLoc the location of the right angle bracket ('>') that
2024/// terminates the template-id.
2025///
Douglas Gregor788cd062009-11-11 01:00:40 +00002026/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002027/// substituting into.
2028///
2029/// \param Converted the list of template arguments provided for template
2030/// parameters that precede \p Param in the template parameter list.
2031///
2032/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00002033static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002034SubstDefaultTemplateArgument(Sema &SemaRef,
2035 TemplateDecl *Template,
2036 SourceLocation TemplateLoc,
2037 SourceLocation RAngleLoc,
2038 NonTypeTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002039 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2040 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2041 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002042
2043 MultiLevelTemplateArgumentList AllTemplateArgs
2044 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2045
2046 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002047 Template, Converted.data(),
2048 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002049 SourceRange(TemplateLoc, RAngleLoc));
2050
2051 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2052}
2053
Douglas Gregor788cd062009-11-11 01:00:40 +00002054/// \brief Substitute template arguments into the default template argument for
2055/// the given template template parameter.
2056///
2057/// \param SemaRef the semantic analysis object for which we are performing
2058/// the substitution.
2059///
2060/// \param Template the template that we are synthesizing template arguments
2061/// for.
2062///
2063/// \param TemplateLoc the location of the template name that started the
2064/// template-id we are checking.
2065///
2066/// \param RAngleLoc the location of the right angle bracket ('>') that
2067/// terminates the template-id.
2068///
2069/// \param Param the template template parameter whose default we are
2070/// substituting into.
2071///
2072/// \param Converted the list of template arguments provided for template
2073/// parameters that precede \p Param in the template parameter list.
2074///
2075/// \returns the substituted template argument, or NULL if an error occurred.
2076static TemplateName
2077SubstDefaultTemplateArgument(Sema &SemaRef,
2078 TemplateDecl *Template,
2079 SourceLocation TemplateLoc,
2080 SourceLocation RAngleLoc,
2081 TemplateTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002082 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2083 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2084 Converted.data(), Converted.size());
Douglas Gregor788cd062009-11-11 01:00:40 +00002085
2086 MultiLevelTemplateArgumentList AllTemplateArgs
2087 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2088
2089 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002090 Template, Converted.data(),
2091 Converted.size(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002092 SourceRange(TemplateLoc, RAngleLoc));
2093
2094 return SemaRef.SubstTemplateName(
2095 Param->getDefaultArgument().getArgument().getAsTemplate(),
2096 Param->getDefaultArgument().getTemplateNameLoc(),
2097 AllTemplateArgs);
2098}
2099
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002100/// \brief If the given template parameter has a default template
2101/// argument, substitute into that default template argument and
2102/// return the corresponding template argument.
2103TemplateArgumentLoc
2104Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2105 SourceLocation TemplateLoc,
2106 SourceLocation RAngleLoc,
2107 Decl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002108 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2109 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002110 if (!TypeParm->hasDefaultArgument())
2111 return TemplateArgumentLoc();
2112
John McCalla93c9342009-12-07 02:54:59 +00002113 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002114 TemplateLoc,
2115 RAngleLoc,
2116 TypeParm,
2117 Converted);
2118 if (DI)
2119 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2120
2121 return TemplateArgumentLoc();
2122 }
2123
2124 if (NonTypeTemplateParmDecl *NonTypeParm
2125 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2126 if (!NonTypeParm->hasDefaultArgument())
2127 return TemplateArgumentLoc();
2128
John McCall60d7b3a2010-08-24 06:29:42 +00002129 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002130 TemplateLoc,
2131 RAngleLoc,
2132 NonTypeParm,
2133 Converted);
2134 if (Arg.isInvalid())
2135 return TemplateArgumentLoc();
2136
2137 Expr *ArgE = Arg.takeAs<Expr>();
2138 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2139 }
2140
2141 TemplateTemplateParmDecl *TempTempParm
2142 = cast<TemplateTemplateParmDecl>(Param);
2143 if (!TempTempParm->hasDefaultArgument())
2144 return TemplateArgumentLoc();
2145
2146 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2147 TemplateLoc,
2148 RAngleLoc,
2149 TempTempParm,
2150 Converted);
2151 if (TName.isNull())
2152 return TemplateArgumentLoc();
2153
2154 return TemplateArgumentLoc(TemplateArgument(TName),
2155 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2156 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2157}
2158
Douglas Gregore7526412009-11-11 19:31:23 +00002159/// \brief Check that the given template argument corresponds to the given
2160/// template parameter.
2161bool Sema::CheckTemplateArgument(NamedDecl *Param,
2162 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00002163 TemplateDecl *Template,
2164 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002165 SourceLocation RAngleLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002166 llvm::SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor02024a92010-03-28 02:42:43 +00002167 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002168 // Check template type parameters.
2169 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002170 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002171
Douglas Gregord9e15302009-11-11 19:41:09 +00002172 // Check non-type template parameters.
2173 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002174 // Do substitution on the type of the non-type template parameter
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002175 // with the template arguments we've seen thus far. But if the
2176 // template has a dependent context then we cannot substitute yet.
Douglas Gregore7526412009-11-11 19:31:23 +00002177 QualType NTTPType = NTTP->getType();
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002178 if (NTTPType->isDependentType() &&
2179 !isa<TemplateTemplateParmDecl>(Template) &&
2180 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002181 // Do substitution on the type of the non-type template parameter.
2182 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002183 NTTP, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002184 SourceRange(TemplateLoc, RAngleLoc));
2185
Douglas Gregor910f8002010-11-07 23:05:16 +00002186 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2187 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002188 NTTPType = SubstType(NTTPType,
2189 MultiLevelTemplateArgumentList(TemplateArgs),
2190 NTTP->getLocation(),
2191 NTTP->getDeclName());
2192 // If that worked, check the non-type template parameter type
2193 // for validity.
2194 if (!NTTPType.isNull())
2195 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2196 NTTP->getLocation());
2197 if (NTTPType.isNull())
2198 return true;
2199 }
2200
2201 switch (Arg.getArgument().getKind()) {
2202 case TemplateArgument::Null:
2203 assert(false && "Should never see a NULL template argument here");
2204 return true;
2205
2206 case TemplateArgument::Expression: {
2207 Expr *E = Arg.getArgument().getAsExpr();
2208 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002209 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002210 return true;
2211
Douglas Gregor910f8002010-11-07 23:05:16 +00002212 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002213 break;
2214 }
2215
2216 case TemplateArgument::Declaration:
2217 case TemplateArgument::Integral:
2218 // We've already checked this template argument, so just copy
2219 // it to the list of converted arguments.
Douglas Gregor910f8002010-11-07 23:05:16 +00002220 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002221 break;
2222
2223 case TemplateArgument::Template:
2224 // We were given a template template argument. It may not be ill-formed;
2225 // see below.
2226 if (DependentTemplateName *DTN
2227 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2228 // We have a template argument such as \c T::template X, which we
2229 // parsed as a template template argument. However, since we now
2230 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002231 // template name into an expression.
2232
2233 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2234 Arg.getTemplateNameLoc());
2235
John McCallf7a1a742009-11-24 19:00:30 +00002236 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2237 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002238 Arg.getTemplateQualifierRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002239 NameInfo);
Douglas Gregore7526412009-11-11 19:31:23 +00002240
2241 TemplateArgument Result;
2242 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2243 return true;
2244
Douglas Gregor910f8002010-11-07 23:05:16 +00002245 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002246 break;
2247 }
2248
2249 // We have a template argument that actually does refer to a class
2250 // template, template alias, or template template parameter, and
2251 // therefore cannot be a non-type template argument.
2252 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2253 << Arg.getSourceRange();
2254
2255 Diag(Param->getLocation(), diag::note_template_param_here);
2256 return true;
2257
2258 case TemplateArgument::Type: {
2259 // We have a non-type template parameter but the template
2260 // argument is a type.
2261
2262 // C++ [temp.arg]p2:
2263 // In a template-argument, an ambiguity between a type-id and
2264 // an expression is resolved to a type-id, regardless of the
2265 // form of the corresponding template-parameter.
2266 //
2267 // We warn specifically about this case, since it can be rather
2268 // confusing for users.
2269 QualType T = Arg.getArgument().getAsType();
2270 SourceRange SR = Arg.getSourceRange();
2271 if (T->isFunctionType())
2272 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2273 else
2274 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2275 Diag(Param->getLocation(), diag::note_template_param_here);
2276 return true;
2277 }
2278
2279 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002280 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002281 break;
2282 }
2283
2284 return false;
2285 }
2286
2287
2288 // Check template template parameters.
2289 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2290
2291 // Substitute into the template parameter list of the template
2292 // template parameter, since previously-supplied template arguments
2293 // may appear within the template template parameter.
2294 {
2295 // Set up a template instantiation context.
2296 LocalInstantiationScope Scope(*this);
2297 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002298 TempParm, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002299 SourceRange(TemplateLoc, RAngleLoc));
2300
Douglas Gregor910f8002010-11-07 23:05:16 +00002301 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2302 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002303 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2304 SubstDecl(TempParm, CurContext,
2305 MultiLevelTemplateArgumentList(TemplateArgs)));
2306 if (!TempParm)
2307 return true;
Douglas Gregore7526412009-11-11 19:31:23 +00002308 }
2309
2310 switch (Arg.getArgument().getKind()) {
2311 case TemplateArgument::Null:
2312 assert(false && "Should never see a NULL template argument here");
2313 return true;
2314
2315 case TemplateArgument::Template:
2316 if (CheckTemplateArgument(TempParm, Arg))
2317 return true;
2318
Douglas Gregor910f8002010-11-07 23:05:16 +00002319 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002320 break;
2321
2322 case TemplateArgument::Expression:
2323 case TemplateArgument::Type:
2324 // We have a template template parameter but the template
2325 // argument does not refer to a template.
2326 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2327 return true;
2328
2329 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002330 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002331 "Declaration argument with template template parameter");
2332 break;
2333 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002334 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002335 "Integral argument with template template parameter");
2336 break;
2337
2338 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002339 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002340 break;
2341 }
2342
2343 return false;
2344}
2345
Douglas Gregorc15cb382009-02-09 23:23:08 +00002346/// \brief Check that the given template argument list is well-formed
2347/// for specializing the given template.
2348bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2349 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002350 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002351 bool PartialTemplateArgs,
Douglas Gregor910f8002010-11-07 23:05:16 +00002352 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002353 TemplateParameterList *Params = Template->getTemplateParameters();
2354 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002355 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002356 bool Invalid = false;
2357
John McCalld5532b62009-11-23 01:53:49 +00002358 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2359
Mike Stump1eb44332009-09-09 15:08:12 +00002360 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002361 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002362
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002363 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002364 (NumArgs < Params->getMinRequiredArguments() &&
2365 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002366 // FIXME: point at either the first arg beyond what we can handle,
2367 // or the '>', depending on whether we have too many or too few
2368 // arguments.
2369 SourceRange Range;
2370 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002371 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002372 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2373 << (NumArgs > NumParams)
2374 << (isa<ClassTemplateDecl>(Template)? 0 :
2375 isa<FunctionTemplateDecl>(Template)? 1 :
2376 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2377 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002378 Diag(Template->getLocation(), diag::note_template_decl_here)
2379 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002380 Invalid = true;
2381 }
Mike Stump1eb44332009-09-09 15:08:12 +00002382
2383 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002384 // [...] The type and form of each template-argument specified in
2385 // a template-id shall match the type and form specified for the
2386 // corresponding parameter declared by the template in its
2387 // template-parameter-list.
Douglas Gregor14be16b2010-12-20 16:57:52 +00002388 llvm::SmallVector<TemplateArgument, 2> ArgumentPack;
2389 TemplateParameterList::iterator Param = Params->begin(),
2390 ParamEnd = Params->end();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002391 unsigned ArgIdx = 0;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002392 while (Param != ParamEnd) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002393 if (ArgIdx > NumArgs && PartialTemplateArgs)
2394 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002395
Douglas Gregorf35f8282009-11-11 21:54:23 +00002396 if (ArgIdx < NumArgs) {
2397 // Check the template argument we were given.
2398 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2399 TemplateLoc, RAngleLoc, Converted))
2400 return true;
2401
Douglas Gregor14be16b2010-12-20 16:57:52 +00002402 if ((*Param)->isTemplateParameterPack()) {
2403 // The template parameter was a template parameter pack, so take the
2404 // deduced argument and place it on the argument pack. Note that we
2405 // stay on the same template parameter so that we can deduce more
2406 // arguments.
2407 ArgumentPack.push_back(Converted.back());
2408 Converted.pop_back();
2409 } else {
2410 // Move to the next template parameter.
2411 ++Param;
2412 }
2413 ++ArgIdx;
Douglas Gregorf35f8282009-11-11 21:54:23 +00002414 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002415 }
Douglas Gregore7526412009-11-11 19:31:23 +00002416
Douglas Gregor14be16b2010-12-20 16:57:52 +00002417 // If we have a template parameter pack with no more corresponding
2418 // arguments, just break out now and we'll fill in the argument pack below.
2419 if ((*Param)->isTemplateParameterPack())
2420 break;
2421
Douglas Gregorf35f8282009-11-11 21:54:23 +00002422 // We have a default template argument that we will use.
2423 TemplateArgumentLoc Arg;
2424
2425 // Retrieve the default template argument from the template
2426 // parameter. For each kind of template parameter, we substitute the
2427 // template arguments provided thus far and any "outer" template arguments
2428 // (when the template parameter was part of a nested template) into
2429 // the default argument.
2430 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2431 if (!TTP->hasDefaultArgument()) {
2432 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2433 break;
2434 }
2435
John McCalla93c9342009-12-07 02:54:59 +00002436 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002437 Template,
2438 TemplateLoc,
2439 RAngleLoc,
2440 TTP,
2441 Converted);
2442 if (!ArgType)
2443 return true;
2444
2445 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2446 ArgType);
2447 } else if (NonTypeTemplateParmDecl *NTTP
2448 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2449 if (!NTTP->hasDefaultArgument()) {
2450 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2451 break;
2452 }
2453
John McCall60d7b3a2010-08-24 06:29:42 +00002454 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002455 TemplateLoc,
2456 RAngleLoc,
2457 NTTP,
2458 Converted);
2459 if (E.isInvalid())
2460 return true;
2461
2462 Expr *Ex = E.takeAs<Expr>();
2463 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2464 } else {
2465 TemplateTemplateParmDecl *TempParm
2466 = cast<TemplateTemplateParmDecl>(*Param);
2467
2468 if (!TempParm->hasDefaultArgument()) {
2469 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2470 break;
2471 }
2472
2473 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2474 TemplateLoc,
2475 RAngleLoc,
2476 TempParm,
2477 Converted);
2478 if (Name.isNull())
2479 return true;
2480
2481 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2482 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2483 TempParm->getDefaultArgument().getTemplateNameLoc());
2484 }
2485
2486 // Introduce an instantiation record that describes where we are using
2487 // the default template argument.
2488 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002489 Converted.data(), Converted.size(),
Douglas Gregorf35f8282009-11-11 21:54:23 +00002490 SourceRange(TemplateLoc, RAngleLoc));
2491
2492 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002493 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002494 RAngleLoc, Converted))
2495 return true;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002496
2497 // Move to the next template parameter and argument.
2498 ++Param;
2499 ++ArgIdx;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002500 }
Douglas Gregor14be16b2010-12-20 16:57:52 +00002501
2502 // Form argument packs for each of the parameter packs remaining.
2503 while (Param != ParamEnd) {
2504 if ((*Param)->isTemplateParameterPack()) {
2505 // The parameter pack takes the contents of the current argument pack,
2506 // which we built up earlier.
2507 if (ArgumentPack.empty()) {
2508 Converted.push_back(TemplateArgument(0, 0));
2509 } else {
2510 TemplateArgument *PackedArgs
2511 = new (Context) TemplateArgument [ArgumentPack.size()];
2512 std::copy(ArgumentPack.begin(), ArgumentPack.end(), PackedArgs);
2513 Converted.push_back(TemplateArgument(PackedArgs, ArgumentPack.size()));
2514 ArgumentPack.clear();
2515 }
2516 }
2517
2518 ++Param;
2519 }
2520
Douglas Gregorc15cb382009-02-09 23:23:08 +00002521 return Invalid;
2522}
2523
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002524namespace {
2525 class UnnamedLocalNoLinkageFinder
2526 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2527 {
2528 Sema &S;
2529 SourceRange SR;
2530
2531 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2532
2533 public:
2534 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2535
2536 bool Visit(QualType T) {
2537 return inherited::Visit(T.getTypePtr());
2538 }
2539
2540#define TYPE(Class, Parent) \
2541 bool Visit##Class##Type(const Class##Type *);
2542#define ABSTRACT_TYPE(Class, Parent) \
2543 bool Visit##Class##Type(const Class##Type *) { return false; }
2544#define NON_CANONICAL_TYPE(Class, Parent) \
2545 bool Visit##Class##Type(const Class##Type *) { return false; }
2546#include "clang/AST/TypeNodes.def"
2547
2548 bool VisitTagDecl(const TagDecl *Tag);
2549 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2550 };
2551}
2552
2553bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2554 return false;
2555}
2556
2557bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2558 return Visit(T->getElementType());
2559}
2560
2561bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2562 return Visit(T->getPointeeType());
2563}
2564
2565bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2566 const BlockPointerType* T) {
2567 return Visit(T->getPointeeType());
2568}
2569
2570bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2571 const LValueReferenceType* T) {
2572 return Visit(T->getPointeeType());
2573}
2574
2575bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2576 const RValueReferenceType* T) {
2577 return Visit(T->getPointeeType());
2578}
2579
2580bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2581 const MemberPointerType* T) {
2582 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2583}
2584
2585bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2586 const ConstantArrayType* T) {
2587 return Visit(T->getElementType());
2588}
2589
2590bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2591 const IncompleteArrayType* T) {
2592 return Visit(T->getElementType());
2593}
2594
2595bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2596 const VariableArrayType* T) {
2597 return Visit(T->getElementType());
2598}
2599
2600bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2601 const DependentSizedArrayType* T) {
2602 return Visit(T->getElementType());
2603}
2604
2605bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2606 const DependentSizedExtVectorType* T) {
2607 return Visit(T->getElementType());
2608}
2609
2610bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2611 return Visit(T->getElementType());
2612}
2613
2614bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2615 return Visit(T->getElementType());
2616}
2617
2618bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2619 const FunctionProtoType* T) {
2620 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2621 AEnd = T->arg_type_end();
2622 A != AEnd; ++A) {
2623 if (Visit(*A))
2624 return true;
2625 }
2626
2627 return Visit(T->getResultType());
2628}
2629
2630bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2631 const FunctionNoProtoType* T) {
2632 return Visit(T->getResultType());
2633}
2634
2635bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2636 const UnresolvedUsingType*) {
2637 return false;
2638}
2639
2640bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2641 return false;
2642}
2643
2644bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2645 return Visit(T->getUnderlyingType());
2646}
2647
2648bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2649 return false;
2650}
2651
2652bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2653 return VisitTagDecl(T->getDecl());
2654}
2655
2656bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2657 return VisitTagDecl(T->getDecl());
2658}
2659
2660bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2661 const TemplateTypeParmType*) {
2662 return false;
2663}
2664
2665bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2666 const TemplateSpecializationType*) {
2667 return false;
2668}
2669
2670bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2671 const InjectedClassNameType* T) {
2672 return VisitTagDecl(T->getDecl());
2673}
2674
2675bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2676 const DependentNameType* T) {
2677 return VisitNestedNameSpecifier(T->getQualifier());
2678}
2679
2680bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2681 const DependentTemplateSpecializationType* T) {
2682 return VisitNestedNameSpecifier(T->getQualifier());
2683}
2684
Douglas Gregor7536dd52010-12-20 02:24:11 +00002685bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
2686 const PackExpansionType* T) {
2687 return Visit(T->getPattern());
2688}
2689
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002690bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2691 return false;
2692}
2693
2694bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2695 const ObjCInterfaceType *) {
2696 return false;
2697}
2698
2699bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2700 const ObjCObjectPointerType *) {
2701 return false;
2702}
2703
2704bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2705 if (Tag->getDeclContext()->isFunctionOrMethod()) {
2706 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2707 << S.Context.getTypeDeclType(Tag) << SR;
2708 return true;
2709 }
2710
2711 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2712 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2713 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2714 return true;
2715 }
2716
2717 return false;
2718}
2719
2720bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2721 NestedNameSpecifier *NNS) {
2722 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2723 return true;
2724
2725 switch (NNS->getKind()) {
2726 case NestedNameSpecifier::Identifier:
2727 case NestedNameSpecifier::Namespace:
2728 case NestedNameSpecifier::Global:
2729 return false;
2730
2731 case NestedNameSpecifier::TypeSpec:
2732 case NestedNameSpecifier::TypeSpecWithTemplate:
2733 return Visit(QualType(NNS->getAsType(), 0));
2734 }
Fariborz Jahanian7b1ec6c2010-10-13 16:19:16 +00002735 return false;
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002736}
2737
2738
Douglas Gregorc15cb382009-02-09 23:23:08 +00002739/// \brief Check a template argument against its corresponding
2740/// template type parameter.
2741///
2742/// This routine implements the semantics of C++ [temp.arg.type]. It
2743/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002744bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002745 TypeSourceInfo *ArgInfo) {
2746 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002747 QualType Arg = ArgInfo->getType();
Douglas Gregor0fddb972010-05-22 16:17:30 +00002748 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth17fb8552010-09-03 21:12:34 +00002749
2750 if (Arg->isVariablyModifiedType()) {
2751 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002752 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00002753 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002754 }
2755
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002756 // C++03 [temp.arg.type]p2:
2757 // A local type, a type with no linkage, an unnamed type or a type
2758 // compounded from any of these types shall not be used as a
2759 // template-argument for a template type-parameter.
2760 //
2761 // C++0x allows these, and even in C++03 we allow them as an extension with
2762 // a warning.
Douglas Gregordb4d4bb2010-10-13 18:05:20 +00002763 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002764 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2765 (void)Finder.Visit(Context.getCanonicalType(Arg));
2766 }
2767
Douglas Gregorc15cb382009-02-09 23:23:08 +00002768 return false;
2769}
2770
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002771/// \brief Checks whether the given template argument is the address
2772/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002773static bool
2774CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2775 NonTypeTemplateParmDecl *Param,
2776 QualType ParamType,
2777 Expr *ArgIn,
2778 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002779 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002780 Expr *Arg = ArgIn;
2781 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002782
2783 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002784 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002785 Arg = Cast->getSubExpr();
2786
2787 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002788 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002789 // A template-argument for a non-type, non-template
2790 // template-parameter shall be one of: [...]
2791 //
2792 // -- the address of an object or function with external
2793 // linkage, including function templates and function
2794 // template-ids but excluding non-static class members,
2795 // expressed as & id-expression where the & is optional if
2796 // the name refers to a function or array, or if the
2797 // corresponding template-parameter is a reference; or
2798 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002799
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002800 // In C++98/03 mode, give an extension warning on any extra parentheses.
2801 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2802 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002803 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002804 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002805 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002806 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002807 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002808 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002809 }
2810
2811 Arg = Parens->getSubExpr();
2812 }
2813
Douglas Gregorb7a09262010-04-01 18:32:35 +00002814 bool AddressTaken = false;
2815 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002816 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002817 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002818 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002819 AddressTaken = true;
2820 AddrOpLoc = UnOp->getOperatorLoc();
2821 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002822 } else
2823 DRE = dyn_cast<DeclRefExpr>(Arg);
2824
Douglas Gregorb7a09262010-04-01 18:32:35 +00002825 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002826 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2827 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002828 S.Diag(Param->getLocation(), diag::note_template_param_here);
2829 return true;
2830 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002831
2832 // Stop checking the precise nature of the argument if it is value dependent,
2833 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002834 if (Arg->isValueDependent()) {
John McCall3fa5cae2010-10-26 07:05:15 +00002835 Converted = TemplateArgument(ArgIn);
Chandler Carruth038cc392010-01-31 10:01:20 +00002836 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002837 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002838
Douglas Gregorb7a09262010-04-01 18:32:35 +00002839 if (!isa<ValueDecl>(DRE->getDecl())) {
2840 S.Diag(Arg->getSourceRange().getBegin(),
2841 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002842 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002843 S.Diag(Param->getLocation(), diag::note_template_param_here);
2844 return true;
2845 }
2846
2847 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002848
2849 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002850 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2851 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002852 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002853 S.Diag(Param->getLocation(), diag::note_template_param_here);
2854 return true;
2855 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002856
2857 // Cannot refer to non-static member functions
2858 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002859 if (!Method->isStatic()) {
2860 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002861 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002862 S.Diag(Param->getLocation(), diag::note_template_param_here);
2863 return true;
2864 }
Mike Stump1eb44332009-09-09 15:08:12 +00002865
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002866 // Functions must have external linkage.
2867 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002868 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002869 S.Diag(Arg->getSourceRange().getBegin(),
2870 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002871 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002872 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002873 << true;
2874 return true;
2875 }
2876
2877 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002878 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002879
Douglas Gregorb7a09262010-04-01 18:32:35 +00002880 // If the template parameter has pointer type, the function decays.
2881 if (ParamType->isPointerType() && !AddressTaken)
2882 ArgType = S.Context.getPointerType(Func->getType());
2883 else if (AddressTaken && ParamType->isReferenceType()) {
2884 // If we originally had an address-of operator, but the
2885 // parameter has reference type, complain and (if things look
2886 // like they will work) drop the address-of operator.
2887 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2888 ParamType.getNonReferenceType())) {
2889 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2890 << ParamType;
2891 S.Diag(Param->getLocation(), diag::note_template_param_here);
2892 return true;
2893 }
2894
2895 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2896 << ParamType
2897 << FixItHint::CreateRemoval(AddrOpLoc);
2898 S.Diag(Param->getLocation(), diag::note_template_param_here);
2899
2900 ArgType = Func->getType();
2901 }
2902 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002903 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002904 S.Diag(Arg->getSourceRange().getBegin(),
2905 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002906 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002907 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002908 << true;
2909 return true;
2910 }
2911
Douglas Gregorb7a09262010-04-01 18:32:35 +00002912 // A value of reference type is not an object.
2913 if (Var->getType()->isReferenceType()) {
2914 S.Diag(Arg->getSourceRange().getBegin(),
2915 diag::err_template_arg_reference_var)
2916 << Var->getType() << Arg->getSourceRange();
2917 S.Diag(Param->getLocation(), diag::note_template_param_here);
2918 return true;
2919 }
2920
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002921 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002922 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002923
2924 // If the template parameter has pointer type, we must have taken
2925 // the address of this object.
2926 if (ParamType->isReferenceType()) {
2927 if (AddressTaken) {
2928 // If we originally had an address-of operator, but the
2929 // parameter has reference type, complain and (if things look
2930 // like they will work) drop the address-of operator.
2931 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2932 ParamType.getNonReferenceType())) {
2933 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2934 << ParamType;
2935 S.Diag(Param->getLocation(), diag::note_template_param_here);
2936 return true;
2937 }
2938
2939 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2940 << ParamType
2941 << FixItHint::CreateRemoval(AddrOpLoc);
2942 S.Diag(Param->getLocation(), diag::note_template_param_here);
2943
2944 ArgType = Var->getType();
2945 }
2946 } else if (!AddressTaken && ParamType->isPointerType()) {
2947 if (Var->getType()->isArrayType()) {
2948 // Array-to-pointer decay.
2949 ArgType = S.Context.getArrayDecayedType(Var->getType());
2950 } else {
2951 // If the template parameter has pointer type but the address of
2952 // this object was not taken, complain and (possibly) recover by
2953 // taking the address of the entity.
2954 ArgType = S.Context.getPointerType(Var->getType());
2955 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2956 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2957 << ParamType;
2958 S.Diag(Param->getLocation(), diag::note_template_param_here);
2959 return true;
2960 }
2961
2962 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2963 << ParamType
2964 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2965
2966 S.Diag(Param->getLocation(), diag::note_template_param_here);
2967 }
2968 }
2969 } else {
2970 // We found something else, but we don't know specifically what it is.
2971 S.Diag(Arg->getSourceRange().getBegin(),
2972 diag::err_template_arg_not_object_or_func)
2973 << Arg->getSourceRange();
2974 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2975 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002976 }
Mike Stump1eb44332009-09-09 15:08:12 +00002977
Douglas Gregorb7a09262010-04-01 18:32:35 +00002978 if (ParamType->isPointerType() &&
2979 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2980 S.IsQualificationConversion(ArgType, ParamType)) {
2981 // For pointer-to-object types, qualification conversions are
2982 // permitted.
2983 } else {
2984 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2985 if (!ParamRef->getPointeeType()->isFunctionType()) {
2986 // C++ [temp.arg.nontype]p5b3:
2987 // For a non-type template-parameter of type reference to
2988 // object, no conversions apply. The type referred to by the
2989 // reference may be more cv-qualified than the (otherwise
2990 // identical) type of the template- argument. The
2991 // template-parameter is bound directly to the
2992 // template-argument, which shall be an lvalue.
2993
2994 // FIXME: Other qualifiers?
2995 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2996 unsigned ArgQuals = ArgType.getCVRQualifiers();
2997
2998 if ((ParamQuals | ArgQuals) != ParamQuals) {
2999 S.Diag(Arg->getSourceRange().getBegin(),
3000 diag::err_template_arg_ref_bind_ignores_quals)
3001 << ParamType << Arg->getType()
3002 << Arg->getSourceRange();
3003 S.Diag(Param->getLocation(), diag::note_template_param_here);
3004 return true;
3005 }
3006 }
3007 }
3008
3009 // At this point, the template argument refers to an object or
3010 // function with external linkage. We now need to check whether the
3011 // argument and parameter types are compatible.
3012 if (!S.Context.hasSameUnqualifiedType(ArgType,
3013 ParamType.getNonReferenceType())) {
3014 // We can't perform this conversion or binding.
3015 if (ParamType->isReferenceType())
3016 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
3017 << ParamType << Arg->getType() << Arg->getSourceRange();
3018 else
3019 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
3020 << Arg->getType() << ParamType << Arg->getSourceRange();
3021 S.Diag(Param->getLocation(), diag::note_template_param_here);
3022 return true;
3023 }
3024 }
3025
3026 // Create the template argument.
3027 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00003028 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00003029 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003030}
3031
3032/// \brief Checks whether the given template argument is a pointer to
3033/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003034bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
3035 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003036 bool Invalid = false;
3037
3038 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003039 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003040 Arg = Cast->getSubExpr();
3041
3042 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003043 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003044 // A template-argument for a non-type, non-template
3045 // template-parameter shall be one of: [...]
3046 //
3047 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003048 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003049
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003050 // In C++98/03 mode, give an extension warning on any extra parentheses.
3051 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3052 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003053 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003054 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00003055 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003056 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003057 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003058 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003059 }
3060
3061 Arg = Parens->getSubExpr();
3062 }
3063
Douglas Gregorcaddba02009-11-12 18:38:13 +00003064 // A pointer-to-member constant written &Class::member.
3065 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00003066 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00003067 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3068 if (DRE && !DRE->getQualifier())
3069 DRE = 0;
3070 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00003071 }
3072 // A constant of pointer-to-member type.
3073 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
3074 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
3075 if (VD->getType()->isMemberPointerType()) {
3076 if (isa<NonTypeTemplateParmDecl>(VD) ||
3077 (isa<VarDecl>(VD) &&
3078 Context.getCanonicalType(VD->getType()).isConstQualified())) {
3079 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003080 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003081 else
3082 Converted = TemplateArgument(VD->getCanonicalDecl());
3083 return Invalid;
3084 }
3085 }
3086 }
3087
3088 DRE = 0;
3089 }
3090
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003091 if (!DRE)
3092 return Diag(Arg->getSourceRange().getBegin(),
3093 diag::err_template_arg_not_pointer_to_member_form)
3094 << Arg->getSourceRange();
3095
3096 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3097 assert((isa<FieldDecl>(DRE->getDecl()) ||
3098 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3099 "Only non-static member pointers can make it here");
3100
3101 // Okay: this is the address of a non-static member, and therefore
3102 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003103 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003104 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003105 else
3106 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003107 return Invalid;
3108 }
3109
3110 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00003111 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003112 diag::err_template_arg_not_pointer_to_member_form)
3113 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003114 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003115 diag::note_template_arg_refers_here);
3116 return true;
3117}
3118
Douglas Gregorc15cb382009-02-09 23:23:08 +00003119/// \brief Check a template argument against its corresponding
3120/// non-type template parameter.
3121///
Douglas Gregor2943aed2009-03-03 04:44:36 +00003122/// This routine implements the semantics of C++ [temp.arg.nontype].
3123/// It returns true if an error occurred, and false otherwise. \p
3124/// InstantiatedParamType is the type of the non-type template
3125/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003126///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003127/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00003128bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00003129 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00003130 TemplateArgument &Converted,
3131 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00003132 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3133
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003134 // If either the parameter has a dependent type or the argument is
3135 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00003136 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3137 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003138 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003139 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00003140 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003141
3142 // C++ [temp.arg.nontype]p5:
3143 // The following conversions are performed on each expression used
3144 // as a non-type template-argument. If a non-type
3145 // template-argument cannot be converted to the type of the
3146 // corresponding template-parameter then the program is
3147 // ill-formed.
3148 //
3149 // -- for a non-type template-parameter of integral or
3150 // enumeration type, integral promotions (4.5) and integral
3151 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00003152 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00003153 QualType ArgType = Arg->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003154 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003155 // C++ [temp.arg.nontype]p1:
3156 // A template-argument for a non-type, non-template
3157 // template-parameter shall be one of:
3158 //
3159 // -- an integral constant-expression of integral or enumeration
3160 // type; or
3161 // -- the name of a non-type template-parameter; or
3162 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003163 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003164 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003165 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003166 diag::err_template_arg_not_integral_or_enumeral)
3167 << ArgType << Arg->getSourceRange();
3168 Diag(Param->getLocation(), diag::note_template_param_here);
3169 return true;
3170 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003171 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003172 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3173 << ArgType << Arg->getSourceRange();
3174 return true;
3175 }
3176
Douglas Gregor02024a92010-03-28 02:42:43 +00003177 // From here on out, all we care about are the unqualified forms
3178 // of the parameter and argument types.
3179 ParamType = ParamType.getUnqualifiedType();
3180 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003181
3182 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00003183 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003184 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00003185 } else if (CTAK == CTAK_Deduced) {
3186 // C++ [temp.deduct.type]p17:
3187 // If, in the declaration of a function template with a non-type
3188 // template-parameter, the non-type template- parameter is used
3189 // in an expression in the function parameter-list and, if the
3190 // corresponding template-argument is deduced, the
3191 // template-argument type shall match the type of the
3192 // template-parameter exactly, except that a template-argument
3193 // deduced from an array bound may be of any integral type.
3194 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3195 << ArgType << ParamType;
3196 Diag(Param->getLocation(), diag::note_template_param_here);
John McCalldaa8e4e2010-11-15 09:13:47 +00003197 return true;
3198 } else if (ParamType->isBooleanType()) {
3199 // This is an integral-to-boolean conversion.
3200 ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003201 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3202 !ParamType->isEnumeralType()) {
3203 // This is an integral promotion or conversion.
John McCall2de56d12010-08-25 11:45:40 +00003204 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003205 } else {
3206 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003207 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003208 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003209 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003210 Diag(Param->getLocation(), diag::note_template_param_here);
3211 return true;
3212 }
3213
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003214 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00003215 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003216 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003217
3218 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003219 llvm::APSInt OldValue = Value;
3220
3221 // Coerce the template argument's value to the value it will have
3222 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003223 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003224 if (Value.getBitWidth() != AllowedBits)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003225 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003226 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003227
3228 // Complain if an unsigned parameter received a negative value.
3229 if (IntegerType->isUnsignedIntegerType()
3230 && (OldValue.isSigned() && OldValue.isNegative())) {
3231 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3232 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3233 << Arg->getSourceRange();
3234 Diag(Param->getLocation(), diag::note_template_param_here);
3235 }
3236
3237 // Complain if we overflowed the template parameter's type.
3238 unsigned RequiredBits;
3239 if (IntegerType->isUnsignedIntegerType())
3240 RequiredBits = OldValue.getActiveBits();
3241 else if (OldValue.isUnsigned())
3242 RequiredBits = OldValue.getActiveBits() + 1;
3243 else
3244 RequiredBits = OldValue.getMinSignedBits();
3245 if (RequiredBits > AllowedBits) {
3246 Diag(Arg->getSourceRange().getBegin(),
3247 diag::warn_template_arg_too_large)
3248 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3249 << Arg->getSourceRange();
3250 Diag(Param->getLocation(), diag::note_template_param_here);
3251 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003252 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003253
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003254 // Add the value of this argument to the list of converted
3255 // arguments. We use the bitwidth and signedness of the template
3256 // parameter.
3257 if (Arg->isValueDependent()) {
3258 // The argument is value-dependent. Create a new
3259 // TemplateArgument with the converted expression.
3260 Converted = TemplateArgument(Arg);
3261 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003262 }
3263
John McCall833ca992009-10-29 08:12:44 +00003264 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00003265 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003266 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003267 return false;
3268 }
Douglas Gregora35284b2009-02-11 00:19:33 +00003269
John McCall6bb80172010-03-30 21:47:33 +00003270 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3271
Douglas Gregorb7a09262010-04-01 18:32:35 +00003272 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3273 // from a template argument of type std::nullptr_t to a non-type
3274 // template parameter of type pointer to object, pointer to
3275 // function, or pointer-to-member, respectively.
3276 if (ArgType->isNullPtrType() &&
3277 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3278 Converted = TemplateArgument((NamedDecl *)0);
3279 return false;
3280 }
3281
Douglas Gregorb86b0572009-02-11 01:18:59 +00003282 // Handle pointer-to-function, reference-to-function, and
3283 // pointer-to-member-function all in (roughly) the same way.
3284 if (// -- For a non-type template-parameter of type pointer to
3285 // function, only the function-to-pointer conversion (4.3) is
3286 // applied. If the template-argument represents a set of
3287 // overloaded functions (or a pointer to such), the matching
3288 // function is selected from the set (13.4).
3289 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003290 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003291 // -- For a non-type template-parameter of type reference to
3292 // function, no conversions apply. If the template-argument
3293 // represents a set of overloaded functions, the matching
3294 // function is selected from the set (13.4).
3295 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003296 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003297 // -- For a non-type template-parameter of type pointer to
3298 // member function, no conversions apply. If the
3299 // template-argument represents a set of overloaded member
3300 // functions, the matching member function is selected from
3301 // the set (13.4).
3302 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003303 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00003304 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003305
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003306 if (Arg->getType() == Context.OverloadTy) {
3307 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3308 true,
3309 FoundResult)) {
3310 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3311 return true;
3312
3313 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3314 ArgType = Arg->getType();
3315 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003316 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00003317 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003318
Douglas Gregorb7a09262010-04-01 18:32:35 +00003319 if (!ParamType->isMemberPointerType())
3320 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3321 ParamType,
3322 Arg, Converted);
3323
3324 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCall2de56d12010-08-25 11:45:40 +00003325 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb7a09262010-04-01 18:32:35 +00003326 } else if (!Context.hasSameUnqualifiedType(ArgType,
3327 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00003328 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003329 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00003330 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003331 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00003332 Diag(Param->getLocation(), diag::note_template_param_here);
3333 return true;
3334 }
Mike Stump1eb44332009-09-09 15:08:12 +00003335
Douglas Gregorb7a09262010-04-01 18:32:35 +00003336 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00003337 }
3338
Chris Lattnerfe90de72009-02-20 21:37:53 +00003339 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003340 // -- for a non-type template-parameter of type pointer to
3341 // object, qualification conversions (4.4) and the
3342 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00003343 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00003344 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003345 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003346
Douglas Gregorb7a09262010-04-01 18:32:35 +00003347 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3348 ParamType,
3349 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003350 }
Mike Stump1eb44332009-09-09 15:08:12 +00003351
Ted Kremenek6217b802009-07-29 21:53:49 +00003352 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003353 // -- For a non-type template-parameter of type reference to
3354 // object, no conversions apply. The type referred to by the
3355 // reference may be more cv-qualified than the (otherwise
3356 // identical) type of the template-argument. The
3357 // template-parameter is bound directly to the
3358 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00003359 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003360 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003361
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003362 if (Arg->getType() == Context.OverloadTy) {
3363 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3364 ParamRefType->getPointeeType(),
3365 true,
3366 FoundResult)) {
3367 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3368 return true;
3369
3370 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3371 ArgType = Arg->getType();
3372 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00003373 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00003374 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003375
Douglas Gregorb7a09262010-04-01 18:32:35 +00003376 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3377 ParamType,
3378 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00003379 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00003380
3381 // -- For a non-type template-parameter of type pointer to data
3382 // member, qualification conversions (4.4) are applied.
3383 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3384
Douglas Gregor8e6563b2009-02-11 18:22:40 +00003385 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00003386 // Types match exactly: nothing more to do here.
3387 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCall2de56d12010-08-25 11:45:40 +00003388 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor658bbb52009-02-11 16:16:59 +00003389 } else {
3390 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003391 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00003392 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003393 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00003394 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00003395 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00003396 }
3397
Douglas Gregorcaddba02009-11-12 18:38:13 +00003398 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00003399}
3400
3401/// \brief Check a template argument against its corresponding
3402/// template template parameter.
3403///
3404/// This routine implements the semantics of C++ [temp.arg.template].
3405/// It returns true if an error occurred, and false otherwise.
3406bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003407 const TemplateArgumentLoc &Arg) {
3408 TemplateName Name = Arg.getArgument().getAsTemplate();
3409 TemplateDecl *Template = Name.getAsTemplateDecl();
3410 if (!Template) {
3411 // Any dependent template name is fine.
3412 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3413 return false;
3414 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003415
3416 // C++ [temp.arg.template]p1:
3417 // A template-argument for a template template-parameter shall be
3418 // the name of a class template, expressed as id-expression. Only
3419 // primary class templates are considered when matching the
3420 // template template argument with the corresponding parameter;
3421 // partial specializations are not considered even if their
3422 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003423 //
3424 // Note that we also allow template template parameters here, which
3425 // will happen when we are dealing with, e.g., class template
3426 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003427 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003428 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003429 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003430 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003431 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003432 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003433 << Template;
3434 }
3435
3436 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3437 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003438 true,
3439 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003440 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003441}
3442
Douglas Gregor02024a92010-03-28 02:42:43 +00003443/// \brief Given a non-type template argument that refers to a
3444/// declaration and the type of its corresponding non-type template
3445/// parameter, produce an expression that properly refers to that
3446/// declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00003447ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003448Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3449 QualType ParamType,
3450 SourceLocation Loc) {
3451 assert(Arg.getKind() == TemplateArgument::Declaration &&
3452 "Only declaration template arguments permitted here");
3453 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3454
3455 if (VD->getDeclContext()->isRecord() &&
3456 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3457 // If the value is a class member, we might have a pointer-to-member.
3458 // Determine whether the non-type template template parameter is of
3459 // pointer-to-member type. If so, we need to build an appropriate
3460 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3461 // would refer to the member itself.
3462 if (ParamType->isMemberPointerType()) {
3463 QualType ClassType
3464 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3465 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00003466 = NestedNameSpecifier::Create(Context, 0, false,
3467 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00003468 CXXScopeSpec SS;
3469 SS.setScopeRep(Qualifier);
John McCalldfa1edb2010-11-23 20:48:44 +00003470
3471 // The actual value-ness of this is unimportant, but for
3472 // internal consistency's sake, references to instance methods
3473 // are r-values.
3474 ExprValueKind VK = VK_LValue;
3475 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
3476 VK = VK_RValue;
3477
John McCall60d7b3a2010-08-24 06:29:42 +00003478 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCallf89e55a2010-11-18 06:31:45 +00003479 VD->getType().getNonReferenceType(),
John McCalldfa1edb2010-11-23 20:48:44 +00003480 VK,
John McCallf89e55a2010-11-18 06:31:45 +00003481 Loc,
3482 &SS);
Douglas Gregor02024a92010-03-28 02:42:43 +00003483 if (RefExpr.isInvalid())
3484 return ExprError();
3485
John McCall2de56d12010-08-25 11:45:40 +00003486 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorc0c83002010-04-30 21:46:38 +00003487
3488 // We might need to perform a trailing qualification conversion, since
3489 // the element type on the parameter could be more qualified than the
3490 // element type in the expression we constructed.
3491 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3492 ParamType.getUnqualifiedType())) {
3493 Expr *RefE = RefExpr.takeAs<Expr>();
John McCall2de56d12010-08-25 11:45:40 +00003494 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorc0c83002010-04-30 21:46:38 +00003495 RefExpr = Owned(RefE);
3496 }
3497
Douglas Gregor02024a92010-03-28 02:42:43 +00003498 assert(!RefExpr.isInvalid() &&
3499 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003500 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003501 return move(RefExpr);
3502 }
3503 }
3504
3505 QualType T = VD->getType().getNonReferenceType();
3506 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003507 // When the non-type template parameter is a pointer, take the
3508 // address of the declaration.
John McCallf89e55a2010-11-18 06:31:45 +00003509 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003510 if (RefExpr.isInvalid())
3511 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003512
3513 if (T->isFunctionType() || T->isArrayType()) {
3514 // Decay functions and arrays.
3515 Expr *RefE = (Expr *)RefExpr.get();
3516 DefaultFunctionArrayConversion(RefE);
3517 if (RefE != RefExpr.get()) {
3518 RefExpr.release();
3519 RefExpr = Owned(RefE);
3520 }
3521
3522 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003523 }
3524
Douglas Gregorb7a09262010-04-01 18:32:35 +00003525 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00003526 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00003527 }
3528
John McCallf89e55a2010-11-18 06:31:45 +00003529 ExprValueKind VK = VK_RValue;
3530
Douglas Gregor02024a92010-03-28 02:42:43 +00003531 // If the non-type template parameter has reference type, qualify the
3532 // resulting declaration reference with the extra qualifiers on the
3533 // type that the reference refers to.
John McCallf89e55a2010-11-18 06:31:45 +00003534 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
3535 VK = VK_LValue;
3536 T = Context.getQualifiedType(T,
3537 TargetRef->getPointeeType().getQualifiers());
3538 }
Douglas Gregor02024a92010-03-28 02:42:43 +00003539
John McCallf89e55a2010-11-18 06:31:45 +00003540 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003541}
3542
3543/// \brief Construct a new expression that refers to the given
3544/// integral template argument with the given source-location
3545/// information.
3546///
3547/// This routine takes care of the mapping from an integral template
3548/// argument (which may have any integral type) to the appropriate
3549/// literal value.
John McCall60d7b3a2010-08-24 06:29:42 +00003550ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003551Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3552 SourceLocation Loc) {
3553 assert(Arg.getKind() == TemplateArgument::Integral &&
3554 "Operation is only value for integral template arguments");
3555 QualType T = Arg.getIntegralType();
3556 if (T->isCharType() || T->isWideCharType())
3557 return Owned(new (Context) CharacterLiteral(
3558 Arg.getAsIntegral()->getZExtValue(),
3559 T->isWideCharType(),
3560 T,
3561 Loc));
3562 if (T->isBooleanType())
3563 return Owned(new (Context) CXXBoolLiteralExpr(
3564 Arg.getAsIntegral()->getBoolValue(),
3565 T,
3566 Loc));
3567
Peter Collingbournefb7b3632010-12-15 15:06:14 +00003568 QualType BT;
3569 if (const EnumType *ET = T->getAs<EnumType>())
3570 BT = ET->getDecl()->getPromotionType();
3571 else
3572 BT = T;
3573
3574 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
3575 ImpCastExprToType(E, T, CK_IntegralCast);
3576
3577 return Owned(E);
Douglas Gregor02024a92010-03-28 02:42:43 +00003578}
3579
3580
Douglas Gregorddc29e12009-02-06 22:42:48 +00003581/// \brief Determine whether the given template parameter lists are
3582/// equivalent.
3583///
Mike Stump1eb44332009-09-09 15:08:12 +00003584/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003585/// source code as part of a new template declaration.
3586///
3587/// \param Old The old template parameter list, typically found via
3588/// name lookup of the template declared with this template parameter
3589/// list.
3590///
3591/// \param Complain If true, this routine will produce a diagnostic if
3592/// the template parameter lists are not equivalent.
3593///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003594/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003595///
3596/// \param TemplateArgLoc If this source location is valid, then we
3597/// are actually checking the template parameter list of a template
3598/// argument (New) against the template parameter list of its
3599/// corresponding template template parameter (Old). We produce
3600/// slightly different diagnostics in this scenario.
3601///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003602/// \returns True if the template parameter lists are equal, false
3603/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003604bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003605Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3606 TemplateParameterList *Old,
3607 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003608 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003609 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003610 if (Old->size() != New->size()) {
3611 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003612 unsigned NextDiag = diag::err_template_param_list_different_arity;
3613 if (TemplateArgLoc.isValid()) {
3614 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3615 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003616 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003617 Diag(New->getTemplateLoc(), NextDiag)
3618 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003619 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003620 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003621 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003622 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003623 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3624 }
3625
3626 return false;
3627 }
3628
3629 for (TemplateParameterList::iterator OldParm = Old->begin(),
3630 OldParmEnd = Old->end(), NewParm = New->begin();
3631 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3632 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003633 if (Complain) {
3634 unsigned NextDiag = diag::err_template_param_different_kind;
3635 if (TemplateArgLoc.isValid()) {
3636 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3637 NextDiag = diag::note_template_param_different_kind;
3638 }
3639 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003640 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003641 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003642 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003643 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003644 return false;
3645 }
3646
Douglas Gregora417b872010-06-04 08:34:32 +00003647 if (TemplateTypeParmDecl *OldTTP
3648 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3649 // Template type parameters are equivalent if either both are template
3650 // type parameter packs or neither are (since we know we're at the same
3651 // index).
3652 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3653 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3654 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3655 // allow one to match a template parameter pack in the template
3656 // parameter list of a template template parameter to one or more
3657 // template parameters in the template parameter list of the
3658 // corresponding template template argument.
3659 if (Complain) {
3660 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3661 if (TemplateArgLoc.isValid()) {
3662 Diag(TemplateArgLoc,
3663 diag::err_template_arg_template_params_mismatch);
3664 NextDiag = diag::note_template_parameter_pack_non_pack;
3665 }
3666 Diag(NewTTP->getLocation(), NextDiag)
3667 << 0 << NewTTP->isParameterPack();
3668 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3669 << 0 << OldTTP->isParameterPack();
3670 }
3671 return false;
3672 }
Mike Stump1eb44332009-09-09 15:08:12 +00003673 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003674 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3675 // The types of non-type template parameters must agree.
3676 NonTypeTemplateParmDecl *NewNTTP
3677 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003678
3679 // If we are matching a template template argument to a template
3680 // template parameter and one of the non-type template parameter types
3681 // is dependent, then we must wait until template instantiation time
3682 // to actually compare the arguments.
3683 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3684 (OldNTTP->getType()->isDependentType() ||
3685 NewNTTP->getType()->isDependentType()))
3686 continue;
3687
Douglas Gregorddc29e12009-02-06 22:42:48 +00003688 if (Context.getCanonicalType(OldNTTP->getType()) !=
3689 Context.getCanonicalType(NewNTTP->getType())) {
3690 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003691 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3692 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003693 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003694 diag::err_template_arg_template_params_mismatch);
3695 NextDiag = diag::note_template_nontype_parm_different_type;
3696 }
3697 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003698 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003699 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003700 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003701 diag::note_template_nontype_parm_prev_declaration)
3702 << OldNTTP->getType();
3703 }
3704 return false;
3705 }
3706 } else {
3707 // The template parameter lists of template template
3708 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003709 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003710 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003711 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003712 = cast<TemplateTemplateParmDecl>(*OldParm);
3713 TemplateTemplateParmDecl *NewTTP
3714 = cast<TemplateTemplateParmDecl>(*NewParm);
3715 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3716 OldTTP->getTemplateParameters(),
3717 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003718 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003719 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003720 return false;
3721 }
3722 }
3723
3724 return true;
3725}
3726
3727/// \brief Check whether a template can be declared within this scope.
3728///
3729/// If the template declaration is valid in this scope, returns
3730/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003731bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003732Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003733 // Find the nearest enclosing declaration scope.
3734 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3735 (S->getFlags() & Scope::TemplateParamScope) != 0)
3736 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003737
Douglas Gregorddc29e12009-02-06 22:42:48 +00003738 // C++ [temp]p2:
3739 // A template-declaration can appear only as a namespace scope or
3740 // class scope declaration.
3741 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003742 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3743 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003744 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003745 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003746
Eli Friedman1503f772009-07-31 01:43:05 +00003747 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003748 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003749
3750 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3751 return false;
3752
Mike Stump1eb44332009-09-09 15:08:12 +00003753 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003754 diag::err_template_outside_namespace_or_class_scope)
3755 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003756}
Douglas Gregorcc636682009-02-17 23:15:12 +00003757
Douglas Gregord5cb8762009-10-07 00:13:32 +00003758/// \brief Determine what kind of template specialization the given declaration
3759/// is.
3760static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3761 if (!D)
3762 return TSK_Undeclared;
3763
Douglas Gregorf6b11852009-10-08 15:14:33 +00003764 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3765 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003766 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3767 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003768 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3769 return Var->getTemplateSpecializationKind();
3770
Douglas Gregord5cb8762009-10-07 00:13:32 +00003771 return TSK_Undeclared;
3772}
3773
Douglas Gregor9302da62009-10-14 23:50:59 +00003774/// \brief Check whether a specialization is well-formed in the current
3775/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003776///
Douglas Gregor9302da62009-10-14 23:50:59 +00003777/// This routine determines whether a template specialization can be declared
3778/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003779///
3780/// \param S the semantic analysis object for which this check is being
3781/// performed.
3782///
3783/// \param Specialized the entity being specialized or instantiated, which
3784/// may be a kind of template (class template, function template, etc.) or
3785/// a member of a class template (member function, static data member,
3786/// member class).
3787///
3788/// \param PrevDecl the previous declaration of this entity, if any.
3789///
3790/// \param Loc the location of the explicit specialization or instantiation of
3791/// this entity.
3792///
3793/// \param IsPartialSpecialization whether this is a partial specialization of
3794/// a class template.
3795///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003796/// \returns true if there was an error that we cannot recover from, false
3797/// otherwise.
3798static bool CheckTemplateSpecializationScope(Sema &S,
3799 NamedDecl *Specialized,
3800 NamedDecl *PrevDecl,
3801 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003802 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003803 // Keep these "kind" numbers in sync with the %select statements in the
3804 // various diagnostics emitted by this routine.
3805 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003806 bool isTemplateSpecialization = false;
3807 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003808 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003809 isTemplateSpecialization = true;
3810 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003811 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003812 isTemplateSpecialization = true;
3813 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003814 EntityKind = 3;
3815 else if (isa<VarDecl>(Specialized))
3816 EntityKind = 4;
3817 else if (isa<RecordDecl>(Specialized))
3818 EntityKind = 5;
3819 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003820 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3821 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003822 return true;
3823 }
3824
Douglas Gregor88b70942009-02-25 22:02:03 +00003825 // C++ [temp.expl.spec]p2:
3826 // An explicit specialization shall be declared in the namespace
3827 // of which the template is a member, or, for member templates, in
3828 // the namespace of which the enclosing class or enclosing class
3829 // template is a member. An explicit specialization of a member
3830 // function, member class or static data member of a class
3831 // template shall be declared in the namespace of which the class
3832 // template is a member. Such a declaration may also be a
3833 // definition. If the declaration is not a definition, the
3834 // specialization may be defined later in the name- space in which
3835 // the explicit specialization was declared, or in a namespace
3836 // that encloses the one in which the explicit specialization was
3837 // declared.
Sebastian Redl7a126a42010-08-31 00:36:30 +00003838 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003839 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003840 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003841 return true;
3842 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003843
Douglas Gregor0a407472009-10-07 17:30:37 +00003844 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3845 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003846 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003847 return true;
3848 }
3849
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003850 // C++ [temp.class.spec]p6:
3851 // A class template partial specialization may be declared or redeclared
3852 // in any namespace scope in which its definition may be defined (14.5.1
3853 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003854 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003855 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003856 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003857 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003858 if ((!PrevDecl ||
3859 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3860 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregor121dc9a2010-09-12 05:08:28 +00003861 // C++ [temp.exp.spec]p2:
3862 // An explicit specialization shall be declared in the namespace of which
3863 // the template is a member, or, for member templates, in the namespace
3864 // of which the enclosing class or enclosing class template is a member.
3865 // An explicit specialization of a member function, member class or
3866 // static data member of a class template shall be declared in the
3867 // namespace of which the class template is a member.
3868 //
3869 // C++0x [temp.expl.spec]p2:
3870 // An explicit specialization shall be declared in a namespace enclosing
3871 // the specialized template.
3872 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3873 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregora4d5de52010-09-12 05:24:55 +00003874 bool IsCPlusPlus0xExtension
3875 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003876 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003877 S.Diag(Loc, IsCPlusPlus0xExtension
3878 ? diag::ext_template_spec_decl_out_of_scope_global
3879 : diag::err_template_spec_decl_out_of_scope_global)
3880 << EntityKind << Specialized;
Douglas Gregor9302da62009-10-14 23:50:59 +00003881 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003882 S.Diag(Loc, IsCPlusPlus0xExtension
3883 ? diag::ext_template_spec_decl_out_of_scope
3884 : diag::err_template_spec_decl_out_of_scope)
3885 << EntityKind << Specialized
3886 << cast<NamedDecl>(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003887
3888 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3889 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003890 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003891 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003892
3893 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003894 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003895 // Note that HandleDeclarator() performs this check for explicit
3896 // specializations of function templates, static data members, and member
3897 // functions, so we skip the check here for those kinds of entities.
3898 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003899 // Should we refactor that check, so that it occurs later?
3900 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003901 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3902 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003903 if (isa<TranslationUnitDecl>(SpecializedContext))
3904 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3905 << EntityKind << Specialized;
3906 else if (isa<NamespaceDecl>(SpecializedContext))
3907 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3908 << EntityKind << Specialized
3909 << cast<NamedDecl>(SpecializedContext);
3910
Douglas Gregor9302da62009-10-14 23:50:59 +00003911 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003912 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003913
3914 // FIXME: check for specialization-after-instantiation errors and such.
3915
Douglas Gregor88b70942009-02-25 22:02:03 +00003916 return false;
3917}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003918
Douglas Gregore94866f2009-06-12 21:21:02 +00003919/// \brief Check the non-type template arguments of a class template
3920/// partial specialization according to C++ [temp.class.spec]p9.
3921///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003922/// \param TemplateParams the template parameters of the primary class
3923/// template.
3924///
3925/// \param TemplateArg the template arguments of the class template
3926/// partial specialization.
3927///
Douglas Gregore94866f2009-06-12 21:21:02 +00003928/// \returns true if there was an error, false otherwise.
3929bool Sema::CheckClassTemplatePartialSpecializationArgs(
3930 TemplateParameterList *TemplateParams,
Douglas Gregorb9c66312010-12-23 17:13:55 +00003931 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor910f8002010-11-07 23:05:16 +00003932 const TemplateArgument *ArgList = TemplateArgs.data();
Mike Stump1eb44332009-09-09 15:08:12 +00003933
Douglas Gregore94866f2009-06-12 21:21:02 +00003934 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00003935 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003936 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregorb9c66312010-12-23 17:13:55 +00003937 if (!Param)
Douglas Gregore94866f2009-06-12 21:21:02 +00003938 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003939
Anders Carlsson6360be72009-06-13 18:20:51 +00003940 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003941 if (!ArgExpr) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003942 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003943 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003944
Douglas Gregorb9c66312010-12-23 17:13:55 +00003945 // FIXME: Variadic templates. Unwrap argument packs.
3946
Douglas Gregore94866f2009-06-12 21:21:02 +00003947 // C++ [temp.class.spec]p8:
3948 // A non-type argument is non-specialized if it is the name of a
3949 // non-type parameter. All other non-type arguments are
3950 // specialized.
3951 //
3952 // Below, we check the two conditions that only apply to
3953 // specialized non-type arguments, so skip any non-specialized
3954 // arguments.
3955 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorb9c66312010-12-23 17:13:55 +00003956 if (llvm::isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregore94866f2009-06-12 21:21:02 +00003957 continue;
Douglas Gregorb9c66312010-12-23 17:13:55 +00003958
Douglas Gregore94866f2009-06-12 21:21:02 +00003959 // C++ [temp.class.spec]p9:
3960 // Within the argument list of a class template partial
3961 // specialization, the following restrictions apply:
3962 // -- A partially specialized non-type argument expression
3963 // shall not involve a template parameter of the partial
3964 // specialization except when the argument expression is a
3965 // simple identifier.
3966 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003967 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003968 diag::err_dependent_non_type_arg_in_partial_spec)
3969 << ArgExpr->getSourceRange();
3970 return true;
3971 }
3972
3973 // -- The type of a template parameter corresponding to a
3974 // specialized non-type argument shall not be dependent on a
3975 // parameter of the specialization.
3976 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003977 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003978 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3979 << Param->getType()
3980 << ArgExpr->getSourceRange();
3981 Diag(Param->getLocation(), diag::note_template_param_here);
3982 return true;
3983 }
3984 }
3985
3986 return false;
3987}
3988
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003989/// \brief Retrieve the previous declaration of the given declaration.
3990static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3991 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3992 return VD->getPreviousDeclaration();
3993 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3994 return FD->getPreviousDeclaration();
3995 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3996 return TD->getPreviousDeclaration();
3997 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3998 return TD->getPreviousDeclaration();
3999 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4000 return FTD->getPreviousDeclaration();
4001 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
4002 return CTD->getPreviousDeclaration();
4003 return 0;
4004}
4005
John McCalld226f652010-08-21 09:40:31 +00004006DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00004007Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
4008 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00004009 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004010 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004011 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00004012 SourceLocation TemplateNameLoc,
4013 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00004014 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00004015 SourceLocation RAngleLoc,
4016 AttributeList *Attr,
4017 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004018 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00004019
Douglas Gregorcc636682009-02-17 23:15:12 +00004020 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00004021 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004022 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00004023 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
4024
4025 if (!ClassTemplate) {
4026 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
4027 << (Name.getAsTemplateDecl() &&
4028 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
4029 return true;
4030 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004031
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004032 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004033 bool isPartialSpecialization = false;
4034
Douglas Gregor88b70942009-02-25 22:02:03 +00004035 // Check the validity of the template headers that introduce this
4036 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004037 // FIXME: We probably shouldn't complain about these headers for
4038 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004039 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00004040 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00004041 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
4042 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004043 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00004044 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004045 isExplicitSpecialization,
4046 Invalid);
4047 if (Invalid)
4048 return true;
4049
Abramo Bagnara9b934882010-06-12 08:15:14 +00004050 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
4051 if (TemplateParams)
4052 --NumMatchedTemplateParamLists;
4053
Douglas Gregor05396e22009-08-25 17:23:04 +00004054 if (TemplateParams && TemplateParams->size() > 0) {
4055 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00004056
Douglas Gregorb0ee93c2010-12-21 08:14:57 +00004057 if (TUK == TUK_Friend) {
4058 Diag(KWLoc, diag::err_partial_specialization_friend)
4059 << SourceRange(LAngleLoc, RAngleLoc);
4060 return true;
4061 }
4062
Douglas Gregor05396e22009-08-25 17:23:04 +00004063 // C++ [temp.class.spec]p10:
4064 // The template parameter list of a specialization shall not
4065 // contain default template argument values.
4066 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4067 Decl *Param = TemplateParams->getParam(I);
4068 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4069 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004070 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004071 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00004072 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004073 }
4074 } else if (NonTypeTemplateParmDecl *NTTP
4075 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4076 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004077 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004078 diag::err_default_arg_in_partial_spec)
4079 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004080 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004081 }
4082 } else {
4083 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00004084 if (TTP->hasDefaultArgument()) {
4085 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004086 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00004087 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004088 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004089 }
4090 }
4091 }
Douglas Gregora735b202009-10-13 14:39:41 +00004092 } else if (TemplateParams) {
4093 if (TUK == TUK_Friend)
4094 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00004095 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00004096 SourceRange(TemplateParams->getTemplateLoc(),
4097 TemplateParams->getRAngleLoc()))
4098 << SourceRange(LAngleLoc, RAngleLoc);
4099 else
4100 isExplicitSpecialization = true;
4101 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00004102 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00004103 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004104 isExplicitSpecialization = true;
4105 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004106
Douglas Gregorcc636682009-02-17 23:15:12 +00004107 // Check that the specialization uses the same tag kind as the
4108 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004109 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4110 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004111 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004112 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004113 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004114 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00004115 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004116 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00004117 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004118 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004119 diag::note_previous_use);
4120 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4121 }
4122
Douglas Gregor40808ce2009-03-09 23:48:35 +00004123 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004124 TemplateArgumentListInfo TemplateArgs;
4125 TemplateArgs.setLAngleLoc(LAngleLoc);
4126 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004127 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00004128
Douglas Gregor925910d2011-01-03 20:35:03 +00004129 // Check for unexpanded parameter packs in any of the template arguments.
4130 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4131 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4132 UPPC_PartialSpecialization))
4133 return true;
4134
Douglas Gregorcc636682009-02-17 23:15:12 +00004135 // Check that the template argument list is well-formed for this
4136 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00004137 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00004138 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4139 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004140 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004141
Douglas Gregor910f8002010-11-07 23:05:16 +00004142 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregorcc636682009-02-17 23:15:12 +00004143 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004144
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004145 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00004146 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004147 if (isPartialSpecialization) {
Douglas Gregore94866f2009-06-12 21:21:02 +00004148 if (CheckClassTemplatePartialSpecializationArgs(
4149 ClassTemplate->getTemplateParameters(),
Douglas Gregorb9c66312010-12-23 17:13:55 +00004150 Converted))
Douglas Gregore94866f2009-06-12 21:21:02 +00004151 return true;
4152
Douglas Gregorde090962010-02-09 00:37:32 +00004153 if (!Name.isDependent() &&
4154 !TemplateSpecializationType::anyDependentTemplateArguments(
4155 TemplateArgs.getArgumentArray(),
4156 TemplateArgs.size())) {
4157 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4158 << ClassTemplate->getDeclName();
4159 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00004160 }
4161 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004162
Douglas Gregorcc636682009-02-17 23:15:12 +00004163 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004164 ClassTemplateSpecializationDecl *PrevDecl = 0;
4165
4166 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004167 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004168 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004169 = ClassTemplate->findPartialSpecialization(Converted.data(),
4170 Converted.size(),
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004171 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004172 else
4173 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004174 = ClassTemplate->findSpecialization(Converted.data(),
4175 Converted.size(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00004176
4177 ClassTemplateSpecializationDecl *Specialization = 0;
4178
Douglas Gregor88b70942009-02-25 22:02:03 +00004179 // Check whether we can declare a class template specialization in
4180 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004181 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00004182 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00004183 TemplateNameLoc,
4184 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004185 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004186
Douglas Gregorb88e8882009-07-30 17:40:51 +00004187 // The canonical type
4188 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004189 if (PrevDecl &&
4190 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00004191 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004192 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004193 // arguments was referenced but not declared, or we're only
4194 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00004195 // declaration node as our own, updating its source location to
4196 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004197 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004198 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00004199 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00004200 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004201 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00004202 // Build the canonical type that describes the converted template
4203 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00004204 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4205 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb9c66312010-12-23 17:13:55 +00004206 Converted.data(),
4207 Converted.size());
4208
4209 if (Context.hasSameType(CanonType,
4210 ClassTemplate->getInjectedClassNameSpecialization())) {
4211 // C++ [temp.class.spec]p9b3:
4212 //
4213 // -- The argument list of the specialization shall not be identical
4214 // to the implicit argument list of the primary template.
4215 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4216 << (TUK == TUK_Definition)
4217 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4218 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
4219 ClassTemplate->getIdentifier(),
4220 TemplateNameLoc,
4221 Attr,
4222 TemplateParams,
4223 AS_none);
4224 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00004225
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004226 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004227 ClassTemplatePartialSpecializationDecl *PrevPartial
4228 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004229 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004230 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00004231 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00004232 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004233 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00004234 TemplateNameLoc,
4235 TemplateParams,
4236 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004237 Converted.data(),
4238 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00004239 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00004240 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004241 PrevPartial,
4242 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00004243 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004244 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004245 Partial->setTemplateParameterListsInfo(Context,
4246 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004247 (TemplateParameterList**) TemplateParameterLists.release());
4248 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004249
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004250 if (!PrevPartial)
4251 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004252 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00004253
Douglas Gregored9c0f92009-10-29 00:04:11 +00004254 // If we are providing an explicit specialization of a member class
4255 // template specialization, make a note of that.
4256 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4257 PrevPartial->setMemberSpecialization();
4258
Douglas Gregor031a5882009-06-13 00:26:55 +00004259 // Check that all of the template parameters of the class template
4260 // partial specialization are deducible from the template
4261 // arguments. If not, this class template partial specialization
4262 // will never be used.
4263 llvm::SmallVector<bool, 8> DeducibleParams;
4264 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00004265 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004266 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00004267 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00004268 unsigned NumNonDeducible = 0;
4269 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4270 if (!DeducibleParams[I])
4271 ++NumNonDeducible;
4272
4273 if (NumNonDeducible) {
4274 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4275 << (NumNonDeducible > 1)
4276 << SourceRange(TemplateNameLoc, RAngleLoc);
4277 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4278 if (!DeducibleParams[I]) {
4279 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4280 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00004281 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004282 diag::note_partial_spec_unused_parameter)
4283 << Param->getDeclName();
4284 else
Mike Stump1eb44332009-09-09 15:08:12 +00004285 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004286 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00004287 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00004288 }
4289 }
4290 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004291 } else {
4292 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004293 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004294 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004295 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00004296 ClassTemplate->getDeclContext(),
4297 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004298 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004299 Converted.data(),
4300 Converted.size(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004301 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004302 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004303 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004304 Specialization->setTemplateParameterListsInfo(Context,
4305 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004306 (TemplateParameterList**) TemplateParameterLists.release());
4307 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004308
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004309 if (!PrevDecl)
4310 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00004311
4312 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004313 }
4314
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004315 // C++ [temp.expl.spec]p6:
4316 // If a template, a member template or the member of a class template is
4317 // explicitly specialized then that specialization shall be declared
4318 // before the first use of that specialization that would cause an implicit
4319 // instantiation to take place, in every translation unit in which such a
4320 // use occurs; no diagnostic is required.
4321 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004322 bool Okay = false;
4323 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4324 // Is there any previous explicit specialization declaration?
4325 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4326 Okay = true;
4327 break;
4328 }
4329 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004330
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004331 if (!Okay) {
4332 SourceRange Range(TemplateNameLoc, RAngleLoc);
4333 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4334 << Context.getTypeDeclType(Specialization) << Range;
4335
4336 Diag(PrevDecl->getPointOfInstantiation(),
4337 diag::note_instantiation_required_here)
4338 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004339 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004340 return true;
4341 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004342 }
4343
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004344 // If this is not a friend, note that this is an explicit specialization.
4345 if (TUK != TUK_Friend)
4346 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004347
4348 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004349 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00004350 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004351 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004352 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004353 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00004354 Diag(Def->getLocation(), diag::note_previous_definition);
4355 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00004356 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004357 }
4358 }
4359
John McCall7f1b9872010-12-18 03:30:47 +00004360 if (Attr)
4361 ProcessDeclAttributeList(S, Specialization, Attr);
4362
Douglas Gregorfc705b82009-02-26 22:19:44 +00004363 // Build the fully-sugared type for this class template
4364 // specialization as the user wrote in the specialization
4365 // itself. This means that we'll pretty-print the type retrieved
4366 // from the specialization's declaration the way that the user
4367 // actually wrote the specialization, rather than formatting the
4368 // name based on the "canonical" representation used to store the
4369 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004370 TypeSourceInfo *WrittenTy
4371 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4372 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004373 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004374 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor7e9b57b2010-07-06 18:33:12 +00004375 if (TemplateParams)
4376 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004377 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00004378 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00004379
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004380 // C++ [temp.expl.spec]p9:
4381 // A template explicit specialization is in the scope of the
4382 // namespace in which the template was defined.
4383 //
4384 // We actually implement this paragraph where we set the semantic
4385 // context (in the creation of the ClassTemplateSpecializationDecl),
4386 // but we also maintain the lexical context where the actual
4387 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00004388 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004389
Douglas Gregorcc636682009-02-17 23:15:12 +00004390 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004391 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00004392 Specialization->startDefinition();
4393
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004394 if (TUK == TUK_Friend) {
4395 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4396 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00004397 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004398 /*FIXME:*/KWLoc);
4399 Friend->setAccess(AS_public);
4400 CurContext->addDecl(Friend);
4401 } else {
4402 // Add the specialization into its lexical context, so that it can
4403 // be seen when iterating through the list of declarations in that
4404 // context. However, specializations are not found by name lookup.
4405 CurContext->addDecl(Specialization);
4406 }
John McCalld226f652010-08-21 09:40:31 +00004407 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00004408}
Douglas Gregord57959a2009-03-27 23:10:48 +00004409
John McCalld226f652010-08-21 09:40:31 +00004410Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00004411 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004412 Declarator &D) {
Douglas Gregore542c862009-06-23 23:11:28 +00004413 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4414}
4415
John McCalld226f652010-08-21 09:40:31 +00004416Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004417 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004418 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00004419 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004420 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00004421
Douglas Gregor52591bf2009-06-24 00:54:41 +00004422 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004423 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00004424 }
Mike Stump1eb44332009-09-09 15:08:12 +00004425
Douglas Gregor52591bf2009-06-24 00:54:41 +00004426 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004427
John McCalld226f652010-08-21 09:40:31 +00004428 Decl *DP = HandleDeclarator(ParentScope, D,
4429 move(TemplateParameterLists),
4430 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004431 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00004432 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00004433 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00004434 FunctionTemplate->getTemplatedDecl());
4435 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4436 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4437 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00004438}
4439
John McCall75042392010-02-11 01:33:53 +00004440/// \brief Strips various properties off an implicit instantiation
4441/// that has just been explicitly specialized.
4442static void StripImplicitInstantiation(NamedDecl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00004443 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00004444
4445 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4446 FD->setInlineSpecified(false);
4447 }
4448}
4449
Douglas Gregor454885e2009-10-15 15:54:05 +00004450/// \brief Diagnose cases where we have an explicit template specialization
4451/// before/after an explicit template instantiation, producing diagnostics
4452/// for those cases where they are required and determining whether the
4453/// new specialization/instantiation will have any effect.
4454///
Douglas Gregor454885e2009-10-15 15:54:05 +00004455/// \param NewLoc the location of the new explicit specialization or
4456/// instantiation.
4457///
4458/// \param NewTSK the kind of the new explicit specialization or instantiation.
4459///
4460/// \param PrevDecl the previous declaration of the entity.
4461///
4462/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4463///
4464/// \param PrevPointOfInstantiation if valid, indicates where the previus
4465/// declaration was instantiated (either implicitly or explicitly).
4466///
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004467/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00004468/// specialization or instantiation has no effect and should be ignored.
4469///
4470/// \returns true if there was an error that should prevent the introduction of
4471/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004472bool
4473Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4474 TemplateSpecializationKind NewTSK,
4475 NamedDecl *PrevDecl,
4476 TemplateSpecializationKind PrevTSK,
4477 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004478 bool &HasNoEffect) {
4479 HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004480
4481 switch (NewTSK) {
4482 case TSK_Undeclared:
4483 case TSK_ImplicitInstantiation:
4484 assert(false && "Don't check implicit instantiations here");
4485 return false;
4486
4487 case TSK_ExplicitSpecialization:
4488 switch (PrevTSK) {
4489 case TSK_Undeclared:
4490 case TSK_ExplicitSpecialization:
4491 // Okay, we're just specializing something that is either already
4492 // explicitly specialized or has merely been mentioned without any
4493 // instantiation.
4494 return false;
4495
4496 case TSK_ImplicitInstantiation:
4497 if (PrevPointOfInstantiation.isInvalid()) {
4498 // The declaration itself has not actually been instantiated, so it is
4499 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004500 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004501 return false;
4502 }
4503 // Fall through
4504
4505 case TSK_ExplicitInstantiationDeclaration:
4506 case TSK_ExplicitInstantiationDefinition:
4507 assert((PrevTSK == TSK_ImplicitInstantiation ||
4508 PrevPointOfInstantiation.isValid()) &&
4509 "Explicit instantiation without point of instantiation?");
4510
4511 // C++ [temp.expl.spec]p6:
4512 // If a template, a member template or the member of a class template
4513 // is explicitly specialized then that specialization shall be declared
4514 // before the first use of that specialization that would cause an
4515 // implicit instantiation to take place, in every translation unit in
4516 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004517 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4518 // Is there any previous explicit specialization declaration?
4519 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4520 return false;
4521 }
4522
Douglas Gregor0d035142009-10-27 18:42:08 +00004523 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004524 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004525 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004526 << (PrevTSK != TSK_ImplicitInstantiation);
4527
4528 return true;
4529 }
4530 break;
4531
4532 case TSK_ExplicitInstantiationDeclaration:
4533 switch (PrevTSK) {
4534 case TSK_ExplicitInstantiationDeclaration:
4535 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004536 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004537 return false;
4538
4539 case TSK_Undeclared:
4540 case TSK_ImplicitInstantiation:
4541 // We're explicitly instantiating something that may have already been
4542 // implicitly instantiated; that's fine.
4543 return false;
4544
4545 case TSK_ExplicitSpecialization:
4546 // C++0x [temp.explicit]p4:
4547 // For a given set of template parameters, if an explicit instantiation
4548 // of a template appears after a declaration of an explicit
4549 // specialization for that template, the explicit instantiation has no
4550 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004551 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004552 return false;
4553
4554 case TSK_ExplicitInstantiationDefinition:
4555 // C++0x [temp.explicit]p10:
4556 // If an entity is the subject of both an explicit instantiation
4557 // declaration and an explicit instantiation definition in the same
4558 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004559 Diag(NewLoc,
4560 diag::err_explicit_instantiation_declaration_after_definition);
4561 Diag(PrevPointOfInstantiation,
4562 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004563 assert(PrevPointOfInstantiation.isValid() &&
4564 "Explicit instantiation without point of instantiation?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004565 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004566 return false;
4567 }
4568 break;
4569
4570 case TSK_ExplicitInstantiationDefinition:
4571 switch (PrevTSK) {
4572 case TSK_Undeclared:
4573 case TSK_ImplicitInstantiation:
4574 // We're explicitly instantiating something that may have already been
4575 // implicitly instantiated; that's fine.
4576 return false;
4577
4578 case TSK_ExplicitSpecialization:
4579 // C++ DR 259, C++0x [temp.explicit]p4:
4580 // For a given set of template parameters, if an explicit
4581 // instantiation of a template appears after a declaration of
4582 // an explicit specialization for that template, the explicit
4583 // instantiation has no effect.
4584 //
4585 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004586 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004587 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004588 if (!getLangOptions().CPlusPlus0x) {
4589 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004590 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004591 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004592 diag::note_previous_template_specialization);
4593 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004594 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004595 return false;
4596
4597 case TSK_ExplicitInstantiationDeclaration:
4598 // We're explicity instantiating a definition for something for which we
4599 // were previously asked to suppress instantiations. That's fine.
4600 return false;
4601
4602 case TSK_ExplicitInstantiationDefinition:
4603 // C++0x [temp.spec]p5:
4604 // For a given template and a given set of template-arguments,
4605 // - an explicit instantiation definition shall appear at most once
4606 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004607 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004608 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004609 Diag(PrevPointOfInstantiation,
4610 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004611 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004612 return false;
4613 }
4614 break;
4615 }
4616
4617 assert(false && "Missing specialization/instantiation case?");
4618
4619 return false;
4620}
4621
John McCallaf2094e2010-04-08 09:05:18 +00004622/// \brief Perform semantic analysis for the given dependent function
4623/// template specialization. The only possible way to get a dependent
4624/// function template specialization is with a friend declaration,
4625/// like so:
4626///
4627/// template <class T> void foo(T);
4628/// template <class T> class A {
4629/// friend void foo<>(T);
4630/// };
4631///
4632/// There really isn't any useful analysis we can do here, so we
4633/// just store the information.
4634bool
4635Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4636 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4637 LookupResult &Previous) {
4638 // Remove anything from Previous that isn't a function template in
4639 // the correct context.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004640 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallaf2094e2010-04-08 09:05:18 +00004641 LookupResult::Filter F = Previous.makeFilter();
4642 while (F.hasNext()) {
4643 NamedDecl *D = F.next()->getUnderlyingDecl();
4644 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl7a126a42010-08-31 00:36:30 +00004645 !FDLookupContext->InEnclosingNamespaceSetOf(
4646 D->getDeclContext()->getRedeclContext()))
John McCallaf2094e2010-04-08 09:05:18 +00004647 F.erase();
4648 }
4649 F.done();
4650
4651 // Should this be diagnosed here?
4652 if (Previous.empty()) return true;
4653
4654 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4655 ExplicitTemplateArgs);
4656 return false;
4657}
4658
Abramo Bagnarae03db982010-05-20 15:32:11 +00004659/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004660/// specialization.
4661///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004662/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004663/// explicit function template specialization. On successful completion,
4664/// the function declaration \p FD will become a function template
4665/// specialization.
4666///
4667/// \param FD the function declaration, which will be updated to become a
4668/// function template specialization.
4669///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004670/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4671/// if any. Note that this may be valid info even when 0 arguments are
4672/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4673/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004674///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004675/// \param PrevDecl the set of declarations that may be specialized by
4676/// this function specialization.
4677bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004678Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004679 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004680 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004681 // The set of function template specializations that could match this
4682 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004683 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004684
Sebastian Redl7a126a42010-08-31 00:36:30 +00004685 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall68263142009-11-18 22:49:29 +00004686 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4687 I != E; ++I) {
4688 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4689 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004690 // Only consider templates found within the same semantic lookup scope as
4691 // FD.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004692 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4693 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004694 continue;
4695
4696 // C++ [temp.expl.spec]p11:
4697 // A trailing template-argument can be left unspecified in the
4698 // template-id naming an explicit function template specialization
4699 // provided it can be deduced from the function argument type.
4700 // Perform template argument deduction to determine whether we may be
4701 // specializing this template.
4702 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004703 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004704 FunctionDecl *Specialization = 0;
4705 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004706 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004707 FD->getType(),
4708 Specialization,
4709 Info)) {
4710 // FIXME: Template argument deduction failed; record why it failed, so
4711 // that we can provide nifty diagnostics.
4712 (void)TDK;
4713 continue;
4714 }
4715
4716 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004717 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004718 }
4719 }
4720
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004721 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004722 UnresolvedSetIterator Result
4723 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4724 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004725 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004726 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004727 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004728 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004729 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004730 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004731 return true;
John McCallc373d482010-01-27 01:50:18 +00004732
4733 // Ignore access information; it doesn't figure into redeclaration checking.
4734 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004735 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004736
4737 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004738 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004739
4740 // If this is a friend declaration, then we're not really declaring
4741 // an explicit specialization.
4742 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004743
Douglas Gregord5cb8762009-10-07 00:13:32 +00004744 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004745 if (!isFriend &&
4746 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004747 Specialization->getPrimaryTemplate(),
4748 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004749 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004750 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004751
4752 // C++ [temp.expl.spec]p6:
4753 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004754 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004755 // before the first use of that specialization that would cause an implicit
4756 // instantiation to take place, in every translation unit in which such a
4757 // use occurs; no diagnostic is required.
4758 FunctionTemplateSpecializationInfo *SpecInfo
4759 = Specialization->getTemplateSpecializationInfo();
4760 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004761
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004762 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00004763 if (!isFriend &&
4764 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004765 TSK_ExplicitSpecialization,
4766 Specialization,
4767 SpecInfo->getTemplateSpecializationKind(),
4768 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004769 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004770 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004771
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004772 // Mark the prior declaration as an explicit specialization, so that later
4773 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004774 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00004775 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004776 MarkUnusedFileScopedDecl(Specialization);
4777 }
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004778
4779 // Turn the given function declaration into a function template
4780 // specialization, with the template arguments from the previous
4781 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004782 // Take copies of (semantic and syntactic) template argument lists.
4783 const TemplateArgumentList* TemplArgs = new (Context)
4784 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4785 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4786 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004787 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004788 TemplArgs, /*InsertPos=*/0,
4789 SpecInfo->getTemplateSpecializationKind(),
4790 TemplArgsAsWritten);
4791
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004792 // The "previous declaration" for this function template specialization is
4793 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004794 Previous.clear();
4795 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004796 return false;
4797}
4798
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004799/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004800/// specialization.
4801///
4802/// This routine performs all of the semantic analysis required for an
4803/// explicit member function specialization. On successful completion,
4804/// the function declaration \p FD will become a member function
4805/// specialization.
4806///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004807/// \param Member the member declaration, which will be updated to become a
4808/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004809///
John McCall68263142009-11-18 22:49:29 +00004810/// \param Previous the set of declarations, one of which may be specialized
4811/// by this function specialization; the set will be modified to contain the
4812/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004813bool
John McCall68263142009-11-18 22:49:29 +00004814Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004815 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004816
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004817 // Try to find the member we are instantiating.
4818 NamedDecl *Instantiation = 0;
4819 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004820 MemberSpecializationInfo *MSInfo = 0;
4821
John McCall68263142009-11-18 22:49:29 +00004822 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004823 // Nowhere to look anyway.
4824 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004825 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4826 I != E; ++I) {
4827 NamedDecl *D = (*I)->getUnderlyingDecl();
4828 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004829 if (Context.hasSameType(Function->getType(), Method->getType())) {
4830 Instantiation = Method;
4831 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004832 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004833 break;
4834 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004835 }
4836 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004837 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004838 VarDecl *PrevVar;
4839 if (Previous.isSingleResult() &&
4840 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004841 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004842 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004843 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004844 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004845 }
4846 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004847 CXXRecordDecl *PrevRecord;
4848 if (Previous.isSingleResult() &&
4849 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4850 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004851 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004852 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004853 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004854 }
4855
4856 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004857 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004858 // specializations are always out-of-line, the caller will complain about
4859 // this mismatch later.
4860 return false;
4861 }
John McCall77e8b112010-04-13 20:37:33 +00004862
4863 // If this is a friend, just bail out here before we start turning
4864 // things into explicit specializations.
4865 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4866 // Preserve instantiation information.
4867 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4868 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4869 cast<CXXMethodDecl>(InstantiatedFrom),
4870 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4871 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4872 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4873 cast<CXXRecordDecl>(InstantiatedFrom),
4874 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4875 }
4876
4877 Previous.clear();
4878 Previous.addDecl(Instantiation);
4879 return false;
4880 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004881
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004882 // Make sure that this is a specialization of a member.
4883 if (!InstantiatedFrom) {
4884 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4885 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004886 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4887 return true;
4888 }
4889
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004890 // C++ [temp.expl.spec]p6:
4891 // If a template, a member template or the member of a class template is
4892 // explicitly specialized then that spe- cialization shall be declared
4893 // before the first use of that specialization that would cause an implicit
4894 // instantiation to take place, in every translation unit in which such a
4895 // use occurs; no diagnostic is required.
4896 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004897
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004898 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00004899 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4900 TSK_ExplicitSpecialization,
4901 Instantiation,
4902 MSInfo->getTemplateSpecializationKind(),
4903 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004904 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004905 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004906
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004907 // Check the scope of this explicit specialization.
4908 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004909 InstantiatedFrom,
4910 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004911 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004912 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004913
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004914 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004915 // the original declaration to note that it is an explicit specialization
4916 // (if it was previously an implicit instantiation). This latter step
4917 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004918 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004919 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4920 if (InstantiationFunction->getTemplateSpecializationKind() ==
4921 TSK_ImplicitInstantiation) {
4922 InstantiationFunction->setTemplateSpecializationKind(
4923 TSK_ExplicitSpecialization);
4924 InstantiationFunction->setLocation(Member->getLocation());
4925 }
4926
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004927 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4928 cast<CXXMethodDecl>(InstantiatedFrom),
4929 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004930 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004931 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004932 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4933 if (InstantiationVar->getTemplateSpecializationKind() ==
4934 TSK_ImplicitInstantiation) {
4935 InstantiationVar->setTemplateSpecializationKind(
4936 TSK_ExplicitSpecialization);
4937 InstantiationVar->setLocation(Member->getLocation());
4938 }
4939
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004940 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4941 cast<VarDecl>(InstantiatedFrom),
4942 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004943 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004944 } else {
4945 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004946 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4947 if (InstantiationClass->getTemplateSpecializationKind() ==
4948 TSK_ImplicitInstantiation) {
4949 InstantiationClass->setTemplateSpecializationKind(
4950 TSK_ExplicitSpecialization);
4951 InstantiationClass->setLocation(Member->getLocation());
4952 }
4953
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004954 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004955 cast<CXXRecordDecl>(InstantiatedFrom),
4956 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004957 }
4958
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004959 // Save the caller the trouble of having to figure out which declaration
4960 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004961 Previous.clear();
4962 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004963 return false;
4964}
4965
Douglas Gregor558c0322009-10-14 23:41:34 +00004966/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00004967///
4968/// \returns true if a serious error occurs, false otherwise.
4969static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00004970 SourceLocation InstLoc,
4971 bool WasQualifiedName) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00004972 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
4973 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregor558c0322009-10-14 23:41:34 +00004974
Douglas Gregor669eed82010-07-13 00:10:04 +00004975 if (CurContext->isRecord()) {
4976 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4977 << D;
4978 return true;
4979 }
4980
Douglas Gregor558c0322009-10-14 23:41:34 +00004981 // C++0x [temp.explicit]p2:
4982 // An explicit instantiation shall appear in an enclosing namespace of its
4983 // template.
4984 //
4985 // This is DR275, which we do not retroactively apply to C++98/03.
4986 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004987 !CurContext->Encloses(OrigContext)) {
4988 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00004989 S.Diag(InstLoc,
4990 S.getLangOptions().CPlusPlus0x?
4991 diag::err_explicit_instantiation_out_of_scope
4992 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004993 << D << NS;
4994 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00004995 S.Diag(InstLoc,
4996 S.getLangOptions().CPlusPlus0x?
4997 diag::err_explicit_instantiation_must_be_global
4998 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004999 << D;
5000 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00005001 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00005002 }
Sebastian Redl7a126a42010-08-31 00:36:30 +00005003
Douglas Gregor558c0322009-10-14 23:41:34 +00005004 // C++0x [temp.explicit]p2:
5005 // If the name declared in the explicit instantiation is an unqualified
5006 // name, the explicit instantiation shall appear in the namespace where
5007 // its template is declared or, if that namespace is inline (7.3.1), any
5008 // namespace from its enclosing namespace set.
5009 if (WasQualifiedName)
Douglas Gregor669eed82010-07-13 00:10:04 +00005010 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005011
5012 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor669eed82010-07-13 00:10:04 +00005013 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005014
Douglas Gregor2166beb2010-05-11 17:39:34 +00005015 S.Diag(InstLoc,
5016 S.getLangOptions().CPlusPlus0x?
5017 diag::err_explicit_instantiation_unqualified_wrong_namespace
5018 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl7a126a42010-08-31 00:36:30 +00005019 << D << OrigContext;
Douglas Gregor558c0322009-10-14 23:41:34 +00005020 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00005021 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00005022}
5023
5024/// \brief Determine whether the given scope specifier has a template-id in it.
5025static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
5026 if (!SS.isSet())
5027 return false;
5028
5029 // C++0x [temp.explicit]p2:
5030 // If the explicit instantiation is for a member function, a member class
5031 // or a static data member of a class template specialization, the name of
5032 // the class template specialization in the qualified-id for the member
5033 // name shall be a simple-template-id.
5034 //
5035 // C++98 has the same restriction, just worded differently.
5036 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
5037 NNS; NNS = NNS->getPrefix())
5038 if (Type *T = NNS->getAsType())
5039 if (isa<TemplateSpecializationType>(T))
5040 return true;
5041
5042 return false;
5043}
5044
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005045// Explicit instantiation of a class template specialization
John McCallf312b1e2010-08-26 23:41:50 +00005046DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005047Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005048 SourceLocation ExternLoc,
5049 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005050 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005051 SourceLocation KWLoc,
5052 const CXXScopeSpec &SS,
5053 TemplateTy TemplateD,
5054 SourceLocation TemplateNameLoc,
5055 SourceLocation LAngleLoc,
5056 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005057 SourceLocation RAngleLoc,
5058 AttributeList *Attr) {
5059 // Find the class template we're specializing
5060 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00005061 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005062 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
5063
5064 // Check that the specialization uses the same tag kind as the
5065 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005066 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5067 assert(Kind != TTK_Enum &&
5068 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005069 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00005070 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005071 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005072 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005073 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00005074 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005075 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00005076 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005077 diag::note_previous_use);
5078 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5079 }
5080
Douglas Gregor558c0322009-10-14 23:41:34 +00005081 // C++0x [temp.explicit]p2:
5082 // There are two forms of explicit instantiation: an explicit instantiation
5083 // definition and an explicit instantiation declaration. An explicit
5084 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00005085 TemplateSpecializationKind TSK
5086 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5087 : TSK_ExplicitInstantiationDeclaration;
5088
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005089 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00005090 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00005091 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005092
5093 // Check that the template argument list is well-formed for this
5094 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00005095 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00005096 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5097 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005098 return true;
5099
Douglas Gregor910f8002010-11-07 23:05:16 +00005100 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005101 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00005102
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005103 // Find the class template specialization declaration that
5104 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005105 void *InsertPos = 0;
5106 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00005107 = ClassTemplate->findSpecialization(Converted.data(),
5108 Converted.size(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005109
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005110 TemplateSpecializationKind PrevDecl_TSK
5111 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5112
Douglas Gregord5cb8762009-10-07 00:13:32 +00005113 // C++0x [temp.explicit]p2:
5114 // [...] An explicit instantiation shall appear in an enclosing
5115 // namespace of its template. [...]
5116 //
5117 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00005118 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5119 SS.isSet()))
5120 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00005121
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005122 ClassTemplateSpecializationDecl *Specialization = 0;
5123
Douglas Gregord78f5982009-11-25 06:01:46 +00005124 bool ReusedDecl = false;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005125 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005126 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00005127 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005128 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005129 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005130 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00005131 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005132
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005133 // Even though HasNoEffect == true means that this explicit instantiation
5134 // has no effect on semantics, we go on to put its syntax in the AST.
5135
5136 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5137 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00005138 // Since the only prior class template specialization with these
5139 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005140 // declaration node as our own, updating the source location
5141 // for the template name to reflect our new declaration.
5142 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00005143 Specialization = PrevDecl;
5144 Specialization->setLocation(TemplateNameLoc);
5145 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00005146 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00005147 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005148 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005149
Douglas Gregor52604ab2009-09-11 21:19:12 +00005150 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005151 // Create a new class template specialization declaration node for
5152 // this explicit specialization.
5153 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00005154 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005155 ClassTemplate->getDeclContext(),
5156 TemplateNameLoc,
5157 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005158 Converted.data(),
5159 Converted.size(),
5160 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00005161 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005162
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005163 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005164 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005165 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005166 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005167 }
5168
5169 // Build the fully-sugared type for this explicit instantiation as
5170 // the user wrote in the explicit instantiation itself. This means
5171 // that we'll pretty-print the type retrieved from the
5172 // specialization's declaration the way that the user actually wrote
5173 // the explicit instantiation, rather than formatting the name based
5174 // on the "canonical" representation used to store the template
5175 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00005176 TypeSourceInfo *WrittenTy
5177 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5178 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005179 Context.getTypeDeclType(Specialization));
5180 Specialization->setTypeAsWritten(WrittenTy);
5181 TemplateArgsIn.release();
5182
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005183 // Set source locations for keywords.
5184 Specialization->setExternLoc(ExternLoc);
5185 Specialization->setTemplateKeywordLoc(TemplateLoc);
5186
5187 // Add the explicit instantiation into its lexical context. However,
5188 // since explicit instantiations are never found by name lookup, we
5189 // just put it into the declaration context directly.
5190 Specialization->setLexicalDeclContext(CurContext);
5191 CurContext->addDecl(Specialization);
5192
5193 // Syntax is now OK, so return if it has no other effect on semantics.
5194 if (HasNoEffect) {
5195 // Set the template specialization kind.
5196 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005197 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00005198 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005199
5200 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005201 // A definition of a class template or class member template
5202 // shall be in scope at the point of the explicit instantiation of
5203 // the class template or class member template.
5204 //
5205 // This check comes when we actually try to perform the
5206 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005207 ClassTemplateSpecializationDecl *Def
5208 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005209 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005210 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005211 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005212 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005213 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005214 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5215 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005216
Douglas Gregor0d035142009-10-27 18:42:08 +00005217 // Instantiate the members of this class template specialization.
5218 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005219 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005220 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00005221 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5222
5223 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5224 // TSK_ExplicitInstantiationDefinition
5225 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5226 TSK == TSK_ExplicitInstantiationDefinition)
5227 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005228
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005229 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005230 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005231
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005232 // Set the template specialization kind.
5233 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005234 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005235}
5236
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005237// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00005238DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005239Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005240 SourceLocation ExternLoc,
5241 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005242 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005243 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005244 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005245 IdentifierInfo *Name,
5246 SourceLocation NameLoc,
5247 AttributeList *Attr) {
5248
Douglas Gregor402abb52009-05-28 23:31:59 +00005249 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00005250 bool IsDependent = false;
John McCallf312b1e2010-08-26 23:41:50 +00005251 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCalld226f652010-08-21 09:40:31 +00005252 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5253 MultiTemplateParamsArg(*this, 0, 0),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00005254 Owned, IsDependent, false, false,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005255 TypeResult());
John McCallc4e70192009-09-11 04:59:25 +00005256 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5257
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005258 if (!TagD)
5259 return true;
5260
John McCalld226f652010-08-21 09:40:31 +00005261 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005262 if (Tag->isEnum()) {
5263 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5264 << Context.getTypeDeclType(Tag);
5265 return true;
5266 }
5267
Douglas Gregord0c87372009-05-27 17:30:49 +00005268 if (Tag->isInvalidDecl())
5269 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00005270
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005271 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5272 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5273 if (!Pattern) {
5274 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5275 << Context.getTypeDeclType(Record);
5276 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5277 return true;
5278 }
5279
Douglas Gregor558c0322009-10-14 23:41:34 +00005280 // C++0x [temp.explicit]p2:
5281 // If the explicit instantiation is for a class or member class, the
5282 // elaborated-type-specifier in the declaration shall include a
5283 // simple-template-id.
5284 //
5285 // C++98 has the same restriction, just worded differently.
5286 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00005287 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005288 << Record << SS.getRange();
5289
5290 // C++0x [temp.explicit]p2:
5291 // There are two forms of explicit instantiation: an explicit instantiation
5292 // definition and an explicit instantiation declaration. An explicit
5293 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00005294 TemplateSpecializationKind TSK
5295 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5296 : TSK_ExplicitInstantiationDeclaration;
5297
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005298 // C++0x [temp.explicit]p2:
5299 // [...] An explicit instantiation shall appear in an enclosing
5300 // namespace of its template. [...]
5301 //
5302 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00005303 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00005304
5305 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00005306 CXXRecordDecl *PrevDecl
5307 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00005308 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00005309 PrevDecl = Record;
5310 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00005311 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005312 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00005313 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00005314 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00005315 PrevDecl,
5316 MSInfo->getTemplateSpecializationKind(),
5317 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005318 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005319 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005320 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00005321 return TagD;
5322 }
5323
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005324 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00005325 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005326 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005327 // C++ [temp.explicit]p3:
5328 // A definition of a member class of a class template shall be in scope
5329 // at the point of an explicit instantiation of the member class.
5330 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00005331 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005332 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00005333 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5334 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005335 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5336 << Pattern;
5337 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00005338 } else {
5339 if (InstantiateClass(NameLoc, Record, Def,
5340 getTemplateInstantiationArgs(Record),
5341 TSK))
5342 return true;
5343
Douglas Gregor952b0172010-02-11 01:04:33 +00005344 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00005345 if (!RecordDef)
5346 return true;
5347 }
5348 }
5349
5350 // Instantiate all of the members of the class.
5351 InstantiateClassMembers(NameLoc, RecordDef,
5352 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005353
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005354 if (TSK == TSK_ExplicitInstantiationDefinition)
5355 MarkVTableUsed(NameLoc, RecordDef, true);
5356
Mike Stump390b4cc2009-05-16 07:39:55 +00005357 // FIXME: We don't have any representation for explicit instantiations of
5358 // member classes. Such a representation is not needed for compilation, but it
5359 // should be available for clients that want to see all of the declarations in
5360 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005361 return TagD;
5362}
5363
John McCallf312b1e2010-08-26 23:41:50 +00005364DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5365 SourceLocation ExternLoc,
5366 SourceLocation TemplateLoc,
5367 Declarator &D) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005368 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00005369 // TODO: check if/when DNInfo should replace Name.
5370 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5371 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005372 if (!Name) {
5373 if (!D.isInvalidType())
5374 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5375 diag::err_explicit_instantiation_requires_name)
5376 << D.getDeclSpec().getSourceRange()
5377 << D.getSourceRange();
5378
5379 return true;
5380 }
5381
5382 // The scope passed in may not be a decl scope. Zip up the scope tree until
5383 // we find one that is.
5384 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5385 (S->getFlags() & Scope::TemplateParamScope) != 0)
5386 S = S->getParent();
5387
5388 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00005389 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5390 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005391 if (R.isNull())
5392 return true;
5393
5394 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5395 // Cannot explicitly instantiate a typedef.
5396 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5397 << Name;
5398 return true;
5399 }
5400
Douglas Gregor663b5a02009-10-14 20:14:33 +00005401 // C++0x [temp.explicit]p1:
5402 // [...] An explicit instantiation of a function template shall not use the
5403 // inline or constexpr specifiers.
5404 // Presumably, this also applies to member functions of class templates as
5405 // well.
5406 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5407 Diag(D.getDeclSpec().getInlineSpecLoc(),
5408 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00005409 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00005410
5411 // FIXME: check for constexpr specifier.
5412
Douglas Gregor558c0322009-10-14 23:41:34 +00005413 // C++0x [temp.explicit]p2:
5414 // There are two forms of explicit instantiation: an explicit instantiation
5415 // definition and an explicit instantiation declaration. An explicit
5416 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00005417 TemplateSpecializationKind TSK
5418 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5419 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00005420
Abramo Bagnara25777432010-08-11 22:01:17 +00005421 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005422 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005423
5424 if (!R->isFunctionType()) {
5425 // C++ [temp.explicit]p1:
5426 // A [...] static data member of a class template can be explicitly
5427 // instantiated from the member definition associated with its class
5428 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00005429 if (Previous.isAmbiguous())
5430 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005431
John McCall1bcee0a2009-12-02 08:25:40 +00005432 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005433 if (!Prev || !Prev->isStaticDataMember()) {
5434 // We expect to see a data data member here.
5435 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5436 << Name;
5437 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5438 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00005439 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005440 return true;
5441 }
5442
5443 if (!Prev->getInstantiatedFromStaticDataMember()) {
5444 // FIXME: Check for explicit specialization?
5445 Diag(D.getIdentifierLoc(),
5446 diag::err_explicit_instantiation_data_member_not_instantiated)
5447 << Prev;
5448 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5449 // FIXME: Can we provide a note showing where this was declared?
5450 return true;
5451 }
5452
Douglas Gregor558c0322009-10-14 23:41:34 +00005453 // C++0x [temp.explicit]p2:
5454 // If the explicit instantiation is for a member function, a member class
5455 // or a static data member of a class template specialization, the name of
5456 // the class template specialization in the qualified-id for the member
5457 // name shall be a simple-template-id.
5458 //
5459 // C++98 has the same restriction, just worded differently.
5460 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5461 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005462 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005463 << Prev << D.getCXXScopeSpec().getRange();
5464
5465 // Check the scope of this explicit instantiation.
5466 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5467
Douglas Gregor454885e2009-10-15 15:54:05 +00005468 // Verify that it is okay to explicitly instantiate here.
5469 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5470 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005471 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005472 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005473 MSInfo->getTemplateSpecializationKind(),
5474 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005475 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005476 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005477 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005478 return (Decl*) 0;
Douglas Gregor454885e2009-10-15 15:54:05 +00005479
Douglas Gregord5a423b2009-09-25 18:43:00 +00005480 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005481 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005482 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005483 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005484
5485 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00005486 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005487 }
5488
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005489 // If the declarator is a template-id, translate the parser's template
5490 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005491 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005492 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005493 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5494 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005495 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5496 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005497 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5498 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005499 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005500 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005501 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005502 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005503 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005504
Douglas Gregord5a423b2009-09-25 18:43:00 +00005505 // C++ [temp.explicit]p1:
5506 // A [...] function [...] can be explicitly instantiated from its template.
5507 // A member function [...] of a class template can be explicitly
5508 // instantiated from the member definition associated with its class
5509 // template.
John McCallc373d482010-01-27 01:50:18 +00005510 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005511 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5512 P != PEnd; ++P) {
5513 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005514 if (!HasExplicitTemplateArgs) {
5515 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5516 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5517 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005518
John McCallc373d482010-01-27 01:50:18 +00005519 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005520 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5521 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005522 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005523 }
5524 }
5525
5526 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5527 if (!FunTmpl)
5528 continue;
5529
John McCall5769d612010-02-08 23:07:23 +00005530 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005531 FunctionDecl *Specialization = 0;
5532 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005533 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005534 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005535 R, Specialization, Info)) {
5536 // FIXME: Keep track of almost-matches?
5537 (void)TDK;
5538 continue;
5539 }
5540
John McCallc373d482010-01-27 01:50:18 +00005541 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005542 }
5543
5544 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005545 UnresolvedSetIterator Result
5546 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005547 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005548 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5549 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5550 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005551
John McCallc373d482010-01-27 01:50:18 +00005552 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005553 return true;
John McCallc373d482010-01-27 01:50:18 +00005554
5555 // Ignore access control bits, we don't need them for redeclaration checking.
5556 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005557
Douglas Gregor0a897e32009-10-15 17:21:20 +00005558 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005559 Diag(D.getIdentifierLoc(),
5560 diag::err_explicit_instantiation_member_function_not_instantiated)
5561 << Specialization
5562 << (Specialization->getTemplateSpecializationKind() ==
5563 TSK_ExplicitSpecialization);
5564 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5565 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005566 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005567
Douglas Gregor0a897e32009-10-15 17:21:20 +00005568 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005569 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5570 PrevDecl = Specialization;
5571
Douglas Gregor0a897e32009-10-15 17:21:20 +00005572 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005573 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005574 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005575 PrevDecl,
5576 PrevDecl->getTemplateSpecializationKind(),
5577 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005578 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00005579 return true;
5580
5581 // FIXME: We may still want to build some representation of this
5582 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005583 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005584 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005585 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005586
5587 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005588
5589 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005590 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005591
Douglas Gregor558c0322009-10-14 23:41:34 +00005592 // C++0x [temp.explicit]p2:
5593 // If the explicit instantiation is for a member function, a member class
5594 // or a static data member of a class template specialization, the name of
5595 // the class template specialization in the qualified-id for the member
5596 // name shall be a simple-template-id.
5597 //
5598 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005599 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005600 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005601 D.getCXXScopeSpec().isSet() &&
5602 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5603 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005604 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005605 << Specialization << D.getCXXScopeSpec().getRange();
5606
5607 CheckExplicitInstantiationScope(*this,
5608 FunTmpl? (NamedDecl *)FunTmpl
5609 : Specialization->getInstantiatedFromMemberFunction(),
5610 D.getIdentifierLoc(),
5611 D.getCXXScopeSpec().isSet());
5612
Douglas Gregord5a423b2009-09-25 18:43:00 +00005613 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00005614 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005615}
5616
John McCallf312b1e2010-08-26 23:41:50 +00005617TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005618Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5619 const CXXScopeSpec &SS, IdentifierInfo *Name,
5620 SourceLocation TagLoc, SourceLocation NameLoc) {
5621 // This has to hold, because SS is expected to be defined.
5622 assert(Name && "Expected a name in a dependent tag");
5623
5624 NestedNameSpecifier *NNS
5625 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5626 if (!NNS)
5627 return true;
5628
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005629 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005630
Douglas Gregor48c89f42010-04-24 16:38:41 +00005631 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5632 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005633 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005634 return true;
5635 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005636
5637 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallb3d87482010-08-24 05:47:05 +00005638 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCallc4e70192009-09-11 04:59:25 +00005639}
5640
John McCallf312b1e2010-08-26 23:41:50 +00005641TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005642Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5643 const CXXScopeSpec &SS, const IdentifierInfo &II,
5644 SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005645 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005646 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5647 if (!NNS)
5648 return true;
5649
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005650 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5651 !getLangOptions().CPlusPlus0x)
5652 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5653 << FixItHint::CreateRemoval(TypenameLoc);
5654
Douglas Gregor107de902010-04-24 15:35:55 +00005655 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005656 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005657 if (T.isNull())
5658 return true;
John McCall63b43852010-04-29 23:50:39 +00005659
5660 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5661 if (isa<DependentNameType>(T)) {
5662 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005663 TL.setKeywordLoc(TypenameLoc);
5664 TL.setQualifierRange(SS.getRange());
5665 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005666 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005667 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005668 TL.setKeywordLoc(TypenameLoc);
5669 TL.setQualifierRange(SS.getRange());
5670 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005671 }
5672
John McCallb3d87482010-08-24 05:47:05 +00005673 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00005674}
5675
John McCallf312b1e2010-08-26 23:41:50 +00005676TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005677Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5678 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallb3d87482010-08-24 05:47:05 +00005679 ParsedType Ty) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005680 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5681 !getLangOptions().CPlusPlus0x)
5682 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5683 << FixItHint::CreateRemoval(TypenameLoc);
5684
John McCall4e449832010-05-28 23:32:21 +00005685 TypeSourceInfo *InnerTSI = 0;
5686 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCall4e449832010-05-28 23:32:21 +00005687
5688 assert(isa<TemplateSpecializationType>(T) &&
5689 "Expected a template specialization type");
Douglas Gregor17343172009-04-01 00:28:59 +00005690
Douglas Gregor6946baf2009-09-02 13:05:45 +00005691 if (computeDeclContext(SS, false)) {
5692 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005693 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005694 // track of the nested-name-specifier.
John McCall4e449832010-05-28 23:32:21 +00005695
5696 // Push the inner type, preserving its source locations if possible.
5697 TypeLocBuilder Builder;
5698 if (InnerTSI)
5699 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5700 else
5701 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5702
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005703 /* Note: NNS already embedded in template specialization type T. */
5704 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCall4e449832010-05-28 23:32:21 +00005705 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5706 TL.setKeywordLoc(TypenameLoc);
5707 TL.setQualifierRange(SS.getRange());
5708
5709 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallb3d87482010-08-24 05:47:05 +00005710 return CreateParsedType(T, TSI);
Douglas Gregor6946baf2009-09-02 13:05:45 +00005711 }
Mike Stump1eb44332009-09-09 15:08:12 +00005712
John McCall33500952010-06-11 00:33:02 +00005713 // TODO: it's really silly that we make a template specialization
5714 // type earlier only to drop it again here.
5715 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5716 DependentTemplateName *DTN =
5717 TST->getTemplateName().getAsDependentTemplateName();
5718 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005719 assert(DTN->getQualifier()
5720 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5721 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5722 DTN->getQualifier(),
John McCall33500952010-06-11 00:33:02 +00005723 DTN->getIdentifier(),
5724 TST->getNumArgs(),
5725 TST->getArgs());
John McCall63b43852010-04-29 23:50:39 +00005726 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCall33500952010-06-11 00:33:02 +00005727 DependentTemplateSpecializationTypeLoc TL =
5728 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5729 if (InnerTSI) {
5730 TemplateSpecializationTypeLoc TSTL =
5731 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5732 TL.setLAngleLoc(TSTL.getLAngleLoc());
5733 TL.setRAngleLoc(TSTL.getRAngleLoc());
5734 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5735 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5736 } else {
5737 TL.initializeLocal(SourceLocation());
5738 }
John McCall4e449832010-05-28 23:32:21 +00005739 TL.setKeywordLoc(TypenameLoc);
5740 TL.setQualifierRange(SS.getRange());
John McCallb3d87482010-08-24 05:47:05 +00005741 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00005742}
5743
Douglas Gregord57959a2009-03-27 23:10:48 +00005744/// \brief Build the type that describes a C++ typename specifier,
5745/// e.g., "typename T::type".
5746QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005747Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5748 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005749 SourceLocation KeywordLoc, SourceRange NNSRange,
5750 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005751 CXXScopeSpec SS;
5752 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005753 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005754
John McCall77bb1aa2010-05-01 00:40:08 +00005755 DeclContext *Ctx = computeDeclContext(SS);
5756 if (!Ctx) {
5757 // If the nested-name-specifier is dependent and couldn't be
5758 // resolved to a type, build a typename type.
5759 assert(NNS->isDependent());
5760 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005761 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005762
John McCall77bb1aa2010-05-01 00:40:08 +00005763 // If the nested-name-specifier refers to the current instantiation,
5764 // the "typename" keyword itself is superfluous. In C++03, the
5765 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5766 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00005767 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005768
John McCall77bb1aa2010-05-01 00:40:08 +00005769 if (RequireCompleteDeclContext(SS, Ctx))
5770 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005771
5772 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005773 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005774 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005775 unsigned DiagID = 0;
5776 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005777 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005778 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005779 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005780 break;
Douglas Gregord9545042010-12-09 00:06:27 +00005781
5782 case LookupResult::FoundUnresolvedValue: {
5783 // We found a using declaration that is a value. Most likely, the using
5784 // declaration itself is meant to have the 'typename' keyword.
5785 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5786 IILoc);
5787 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
5788 << Name << Ctx << FullRange;
5789 if (UnresolvedUsingValueDecl *Using
5790 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
5791 SourceLocation Loc = Using->getTargetNestedNameRange().getBegin();
5792 Diag(Loc, diag::note_using_value_decl_missing_typename)
5793 << FixItHint::CreateInsertion(Loc, "typename ");
5794 }
5795 }
5796 // Fall through to create a dependent typename type, from which we can recover
5797 // better.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005798
5799 case LookupResult::NotFoundInCurrentInstantiation:
5800 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005801 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005802
5803 case LookupResult::Found:
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005804 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005805 // We found a type. Build an ElaboratedType, since the
5806 // typename-specifier was just sugar.
5807 return Context.getElaboratedType(ETK_Typename, NNS,
5808 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005809 }
5810
5811 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005812 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005813 break;
5814
Douglas Gregord9545042010-12-09 00:06:27 +00005815
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005816 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005817 return QualType();
5818
Douglas Gregord57959a2009-03-27 23:10:48 +00005819 case LookupResult::FoundOverloaded:
5820 DiagID = diag::err_typename_nested_not_type;
5821 Referenced = *Result.begin();
5822 break;
5823
John McCall6e247262009-10-10 05:48:19 +00005824 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005825 return QualType();
5826 }
5827
5828 // If we get here, it's because name lookup did not find a
5829 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005830 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5831 IILoc);
5832 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005833 if (Referenced)
5834 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5835 << Name;
5836 return QualType();
5837}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005838
5839namespace {
5840 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005841 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005842 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005843 SourceLocation Loc;
5844 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005845
Douglas Gregor4a959d82009-08-06 16:20:37 +00005846 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005847 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5848
Mike Stump1eb44332009-09-09 15:08:12 +00005849 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005850 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005851 DeclarationName Entity)
5852 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005853 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005854
5855 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005856 /// transformed.
5857 ///
5858 /// For the purposes of type reconstruction, a type has already been
5859 /// transformed if it is NULL or if it is not dependent.
5860 bool AlreadyTransformed(QualType T) {
5861 return T.isNull() || !T->isDependentType();
5862 }
Mike Stump1eb44332009-09-09 15:08:12 +00005863
5864 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005865 /// rebuilt.
5866 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005867
Douglas Gregor4a959d82009-08-06 16:20:37 +00005868 /// \brief Returns the name of the entity whose type is being rebuilt.
5869 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005870
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005871 /// \brief Sets the "base" location and entity when that
5872 /// information is known based on another transformation.
5873 void setBase(SourceLocation Loc, DeclarationName Entity) {
5874 this->Loc = Loc;
5875 this->Entity = Entity;
5876 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00005877 };
5878}
5879
Douglas Gregor4a959d82009-08-06 16:20:37 +00005880/// \brief Rebuilds a type within the context of the current instantiation.
5881///
Mike Stump1eb44332009-09-09 15:08:12 +00005882/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005883/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005884/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005885/// partial specialization thereof). This routine will rebuild that type now
5886/// that we have entered the declarator's scope, which may produce different
5887/// canonical types, e.g.,
5888///
5889/// \code
5890/// template<typename T>
5891/// struct X {
5892/// typedef T* pointer;
5893/// pointer data();
5894/// };
5895///
5896/// template<typename T>
5897/// typename X<T>::pointer X<T>::data() { ... }
5898/// \endcode
5899///
Douglas Gregor4714c122010-03-31 17:34:00 +00005900/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005901/// since we do not know that we can look into X<T> when we parsed the type.
5902/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005903/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00005904/// as the canonical type of T*, allowing the return types of the out-of-line
5905/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00005906TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5907 SourceLocation Loc,
5908 DeclarationName Name) {
5909 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00005910 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005911
Douglas Gregor4a959d82009-08-06 16:20:37 +00005912 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5913 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005914}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005915
John McCall60d7b3a2010-08-24 06:29:42 +00005916ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00005917 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5918 DeclarationName());
5919 return Rebuilder.TransformExpr(E);
5920}
5921
John McCall63b43852010-04-29 23:50:39 +00005922bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5923 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00005924
5925 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5926 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5927 DeclarationName());
5928 NestedNameSpecifier *Rebuilt =
5929 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005930 if (!Rebuilt) return true;
5931
5932 SS.setScopeRep(Rebuilt);
5933 return false;
John McCall31f17ec2010-04-27 00:57:59 +00005934}
5935
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005936/// \brief Produces a formatted string that describes the binding of
5937/// template parameters to template arguments.
5938std::string
5939Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5940 const TemplateArgumentList &Args) {
Douglas Gregor910f8002010-11-07 23:05:16 +00005941 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005942}
5943
5944std::string
5945Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5946 const TemplateArgument *Args,
5947 unsigned NumArgs) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00005948 llvm::SmallString<128> Str;
5949 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005950
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005951 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00005952 return std::string();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005953
5954 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005955 if (I >= NumArgs)
5956 break;
5957
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005958 if (I == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00005959 Out << "[with ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005960 else
Douglas Gregor87dd6972010-12-20 16:52:59 +00005961 Out << ", ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005962
5963 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00005964 Out << Id->getName();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005965 } else {
Douglas Gregor87dd6972010-12-20 16:52:59 +00005966 Out << '$' << I;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005967 }
5968
Douglas Gregor87dd6972010-12-20 16:52:59 +00005969 Out << " = ";
5970 Args[I].print(Context.PrintingPolicy, Out);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005971 }
Douglas Gregor87dd6972010-12-20 16:52:59 +00005972
5973 Out << ']';
5974 return Out.str();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005975}
Douglas Gregord0937222010-12-13 22:49:22 +00005976