blob: 0a319b17f60e7538d9b4f1d330444631eef9ed6c [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 Gregorba68eca2011-01-05 17:40:24 +0000440ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
441 SourceLocation EllipsisLoc) const {
442 assert(Kind == Template &&
443 "Only template template arguments can be pack expansions here");
444 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
445 "Template template argument pack expansion without packs");
446 ParsedTemplateArgument Result(*this);
447 Result.EllipsisLoc = EllipsisLoc;
448 return Result;
449}
450
Douglas Gregor788cd062009-11-11 01:00:40 +0000451static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
452 const ParsedTemplateArgument &Arg) {
453
454 switch (Arg.getKind()) {
455 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000456 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000457 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
458 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000459 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000460 return TemplateArgumentLoc(TemplateArgument(T), DI);
461 }
462
463 case ParsedTemplateArgument::NonType: {
464 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
465 return TemplateArgumentLoc(TemplateArgument(E), E);
466 }
467
468 case ParsedTemplateArgument::Template: {
John McCall2b5289b2010-08-23 07:28:44 +0000469 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregorba68eca2011-01-05 17:40:24 +0000470 return TemplateArgumentLoc(TemplateArgument(Template,
471 Arg.getEllipsisLoc().isValid()),
Douglas Gregor788cd062009-11-11 01:00:40 +0000472 Arg.getScopeSpec().getRange(),
Douglas Gregorba68eca2011-01-05 17:40:24 +0000473 Arg.getLocation(),
474 Arg.getEllipsisLoc());
Douglas Gregor788cd062009-11-11 01:00:40 +0000475 }
476 }
477
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000478 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000479 return TemplateArgumentLoc();
480}
481
482/// \brief Translates template arguments as provided by the parser
483/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000484void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
485 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000486 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000487 TemplateArgs.addArgument(translateTemplateArgument(*this,
488 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000489}
490
Douglas Gregor72c3f312008-12-05 18:15:24 +0000491/// ActOnTypeParameter - Called when a C++ template type parameter
492/// (e.g., "typename T") has been parsed. Typename specifies whether
493/// the keyword "typename" was used to declare the type parameter
494/// (otherwise, "class" was used), and KeyLoc is the location of the
495/// "class" or "typename" keyword. ParamName is the name of the
496/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregorefed5c82010-06-16 15:23:05 +0000497/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000498/// If the type parameter has a default argument, it will be added
499/// later via ActOnTypeParameterDefault.
John McCalld226f652010-08-21 09:40:31 +0000500Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
501 SourceLocation EllipsisLoc,
502 SourceLocation KeyLoc,
503 IdentifierInfo *ParamName,
504 SourceLocation ParamNameLoc,
505 unsigned Depth, unsigned Position,
506 SourceLocation EqualLoc,
John McCallb3d87482010-08-24 05:47:05 +0000507 ParsedType DefaultArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000508 assert(S->isTemplateParamScope() &&
509 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000510 bool Invalid = false;
511
512 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000513 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000514 LookupOrdinaryName,
515 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000516 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000517 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000518 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000519 }
520
Douglas Gregorddc29e12009-02-06 22:42:48 +0000521 SourceLocation Loc = ParamNameLoc;
522 if (!ParamName)
523 Loc = KeyLoc;
524
Douglas Gregor72c3f312008-12-05 18:15:24 +0000525 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000526 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
527 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000528 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000529 if (Invalid)
530 Param->setInvalidDecl();
531
532 if (ParamName) {
533 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000534 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000535 IdResolver.AddDecl(Param);
536 }
537
Douglas Gregor61c4d282011-01-05 15:48:55 +0000538 // C++0x [temp.param]p9:
539 // A default template-argument may be specified for any kind of
540 // template-parameter that is not a template parameter pack.
541 if (DefaultArg && Ellipsis) {
542 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
543 DefaultArg = ParsedType();
544 }
545
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000546 // Handle the default argument, if provided.
547 if (DefaultArg) {
548 TypeSourceInfo *DefaultTInfo;
549 GetTypeFromParser(DefaultArg, &DefaultTInfo);
550
551 assert(DefaultTInfo && "expected source information for type");
552
Douglas Gregor6f526752010-12-16 08:48:57 +0000553 // Check for unexpanded parameter packs.
554 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
555 UPPC_DefaultArgument))
556 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000557
558 // Check the template argument itself.
559 if (CheckTemplateArgument(Param, DefaultTInfo)) {
560 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000561 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000562 }
563
564 Param->setDefaultArgument(DefaultTInfo, false);
565 }
566
John McCalld226f652010-08-21 09:40:31 +0000567 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000568}
569
Douglas Gregor2943aed2009-03-03 04:44:36 +0000570/// \brief Check that the type of a non-type template parameter is
571/// well-formed.
572///
573/// \returns the (possibly-promoted) parameter type if valid;
574/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000575QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000576Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000577 // We don't allow variably-modified types as the type of non-type template
578 // parameters.
579 if (T->isVariablyModifiedType()) {
580 Diag(Loc, diag::err_variably_modified_nontype_template_param)
581 << T;
582 return QualType();
583 }
584
Douglas Gregor2943aed2009-03-03 04:44:36 +0000585 // C++ [temp.param]p4:
586 //
587 // A non-type template-parameter shall have one of the following
588 // (optionally cv-qualified) types:
589 //
590 // -- integral or enumeration type,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000591 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000592 // -- pointer to object or pointer to function,
Eli Friedman13578692010-08-05 02:49:48 +0000593 T->isPointerType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000594 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000595 T->isReferenceType() ||
596 // -- pointer to member.
597 T->isMemberPointerType() ||
598 // If T is a dependent type, we can't do the check now, so we
599 // assume that it is well-formed.
600 T->isDependentType())
601 return T;
602 // C++ [temp.param]p8:
603 //
604 // A non-type template-parameter of type "array of T" or
605 // "function returning T" is adjusted to be of type "pointer to
606 // T" or "pointer to function returning T", respectively.
607 else if (T->isArrayType())
608 // FIXME: Keep the type prior to promotion?
609 return Context.getArrayDecayedType(T);
610 else if (T->isFunctionType())
611 // FIXME: Keep the type prior to promotion?
612 return Context.getPointerType(T);
Douglas Gregor0fddb972010-05-22 16:17:30 +0000613
Douglas Gregor2943aed2009-03-03 04:44:36 +0000614 Diag(Loc, diag::err_template_nontype_parm_bad_type)
615 << T;
616
617 return QualType();
618}
619
John McCalld226f652010-08-21 09:40:31 +0000620Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
621 unsigned Depth,
622 unsigned Position,
623 SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000624 Expr *Default) {
John McCallbf1a0282010-06-04 23:28:52 +0000625 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
626 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000627
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000628 assert(S->isTemplateParamScope() &&
629 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000630 bool Invalid = false;
631
632 IdentifierInfo *ParamName = D.getIdentifier();
633 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000634 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000635 LookupOrdinaryName,
636 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000637 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000638 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000639 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000640 }
641
Douglas Gregor4d2abba2010-12-16 15:36:43 +0000642 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
643 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000644 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000645 Invalid = true;
646 }
Douglas Gregor781def02010-12-16 08:56:23 +0000647
Douglas Gregor10738d32010-12-23 23:51:58 +0000648 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000649 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000650 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
651 D.getIdentifierLoc(),
Douglas Gregor10738d32010-12-23 23:51:58 +0000652 Depth, Position, ParamName, T,
653 IsParameterPack, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000654 if (Invalid)
655 Param->setInvalidDecl();
656
657 if (D.getIdentifier()) {
658 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000659 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000660 IdResolver.AddDecl(Param);
661 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000662
Douglas Gregor61c4d282011-01-05 15:48:55 +0000663 // C++0x [temp.param]p9:
664 // A default template-argument may be specified for any kind of
665 // template-parameter that is not a template parameter pack.
666 if (Default && IsParameterPack) {
667 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
668 Default = 0;
669 }
670
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000671 // Check the well-formedness of the default template argument, if provided.
Douglas Gregor10738d32010-12-23 23:51:58 +0000672 if (Default) {
Douglas Gregor6f526752010-12-16 08:48:57 +0000673 // Check for unexpanded parameter packs.
674 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
675 return Param;
676
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000677 TemplateArgument Converted;
678 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
679 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000680 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000681 }
682
John McCall9ae2f072010-08-23 23:25:46 +0000683 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000684 }
685
John McCalld226f652010-08-21 09:40:31 +0000686 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000687}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000688
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000689/// ActOnTemplateTemplateParameter - Called when a C++ template template
690/// parameter (e.g. T in template <template <typename> class T> class array)
691/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000692Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
693 SourceLocation TmpLoc,
694 TemplateParamsTy *Params,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000695 SourceLocation EllipsisLoc,
John McCalld226f652010-08-21 09:40:31 +0000696 IdentifierInfo *Name,
697 SourceLocation NameLoc,
698 unsigned Depth,
699 unsigned Position,
700 SourceLocation EqualLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000701 ParsedTemplateArgument Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000702 assert(S->isTemplateParamScope() &&
703 "Template template parameter not in template parameter scope!");
704
705 // Construct the parameter object.
Douglas Gregor61c4d282011-01-05 15:48:55 +0000706 bool IsParameterPack = EllipsisLoc.isValid();
707 // FIXME: Pack-ness is dropped
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000708 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000709 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000710 NameLoc.isInvalid()? TmpLoc : NameLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000711 Depth, Position, IsParameterPack,
712 Name, Params);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000713
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000714 // If the template template parameter has a name, then link the identifier
715 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000716 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000717 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000718 IdResolver.AddDecl(Param);
719 }
720
Douglas Gregor6f526752010-12-16 08:48:57 +0000721 if (Params->size() == 0) {
722 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
723 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
724 Param->setInvalidDecl();
725 }
726
Douglas Gregor61c4d282011-01-05 15:48:55 +0000727 // C++0x [temp.param]p9:
728 // A default template-argument may be specified for any kind of
729 // template-parameter that is not a template parameter pack.
730 if (IsParameterPack && !Default.isInvalid()) {
731 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
732 Default = ParsedTemplateArgument();
733 }
734
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000735 if (!Default.isInvalid()) {
736 // Check only that we have a template template argument. We don't want to
737 // try to check well-formedness now, because our template template parameter
738 // might have dependent types in its template parameters, which we wouldn't
739 // be able to match now.
740 //
741 // If none of the template template parameter's template arguments mention
742 // other template parameters, we could actually perform more checking here.
743 // However, it isn't worth doing.
744 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
745 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
746 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
747 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000748 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000749 }
750
Douglas Gregor6f526752010-12-16 08:48:57 +0000751 // Check for unexpanded parameter packs.
752 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
753 DefaultArg.getArgument().getAsTemplate(),
754 UPPC_DefaultArgument))
755 return Param;
756
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000757 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000758 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000759
John McCalld226f652010-08-21 09:40:31 +0000760 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000761}
762
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000763/// ActOnTemplateParameterList - Builds a TemplateParameterList that
764/// contains the template parameters in Params/NumParams.
765Sema::TemplateParamsTy *
766Sema::ActOnTemplateParameterList(unsigned Depth,
767 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000768 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000769 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000770 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000771 SourceLocation RAngleLoc) {
772 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000773 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000774
Douglas Gregorddc29e12009-02-06 22:42:48 +0000775 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000776 (NamedDecl**)Params, NumParams,
777 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000778}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000779
John McCallb6217662010-03-15 10:12:16 +0000780static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
781 if (SS.isSet())
782 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
783 SS.getRange());
784}
785
John McCallf312b1e2010-08-26 23:41:50 +0000786DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000787Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000788 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000789 IdentifierInfo *Name, SourceLocation NameLoc,
790 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000791 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000792 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000793 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000794 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000795 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000796 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000797
798 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000799 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000800 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000801
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000802 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
803 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000804
805 // There is no such thing as an unnamed class template.
806 if (!Name) {
807 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000808 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000809 }
810
811 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000812 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000813 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000814 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000815 if (SS.isNotEmpty() && !SS.isInvalid()) {
816 SemanticContext = computeDeclContext(SS, true);
817 if (!SemanticContext) {
818 // FIXME: Produce a reasonable diagnostic here
819 return true;
820 }
Mike Stump1eb44332009-09-09 15:08:12 +0000821
John McCall77bb1aa2010-05-01 00:40:08 +0000822 if (RequireCompleteDeclContext(SS, SemanticContext))
823 return true;
824
John McCalla24dc2e2009-11-17 02:14:36 +0000825 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000826 } else {
827 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000828 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000829 }
Mike Stump1eb44332009-09-09 15:08:12 +0000830
Douglas Gregor57265e32010-04-12 16:00:01 +0000831 if (Previous.isAmbiguous())
832 return true;
833
Douglas Gregorddc29e12009-02-06 22:42:48 +0000834 NamedDecl *PrevDecl = 0;
835 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000836 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000837
Douglas Gregorddc29e12009-02-06 22:42:48 +0000838 // If there is a previous declaration with the same name, check
839 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000840 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000841 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000842
843 // We may have found the injected-class-name of a class template,
844 // class template partial specialization, or class template specialization.
845 // In these cases, grab the template that is being defined or specialized.
846 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
847 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
848 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
849 PrevClassTemplate
850 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
851 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
852 PrevClassTemplate
853 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
854 ->getSpecializedTemplate();
855 }
856 }
857
John McCall65c49462009-12-18 11:25:59 +0000858 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000859 // C++ [namespace.memdef]p3:
860 // [...] When looking for a prior declaration of a class or a function
861 // declared as a friend, and when the name of the friend class or
862 // function is neither a qualified name nor a template-id, scopes outside
863 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000864 if (!SS.isSet()) {
865 DeclContext *OutermostContext = CurContext;
866 while (!OutermostContext->isFileContext())
867 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000868
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000869 if (PrevDecl &&
870 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
871 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
872 SemanticContext = PrevDecl->getDeclContext();
873 } else {
874 // Declarations in outer scopes don't matter. However, the outermost
875 // context we computed is the semantic context for our new
876 // declaration.
877 PrevDecl = PrevClassTemplate = 0;
878 SemanticContext = OutermostContext;
879 }
John McCalle129d442009-12-17 23:21:11 +0000880 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000881
John McCalle129d442009-12-17 23:21:11 +0000882 if (CurContext->isDependentContext()) {
883 // If this is a dependent context, we don't want to link the friend
884 // class template to the template in scope, because that would perform
885 // checking of the template parameter lists that can't be performed
886 // until the outer context is instantiated.
887 PrevDecl = PrevClassTemplate = 0;
888 }
889 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
890 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000891
Douglas Gregorddc29e12009-02-06 22:42:48 +0000892 if (PrevClassTemplate) {
893 // Ensure that the template parameter lists are compatible.
894 if (!TemplateParameterListsAreEqual(TemplateParams,
895 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000896 /*Complain=*/true,
897 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000898 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000899
900 // C++ [temp.class]p4:
901 // In a redeclaration, partial specialization, explicit
902 // specialization or explicit instantiation of a class template,
903 // the class-key shall agree in kind with the original class
904 // template declaration (7.1.5.3).
905 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000906 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000907 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000908 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000909 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000910 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000911 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000912 }
913
Douglas Gregorddc29e12009-02-06 22:42:48 +0000914 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000915 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000916 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000917 Diag(NameLoc, diag::err_redefinition) << Name;
918 Diag(Def->getLocation(), diag::note_previous_definition);
919 // FIXME: Would it make sense to try to "forget" the previous
920 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000921 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000922 }
923 }
924 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
925 // Maybe we will complain about the shadowed template parameter.
926 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
927 // Just pretend that we didn't see the previous declaration.
928 PrevDecl = 0;
929 } else if (PrevDecl) {
930 // C++ [temp]p5:
931 // A class template shall not have the same name as any other
932 // template, class, function, object, enumeration, enumerator,
933 // namespace, or type in the same scope (3.3), except as specified
934 // in (14.5.4).
935 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
936 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000937 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000938 }
939
Douglas Gregord684b002009-02-10 19:49:53 +0000940 // Check the template parameter list of this declaration, possibly
941 // merging in the template parameter list from the previous class
942 // template declaration.
943 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000944 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
945 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000946 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Douglas Gregor57265e32010-04-12 16:00:01 +0000948 if (SS.isSet()) {
949 // If the name of the template was qualified, we must be defining the
950 // template out-of-line.
951 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
952 !(TUK == TUK_Friend && CurContext->isDependentContext()))
953 Diag(NameLoc, diag::err_member_def_does_not_match)
954 << Name << SemanticContext << SS.getRange();
955 }
956
Mike Stump1eb44332009-09-09 15:08:12 +0000957 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000958 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000959 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000960 PrevClassTemplate->getTemplatedDecl() : 0,
961 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000962 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000963
964 ClassTemplateDecl *NewTemplate
965 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
966 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000967 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000968 NewClass->setDescribedClassTemplate(NewTemplate);
969
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000970 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +0000971 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +0000972 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000973 assert(T->isDependentType() && "Class template type is not dependent?");
974 (void)T;
975
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000976 // If we are providing an explicit specialization of a member that is a
977 // class template, make a note of that.
978 if (PrevClassTemplate &&
979 PrevClassTemplate->getInstantiatedFromMemberTemplate())
980 PrevClassTemplate->setMemberSpecialization();
981
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000982 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000983 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000984 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Douglas Gregorddc29e12009-02-06 22:42:48 +0000986 // Set the lexical context of these templates
987 NewClass->setLexicalDeclContext(CurContext);
988 NewTemplate->setLexicalDeclContext(CurContext);
989
John McCall0f434ec2009-07-31 02:45:11 +0000990 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000991 NewClass->startDefinition();
992
993 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000994 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000995
John McCall05b23ea2009-09-14 21:59:20 +0000996 if (TUK != TUK_Friend)
997 PushOnScopeChains(NewTemplate, S);
998 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000999 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +00001000 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +00001001 NewClass->setAccess(PrevClassTemplate->getAccess());
1002 }
John McCall05b23ea2009-09-14 21:59:20 +00001003
Douglas Gregord85bea22009-09-26 06:47:28 +00001004 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
1005 PrevClassTemplate != NULL);
1006
John McCall05b23ea2009-09-14 21:59:20 +00001007 // Friend templates are visible in fairly strange ways.
1008 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001009 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall05b23ea2009-09-14 21:59:20 +00001010 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
1011 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1012 PushOnScopeChains(NewTemplate, EnclosingScope,
1013 /* AddToContext = */ false);
1014 }
Douglas Gregord85bea22009-09-26 06:47:28 +00001015
1016 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1017 NewClass->getLocation(),
1018 NewTemplate,
1019 /*FIXME:*/NewClass->getLocation());
1020 Friend->setAccess(AS_public);
1021 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +00001022 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00001023
Douglas Gregord684b002009-02-10 19:49:53 +00001024 if (Invalid) {
1025 NewTemplate->setInvalidDecl();
1026 NewClass->setInvalidDecl();
1027 }
John McCalld226f652010-08-21 09:40:31 +00001028 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +00001029}
1030
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001031/// \brief Diagnose the presence of a default template argument on a
1032/// template parameter, which is ill-formed in certain contexts.
1033///
1034/// \returns true if the default template argument should be dropped.
1035static bool DiagnoseDefaultTemplateArgument(Sema &S,
1036 Sema::TemplateParamListContext TPC,
1037 SourceLocation ParamLoc,
1038 SourceRange DefArgRange) {
1039 switch (TPC) {
1040 case Sema::TPC_ClassTemplate:
1041 return false;
1042
1043 case Sema::TPC_FunctionTemplate:
1044 // C++ [temp.param]p9:
1045 // A default template-argument shall not be specified in a
1046 // function template declaration or a function template
1047 // definition [...]
1048 // (This sentence is not in C++0x, per DR226).
1049 if (!S.getLangOptions().CPlusPlus0x)
1050 S.Diag(ParamLoc,
1051 diag::err_template_parameter_default_in_function_template)
1052 << DefArgRange;
1053 return false;
1054
1055 case Sema::TPC_ClassTemplateMember:
1056 // C++0x [temp.param]p9:
1057 // A default template-argument shall not be specified in the
1058 // template-parameter-lists of the definition of a member of a
1059 // class template that appears outside of the member's class.
1060 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1061 << DefArgRange;
1062 return true;
1063
1064 case Sema::TPC_FriendFunctionTemplate:
1065 // C++ [temp.param]p9:
1066 // A default template-argument shall not be specified in a
1067 // friend template declaration.
1068 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1069 << DefArgRange;
1070 return true;
1071
1072 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1073 // for friend function templates if there is only a single
1074 // declaration (and it is a definition). Strange!
1075 }
1076
1077 return false;
1078}
1079
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001080/// \brief Check for unexpanded parameter packs within the template parameters
1081/// of a template template parameter, recursively.
1082bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP){
1083 TemplateParameterList *Params = TTP->getTemplateParameters();
1084 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1085 NamedDecl *P = Params->getParam(I);
1086 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1087 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1088 NTTP->getTypeSourceInfo(),
1089 Sema::UPPC_NonTypeTemplateParameterType))
1090 return true;
1091
1092 continue;
1093 }
1094
1095 if (TemplateTemplateParmDecl *InnerTTP
1096 = dyn_cast<TemplateTemplateParmDecl>(P))
1097 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1098 return true;
1099 }
1100
1101 return false;
1102}
1103
Douglas Gregord684b002009-02-10 19:49:53 +00001104/// \brief Checks the validity of a template parameter list, possibly
1105/// considering the template parameter list from a previous
1106/// declaration.
1107///
1108/// If an "old" template parameter list is provided, it must be
1109/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1110/// template parameter list.
1111///
1112/// \param NewParams Template parameter list for a new template
1113/// declaration. This template parameter list will be updated with any
1114/// default arguments that are carried through from the previous
1115/// template parameter list.
1116///
1117/// \param OldParams If provided, template parameter list from a
1118/// previous declaration of the same template. Default template
1119/// arguments will be merged from the old template parameter list to
1120/// the new template parameter list.
1121///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001122/// \param TPC Describes the context in which we are checking the given
1123/// template parameter list.
1124///
Douglas Gregord684b002009-02-10 19:49:53 +00001125/// \returns true if an error occurred, false otherwise.
1126bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001127 TemplateParameterList *OldParams,
1128 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001129 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Douglas Gregord684b002009-02-10 19:49:53 +00001131 // C++ [temp.param]p10:
1132 // The set of default template-arguments available for use with a
1133 // template declaration or definition is obtained by merging the
1134 // default arguments from the definition (if in scope) and all
1135 // declarations in scope in the same way default function
1136 // arguments are (8.3.6).
1137 bool SawDefaultArgument = false;
1138 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001139
Anders Carlsson49d25572009-06-12 23:20:15 +00001140 bool SawParameterPack = false;
1141 SourceLocation ParameterPackLoc;
1142
Mike Stump1a35fde2009-02-11 23:03:27 +00001143 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001144 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001145 if (OldParams)
1146 OldParam = OldParams->begin();
1147
1148 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1149 NewParamEnd = NewParams->end();
1150 NewParam != NewParamEnd; ++NewParam) {
1151 // Variables used to diagnose redundant default arguments
1152 bool RedundantDefaultArg = false;
1153 SourceLocation OldDefaultLoc;
1154 SourceLocation NewDefaultLoc;
1155
1156 // Variables used to diagnose missing default arguments
1157 bool MissingDefaultArg = false;
1158
Anders Carlsson49d25572009-06-12 23:20:15 +00001159 // C++0x [temp.param]p11:
Douglas Gregor1ed64762011-01-05 16:19:19 +00001160 // If a template parameter of a primary class template is a template
1161 // parameter pack, it shall be the last template parameter.
1162 if (SawParameterPack && TPC == TPC_ClassTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00001163 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001164 diag::err_template_param_pack_must_be_last_template_parameter);
1165 Invalid = true;
1166 }
1167
Douglas Gregord684b002009-02-10 19:49:53 +00001168 if (TemplateTypeParmDecl *NewTypeParm
1169 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001170 // Check the presence of a default argument here.
1171 if (NewTypeParm->hasDefaultArgument() &&
1172 DiagnoseDefaultTemplateArgument(*this, TPC,
1173 NewTypeParm->getLocation(),
1174 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001175 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001176 NewTypeParm->removeDefaultArgument();
1177
1178 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001179 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001180 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Anders Carlsson49d25572009-06-12 23:20:15 +00001182 if (NewTypeParm->isParameterPack()) {
1183 assert(!NewTypeParm->hasDefaultArgument() &&
1184 "Parameter packs can't have a default argument!");
1185 SawParameterPack = true;
1186 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001187 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001188 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001189 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1190 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1191 SawDefaultArgument = true;
1192 RedundantDefaultArg = true;
1193 PreviousDefaultArgLoc = NewDefaultLoc;
1194 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1195 // Merge the default argument from the old declaration to the
1196 // new declaration.
1197 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001198 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001199 true);
1200 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1201 } else if (NewTypeParm->hasDefaultArgument()) {
1202 SawDefaultArgument = true;
1203 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1204 } else if (SawDefaultArgument)
1205 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001206 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001207 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001208 // Check for unexpanded parameter packs.
1209 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1210 NewNonTypeParm->getTypeSourceInfo(),
1211 UPPC_NonTypeTemplateParameterType)) {
1212 Invalid = true;
1213 continue;
1214 }
1215
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001216 // Check the presence of a default argument here.
1217 if (NewNonTypeParm->hasDefaultArgument() &&
1218 DiagnoseDefaultTemplateArgument(*this, TPC,
1219 NewNonTypeParm->getLocation(),
1220 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001221 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001222 }
1223
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001224 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001225 NonTypeTemplateParmDecl *OldNonTypeParm
1226 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001227 if (NewNonTypeParm->isParameterPack()) {
1228 assert(!NewNonTypeParm->hasDefaultArgument() &&
1229 "Parameter packs can't have a default argument!");
1230 SawParameterPack = true;
1231 ParameterPackLoc = NewNonTypeParm->getLocation();
1232 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001233 NewNonTypeParm->hasDefaultArgument()) {
1234 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1235 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1236 SawDefaultArgument = true;
1237 RedundantDefaultArg = true;
1238 PreviousDefaultArgLoc = NewDefaultLoc;
1239 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1240 // Merge the default argument from the old declaration to the
1241 // new declaration.
1242 SawDefaultArgument = true;
1243 // FIXME: We need to create a new kind of "default argument"
Douglas Gregor61c4d282011-01-05 15:48:55 +00001244 // expression that points to a previous non-type template
Douglas Gregord684b002009-02-10 19:49:53 +00001245 // parameter.
1246 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001247 OldNonTypeParm->getDefaultArgument(),
1248 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001249 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1250 } else if (NewNonTypeParm->hasDefaultArgument()) {
1251 SawDefaultArgument = true;
1252 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1253 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001254 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001255 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001256 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001257 TemplateTemplateParmDecl *NewTemplateParm
1258 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001259
1260 // Check for unexpanded parameter packs, recursively.
1261 if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1262 Invalid = true;
1263 continue;
1264 }
1265
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001266 if (NewTemplateParm->hasDefaultArgument() &&
1267 DiagnoseDefaultTemplateArgument(*this, TPC,
1268 NewTemplateParm->getLocation(),
1269 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001270 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001271
1272 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001273 TemplateTemplateParmDecl *OldTemplateParm
1274 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001275 if (NewTemplateParm->isParameterPack()) {
1276 assert(!NewTemplateParm->hasDefaultArgument() &&
1277 "Parameter packs can't have a default argument!");
1278 SawParameterPack = true;
1279 ParameterPackLoc = NewTemplateParm->getLocation();
1280 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001281 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001282 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1283 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001284 SawDefaultArgument = true;
1285 RedundantDefaultArg = true;
1286 PreviousDefaultArgLoc = NewDefaultLoc;
1287 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1288 // Merge the default argument from the old declaration to the
1289 // new declaration.
1290 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001291 // FIXME: We need to create a new kind of "default argument" expression
1292 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001293 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001294 OldTemplateParm->getDefaultArgument(),
1295 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001296 PreviousDefaultArgLoc
1297 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001298 } else if (NewTemplateParm->hasDefaultArgument()) {
1299 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001300 PreviousDefaultArgLoc
1301 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001302 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001303 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001304 }
1305
1306 if (RedundantDefaultArg) {
1307 // C++ [temp.param]p12:
1308 // A template-parameter shall not be given default arguments
1309 // by two different declarations in the same scope.
1310 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1311 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1312 Invalid = true;
1313 } else if (MissingDefaultArg) {
1314 // C++ [temp.param]p11:
Douglas Gregorb49e4152011-01-05 16:21:17 +00001315 // If a template-parameter of a class template has a default
1316 // template-argument, each subsequent template- parameter shall either
1317 // have a default template-argument supplied or be a template parameter
1318 // pack.
Mike Stump1eb44332009-09-09 15:08:12 +00001319 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001320 diag::err_template_param_default_arg_missing);
1321 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1322 Invalid = true;
1323 }
1324
1325 // If we have an old template parameter list that we're merging
1326 // in, move on to the next parameter.
1327 if (OldParams)
1328 ++OldParam;
1329 }
1330
1331 return Invalid;
1332}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001333
John McCall4e2cbb22010-10-20 05:44:58 +00001334namespace {
1335
1336/// A class which looks for a use of a certain level of template
1337/// parameter.
1338struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1339 typedef RecursiveASTVisitor<DependencyChecker> super;
1340
1341 unsigned Depth;
1342 bool Match;
1343
1344 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1345 NamedDecl *ND = Params->getParam(0);
1346 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1347 Depth = PD->getDepth();
1348 } else if (NonTypeTemplateParmDecl *PD =
1349 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1350 Depth = PD->getDepth();
1351 } else {
1352 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1353 }
1354 }
1355
1356 bool Matches(unsigned ParmDepth) {
1357 if (ParmDepth >= Depth) {
1358 Match = true;
1359 return true;
1360 }
1361 return false;
1362 }
1363
1364 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1365 return !Matches(T->getDepth());
1366 }
1367
1368 bool TraverseTemplateName(TemplateName N) {
1369 if (TemplateTemplateParmDecl *PD =
1370 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1371 if (Matches(PD->getDepth())) return false;
1372 return super::TraverseTemplateName(N);
1373 }
1374
1375 bool VisitDeclRefExpr(DeclRefExpr *E) {
1376 if (NonTypeTemplateParmDecl *PD =
1377 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1378 if (PD->getDepth() == Depth) {
1379 Match = true;
1380 return false;
1381 }
1382 }
1383 return super::VisitDeclRefExpr(E);
1384 }
1385};
1386}
1387
1388/// Determines whether a template-id depends on the given parameter
1389/// list.
1390static bool
1391DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId,
1392 TemplateParameterList *Params) {
1393 DependencyChecker Checker(Params);
1394 Checker.TraverseType(QualType(TemplateId, 0));
1395 return Checker.Match;
1396}
1397
Mike Stump1eb44332009-09-09 15:08:12 +00001398/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001399/// specifier, returning the template parameter list that applies to the
1400/// name.
1401///
1402/// \param DeclStartLoc the start of the declaration that has a scope
1403/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001404///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001405/// \param SS the scope specifier that will be matched to the given template
1406/// parameter lists. This scope specifier precedes a qualified name that is
1407/// being declared.
1408///
1409/// \param ParamLists the template parameter lists, from the outermost to the
1410/// innermost template parameter lists.
1411///
1412/// \param NumParamLists the number of template parameter lists in ParamLists.
1413///
John McCall77e8b112010-04-13 20:37:33 +00001414/// \param IsFriend Whether to apply the slightly different rules for
1415/// matching template parameters to scope specifiers in friend
1416/// declarations.
1417///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001418/// \param IsExplicitSpecialization will be set true if the entity being
1419/// declared is an explicit specialization, false otherwise.
1420///
Mike Stump1eb44332009-09-09 15:08:12 +00001421/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001422/// name that is preceded by the scope specifier @p SS. This template
1423/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001424/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001425/// template specialization), or may be NULL (if we were's declaring isn't
1426/// itself a template).
1427TemplateParameterList *
1428Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1429 const CXXScopeSpec &SS,
1430 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001431 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001432 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001433 bool &IsExplicitSpecialization,
1434 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001435 IsExplicitSpecialization = false;
1436
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001437 // Find the template-ids that occur within the nested-name-specifier. These
1438 // template-ids will match up with the template parameter lists.
1439 llvm::SmallVector<const TemplateSpecializationType *, 4>
1440 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001441 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1442 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001443 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1444 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001445 const Type *T = NNS->getAsType();
1446 if (!T) break;
1447
1448 // C++0x [temp.expl.spec]p17:
1449 // A member or a member template may be nested within many
1450 // enclosing class templates. In an explicit specialization for
1451 // such a member, the member declaration shall be preceded by a
1452 // template<> for each enclosing class template that is
1453 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001454 //
1455 // Following the existing practice of GNU and EDG, we allow a typedef of a
1456 // template specialization type.
John McCall49f4e1c2010-12-10 11:01:00 +00001457 while (const TypedefType *TT = dyn_cast<TypedefType>(T))
1458 T = TT->getDecl()->getUnderlyingType().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001459
Mike Stump1eb44332009-09-09 15:08:12 +00001460 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001461 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001462 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1463 if (!Template)
1464 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Ted Kremenek6217b802009-07-29 21:53:49 +00001466 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001467 ClassTemplateSpecializationDecl *SpecDecl
1468 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1469 // If the nested name specifier refers to an explicit specialization,
1470 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001471 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1472 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001473 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001474 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001475 }
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001477 TemplateIdsInSpecifier.push_back(SpecType);
1478 }
1479 }
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001481 // Reverse the list of template-ids in the scope specifier, so that we can
1482 // more easily match up the template-ids and the template parameter lists.
1483 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001485 SourceLocation FirstTemplateLoc = DeclStartLoc;
1486 if (NumParamLists)
1487 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001489 // Match the template-ids found in the specifier to the template parameter
1490 // lists.
John McCall4e2cbb22010-10-20 05:44:58 +00001491 unsigned ParamIdx = 0, TemplateIdx = 0;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001492 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
John McCall4e2cbb22010-10-20 05:44:58 +00001493 TemplateIdx != NumTemplateIds; ++TemplateIdx) {
1494 const TemplateSpecializationType *TemplateId
1495 = TemplateIdsInSpecifier[TemplateIdx];
Douglas Gregorb88e8882009-07-30 17:40:51 +00001496 bool DependentTemplateId = TemplateId->isDependentType();
John McCall4e2cbb22010-10-20 05:44:58 +00001497
1498 // In friend declarations we can have template-ids which don't
1499 // depend on the corresponding template parameter lists. But
1500 // assume that empty parameter lists are supposed to match this
1501 // template-id.
1502 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) {
1503 if (!DependentTemplateId ||
1504 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx]))
1505 continue;
1506 }
1507
1508 if (ParamIdx >= NumParamLists) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001509 // We have a template-id without a corresponding template parameter
1510 // list.
John McCall77e8b112010-04-13 20:37:33 +00001511
1512 // ...which is fine if this is a friend declaration.
1513 if (IsFriend) {
1514 IsExplicitSpecialization = true;
1515 break;
1516 }
1517
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001518 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001519 // FIXME: the location information here isn't great.
1520 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001521 diag::err_template_spec_needs_template_parameters)
John McCall4e2cbb22010-10-20 05:44:58 +00001522 << QualType(TemplateId, 0)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001523 << SS.getRange();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001524 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001525 } else {
1526 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1527 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001528 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001529 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001530 }
1531 return 0;
1532 }
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001534 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001535 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001536 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001537
John McCall31f17ec2010-04-27 00:57:59 +00001538 // Are there cases in (e.g.) friends where this won't match?
1539 if (const InjectedClassNameType *Injected
1540 = TemplateId->getAs<InjectedClassNameType>()) {
1541 CXXRecordDecl *Record = Injected->getDecl();
1542 if (ClassTemplatePartialSpecializationDecl *Partial =
1543 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1544 ExpectedTemplateParams = Partial->getTemplateParameters();
1545 else
1546 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1547 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001548 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001549
John McCall31f17ec2010-04-27 00:57:59 +00001550 if (ExpectedTemplateParams)
John McCall4e2cbb22010-10-20 05:44:58 +00001551 TemplateParameterListsAreEqual(ParamLists[ParamIdx],
John McCall31f17ec2010-04-27 00:57:59 +00001552 ExpectedTemplateParams,
1553 true, TPL_TemplateMatch);
1554
John McCall4e2cbb22010-10-20 05:44:58 +00001555 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1556 TPC_ClassTemplateMember);
1557 } else if (ParamLists[ParamIdx]->size() > 0)
1558 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001559 diag::err_template_param_list_matches_nontemplate)
1560 << TemplateId
John McCall4e2cbb22010-10-20 05:44:58 +00001561 << ParamLists[ParamIdx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001562 else
1563 IsExplicitSpecialization = true;
John McCall4e2cbb22010-10-20 05:44:58 +00001564
1565 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001566 }
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001568 // If there were at least as many template-ids as there were template
1569 // parameter lists, then there are no template parameter lists remaining for
1570 // the declaration itself.
John McCall4e2cbb22010-10-20 05:44:58 +00001571 if (ParamIdx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001572 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001574 // If there were too many template parameter lists, complain about that now.
John McCall4e2cbb22010-10-20 05:44:58 +00001575 if (ParamIdx != NumParamLists - 1) {
1576 while (ParamIdx < NumParamLists - 1) {
1577 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0;
1578 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001579 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1580 : diag::err_template_spec_extra_headers)
John McCall4e2cbb22010-10-20 05:44:58 +00001581 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1582 ParamLists[ParamIdx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001583
1584 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1585 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1586 diag::note_explicit_template_spec_does_not_need_header)
1587 << ExplicitSpecializationsInSpecifier.back();
1588 ExplicitSpecializationsInSpecifier.pop_back();
1589 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001590
1591 // We have a template parameter list with no corresponding scope, which
1592 // means that the resulting template declaration can't be instantiated
1593 // properly (we'll end up with dependent nodes when we shouldn't).
1594 if (!isExplicitSpecHeader)
1595 Invalid = true;
1596
John McCall4e2cbb22010-10-20 05:44:58 +00001597 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001598 }
1599 }
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001601 // Return the last template parameter list, which corresponds to the
1602 // entity being declared.
1603 return ParamLists[NumParamLists - 1];
1604}
1605
Douglas Gregor7532dc62009-03-30 22:58:21 +00001606QualType Sema::CheckTemplateIdType(TemplateName Name,
1607 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001608 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001609 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001610 if (!Template) {
1611 // The template name does not resolve to a template, so we just
1612 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001613 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001614 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001615
Douglas Gregor40808ce2009-03-09 23:48:35 +00001616 // Check that the template argument list is well-formed for this
1617 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001618 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00001619 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001620 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001621 return QualType();
1622
Douglas Gregor910f8002010-11-07 23:05:16 +00001623 assert((Converted.size() == Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001624 "Converted template argument list is too short!");
1625
1626 QualType CanonType;
1627
Douglas Gregorcaddba02009-11-12 18:38:13 +00001628 if (Name.isDependent() ||
1629 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001630 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001631 // This class template specialization is a dependent
1632 // type. Therefore, its canonical type is another class template
1633 // specialization type that contains all of the converted
1634 // arguments in canonical form. This ensures that, e.g., A<T> and
1635 // A<T, T> have identical types when A is declared as:
1636 //
1637 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001638 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001639 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor910f8002010-11-07 23:05:16 +00001640 Converted.data(),
1641 Converted.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Douglas Gregor1275ae02009-07-28 23:00:59 +00001643 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001644 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001645 // In the future, we need to teach getTemplateSpecializationType to only
1646 // build the canonical type and return that to us.
1647 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001648
1649 // This might work out to be a current instantiation, in which
1650 // case the canonical type needs to be the InjectedClassNameType.
1651 //
1652 // TODO: in theory this could be a simple hashtable lookup; most
1653 // changes to CurContext don't change the set of current
1654 // instantiations.
1655 if (isa<ClassTemplateDecl>(Template)) {
1656 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1657 // If we get out to a namespace, we're done.
1658 if (Ctx->isFileContext()) break;
1659
1660 // If this isn't a record, keep looking.
1661 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1662 if (!Record) continue;
1663
1664 // Look for one of the two cases with InjectedClassNameTypes
1665 // and check whether it's the same template.
1666 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1667 !Record->getDescribedClassTemplate())
1668 continue;
1669
1670 // Fetch the injected class name type and check whether its
1671 // injected type is equal to the type we just built.
1672 QualType ICNT = Context.getTypeDeclType(Record);
1673 QualType Injected = cast<InjectedClassNameType>(ICNT)
1674 ->getInjectedSpecializationType();
1675
1676 if (CanonType != Injected->getCanonicalTypeInternal())
1677 continue;
1678
1679 // If so, the canonical type of this TST is the injected
1680 // class name type of the record we just found.
1681 assert(ICNT.isCanonical());
1682 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00001683 break;
1684 }
1685 }
Mike Stump1eb44332009-09-09 15:08:12 +00001686 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001687 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001688 // Find the class template specialization declaration that
1689 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001690 void *InsertPos = 0;
1691 ClassTemplateSpecializationDecl *Decl
Douglas Gregor910f8002010-11-07 23:05:16 +00001692 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
1693 InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001694 if (!Decl) {
1695 // This is the first time we have referenced this class template
1696 // specialization. Create the canonical declaration and add it to
1697 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001698 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001699 ClassTemplate->getTemplatedDecl()->getTagKind(),
1700 ClassTemplate->getDeclContext(),
1701 ClassTemplate->getLocation(),
Douglas Gregor910f8002010-11-07 23:05:16 +00001702 ClassTemplate,
1703 Converted.data(),
1704 Converted.size(), 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001705 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001706 Decl->setLexicalDeclContext(CurContext);
1707 }
1708
1709 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001710 assert(isa<RecordType>(CanonType) &&
1711 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001712 }
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Douglas Gregor40808ce2009-03-09 23:48:35 +00001714 // Build the fully-sugared type for this class template
1715 // specialization, which refers back to the class template
1716 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00001717 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001718}
1719
John McCallf312b1e2010-08-26 23:41:50 +00001720TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001721Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001722 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001723 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001724 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001725 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001726
Douglas Gregor40808ce2009-03-09 23:48:35 +00001727 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001728 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001729 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001730
John McCalld5532b62009-11-23 01:53:49 +00001731 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001732 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001733
1734 if (Result.isNull())
1735 return true;
1736
John McCalla93c9342009-12-07 02:54:59 +00001737 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001738 TemplateSpecializationTypeLoc TL
1739 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1740 TL.setTemplateNameLoc(TemplateLoc);
1741 TL.setLAngleLoc(LAngleLoc);
1742 TL.setRAngleLoc(RAngleLoc);
1743 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1744 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1745
John McCallb3d87482010-08-24 05:47:05 +00001746 return CreateParsedType(Result, DI);
John McCall6b2becf2009-09-08 17:47:29 +00001747}
John McCallf1bbbb42009-09-04 01:14:41 +00001748
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001749TypeResult Sema::ActOnTagTemplateIdType(CXXScopeSpec &SS,
1750 TypeResult TypeResult,
John McCallf312b1e2010-08-26 23:41:50 +00001751 TagUseKind TUK,
1752 TypeSpecifierType TagSpec,
1753 SourceLocation TagLoc) {
John McCall6b2becf2009-09-08 17:47:29 +00001754 if (TypeResult.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001755 return ::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001756
John McCalla93c9342009-12-07 02:54:59 +00001757 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001758 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001759
John McCall6b2becf2009-09-08 17:47:29 +00001760 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001761 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001762
John McCall6b2becf2009-09-08 17:47:29 +00001763 if (const RecordType *RT = Type->getAs<RecordType>()) {
1764 RecordDecl *D = RT->getDecl();
1765
1766 IdentifierInfo *Id = D->getIdentifier();
1767 assert(Id && "templated class must have an identifier");
1768
1769 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1770 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001771 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001772 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001773 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001774 }
1775 }
1776
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001777 ElaboratedTypeKeyword Keyword
1778 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1779 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001780
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001781 TypeSourceInfo *ElabDI = Context.CreateTypeSourceInfo(ElabType);
1782 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(ElabDI->getTypeLoc());
1783 TL.setKeywordLoc(TagLoc);
1784 TL.setQualifierRange(SS.getRange());
1785 TL.getNamedTypeLoc().initializeFullCopy(DI->getTypeLoc());
1786 return CreateParsedType(ElabType, ElabDI);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001787}
1788
John McCall60d7b3a2010-08-24 06:29:42 +00001789ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001790 LookupResult &R,
1791 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001792 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001793 // FIXME: Can we do any checking at this point? I guess we could check the
1794 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001795 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001796 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001797
1798 // These should be filtered out by our callers.
1799 assert(!R.empty() && "empty lookup results when building templateid");
1800 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1801
1802 NestedNameSpecifier *Qualifier = 0;
1803 SourceRange QualifierRange;
1804 if (SS.isSet()) {
1805 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1806 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001807 }
John McCallc373d482010-01-27 01:50:18 +00001808
1809 // We don't want lookup warnings at this point.
1810 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001811
John McCallf7a1a742009-11-24 19:00:30 +00001812 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001813 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001814 Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00001815 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001816 RequiresADL, TemplateArgs,
1817 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001818
1819 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001820}
1821
John McCallf7a1a742009-11-24 19:00:30 +00001822// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00001823ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001824Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001825 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +00001826 const TemplateArgumentListInfo &TemplateArgs) {
1827 DeclContext *DC;
1828 if (!(DC = computeDeclContext(SS, false)) ||
1829 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001830 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara25777432010-08-11 22:01:17 +00001831 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001833 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00001834 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001835 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1836 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001837
John McCallf7a1a742009-11-24 19:00:30 +00001838 if (R.isAmbiguous())
1839 return ExprError();
1840
1841 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001842 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1843 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001844 return ExprError();
1845 }
1846
1847 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001848 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1849 << (NestedNameSpecifier*) SS.getScopeRep()
1850 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001851 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1852 return ExprError();
1853 }
1854
1855 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001856}
1857
Douglas Gregorc45c2322009-03-31 00:43:58 +00001858/// \brief Form a dependent template name.
1859///
1860/// This action forms a dependent template name given the template
1861/// name and its (presumably dependent) scope specifier. For
1862/// example, given "MetaFun::template apply", the scope specifier \p
1863/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1864/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001865TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1866 SourceLocation TemplateKWLoc,
1867 CXXScopeSpec &SS,
1868 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00001869 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001870 bool EnteringContext,
1871 TemplateTy &Result) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00001872 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1873 !getLangOptions().CPlusPlus0x)
1874 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1875 << FixItHint::CreateRemoval(TemplateKWLoc);
1876
Douglas Gregor0707bc52010-01-19 16:01:07 +00001877 DeclContext *LookupCtx = 0;
1878 if (SS.isSet())
1879 LookupCtx = computeDeclContext(SS, EnteringContext);
1880 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00001881 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00001882 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001883 // C++0x [temp.names]p5:
1884 // If a name prefixed by the keyword template is not the name of
1885 // a template, the program is ill-formed. [Note: the keyword
1886 // template may not be applied to non-template members of class
1887 // templates. -end note ] [ Note: as is the case with the
1888 // typename prefix, the template prefix is allowed in cases
1889 // where it is not strictly necessary; i.e., when the
1890 // nested-name-specifier or the expression on the left of the ->
1891 // or . is not dependent on a template-parameter, or the use
1892 // does not appear in the scope of a template. -end note]
1893 //
1894 // Note: C++03 was more strict here, because it banned the use of
1895 // the "template" keyword prior to a template-name that was not a
1896 // dependent name. C++ DR468 relaxed this requirement (the
1897 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00001898 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001899 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001900 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1901 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001902 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001903 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1904 isa<CXXRecordDecl>(LookupCtx) &&
1905 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00001906 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001907 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001908 Diag(Name.getSourceRange().getBegin(),
1909 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001910 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001911 << Name.getSourceRange()
1912 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001913 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001914 } else {
1915 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001916 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001917 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001918 }
1919
Mike Stump1eb44332009-09-09 15:08:12 +00001920 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001921 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001922
1923 switch (Name.getKind()) {
1924 case UnqualifiedId::IK_Identifier:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001925 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1926 Name.Identifier));
1927 return TNK_Dependent_template_name;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001928
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001929 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001930 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001931 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00001932 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00001933
1934 case UnqualifiedId::IK_LiteralOperatorId:
1935 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1936
Douglas Gregor014e88d2009-11-03 23:16:33 +00001937 default:
1938 break;
1939 }
1940
1941 Diag(Name.getSourceRange().getBegin(),
1942 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001943 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001944 << Name.getSourceRange()
1945 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001946 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001947}
1948
Mike Stump1eb44332009-09-09 15:08:12 +00001949bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001950 const TemplateArgumentLoc &AL,
Douglas Gregor910f8002010-11-07 23:05:16 +00001951 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001952 const TemplateArgument &Arg = AL.getArgument();
1953
Anders Carlsson436b1562009-06-13 00:33:33 +00001954 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001955 switch(Arg.getKind()) {
1956 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001957 // C++ [temp.arg.type]p1:
1958 // A template-argument for a template-parameter which is a
1959 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001960 break;
1961 case TemplateArgument::Template: {
1962 // We have a template type parameter but the template argument
1963 // is a template without any arguments.
1964 SourceRange SR = AL.getSourceRange();
1965 TemplateName Name = Arg.getAsTemplate();
1966 Diag(SR.getBegin(), diag::err_template_missing_args)
1967 << Name << SR;
1968 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1969 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001970
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001971 return true;
1972 }
1973 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001974 // We have a template type parameter but the template argument
1975 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001976 SourceRange SR = AL.getSourceRange();
1977 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001978 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Anders Carlsson436b1562009-06-13 00:33:33 +00001980 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001981 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001982 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001983
John McCalla93c9342009-12-07 02:54:59 +00001984 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001985 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Anders Carlsson436b1562009-06-13 00:33:33 +00001987 // Add the converted template type argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001988 Converted.push_back(
John McCall833ca992009-10-29 08:12:44 +00001989 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001990 return false;
1991}
1992
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001993/// \brief Substitute template arguments into the default template argument for
1994/// the given template type parameter.
1995///
1996/// \param SemaRef the semantic analysis object for which we are performing
1997/// the substitution.
1998///
1999/// \param Template the template that we are synthesizing template arguments
2000/// for.
2001///
2002/// \param TemplateLoc the location of the template name that started the
2003/// template-id we are checking.
2004///
2005/// \param RAngleLoc the location of the right angle bracket ('>') that
2006/// terminates the template-id.
2007///
2008/// \param Param the template template parameter whose default we are
2009/// substituting into.
2010///
2011/// \param Converted the list of template arguments provided for template
2012/// parameters that precede \p Param in the template parameter list.
2013///
2014/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00002015static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002016SubstDefaultTemplateArgument(Sema &SemaRef,
2017 TemplateDecl *Template,
2018 SourceLocation TemplateLoc,
2019 SourceLocation RAngleLoc,
2020 TemplateTypeParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002021 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00002022 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002023
2024 // If the argument type is dependent, instantiate it now based
2025 // on the previously-computed template arguments.
2026 if (ArgType->getType()->isDependentType()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002027 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2028 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002029
2030 MultiLevelTemplateArgumentList AllTemplateArgs
2031 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2032
2033 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002034 Template, Converted.data(),
2035 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002036 SourceRange(TemplateLoc, RAngleLoc));
2037
2038 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2039 Param->getDefaultArgumentLoc(),
2040 Param->getDeclName());
2041 }
2042
2043 return ArgType;
2044}
2045
2046/// \brief Substitute template arguments into the default template argument for
2047/// the given non-type template parameter.
2048///
2049/// \param SemaRef the semantic analysis object for which we are performing
2050/// the substitution.
2051///
2052/// \param Template the template that we are synthesizing template arguments
2053/// for.
2054///
2055/// \param TemplateLoc the location of the template name that started the
2056/// template-id we are checking.
2057///
2058/// \param RAngleLoc the location of the right angle bracket ('>') that
2059/// terminates the template-id.
2060///
Douglas Gregor788cd062009-11-11 01:00:40 +00002061/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002062/// substituting into.
2063///
2064/// \param Converted the list of template arguments provided for template
2065/// parameters that precede \p Param in the template parameter list.
2066///
2067/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00002068static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002069SubstDefaultTemplateArgument(Sema &SemaRef,
2070 TemplateDecl *Template,
2071 SourceLocation TemplateLoc,
2072 SourceLocation RAngleLoc,
2073 NonTypeTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002074 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2075 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2076 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002077
2078 MultiLevelTemplateArgumentList AllTemplateArgs
2079 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2080
2081 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002082 Template, Converted.data(),
2083 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002084 SourceRange(TemplateLoc, RAngleLoc));
2085
2086 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2087}
2088
Douglas Gregor788cd062009-11-11 01:00:40 +00002089/// \brief Substitute template arguments into the default template argument for
2090/// the given template template parameter.
2091///
2092/// \param SemaRef the semantic analysis object for which we are performing
2093/// the substitution.
2094///
2095/// \param Template the template that we are synthesizing template arguments
2096/// for.
2097///
2098/// \param TemplateLoc the location of the template name that started the
2099/// template-id we are checking.
2100///
2101/// \param RAngleLoc the location of the right angle bracket ('>') that
2102/// terminates the template-id.
2103///
2104/// \param Param the template template parameter whose default we are
2105/// substituting into.
2106///
2107/// \param Converted the list of template arguments provided for template
2108/// parameters that precede \p Param in the template parameter list.
2109///
2110/// \returns the substituted template argument, or NULL if an error occurred.
2111static TemplateName
2112SubstDefaultTemplateArgument(Sema &SemaRef,
2113 TemplateDecl *Template,
2114 SourceLocation TemplateLoc,
2115 SourceLocation RAngleLoc,
2116 TemplateTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002117 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2118 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2119 Converted.data(), Converted.size());
Douglas Gregor788cd062009-11-11 01:00:40 +00002120
2121 MultiLevelTemplateArgumentList AllTemplateArgs
2122 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2123
2124 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002125 Template, Converted.data(),
2126 Converted.size(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002127 SourceRange(TemplateLoc, RAngleLoc));
2128
2129 return SemaRef.SubstTemplateName(
2130 Param->getDefaultArgument().getArgument().getAsTemplate(),
2131 Param->getDefaultArgument().getTemplateNameLoc(),
2132 AllTemplateArgs);
2133}
2134
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002135/// \brief If the given template parameter has a default template
2136/// argument, substitute into that default template argument and
2137/// return the corresponding template argument.
2138TemplateArgumentLoc
2139Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2140 SourceLocation TemplateLoc,
2141 SourceLocation RAngleLoc,
2142 Decl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002143 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2144 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002145 if (!TypeParm->hasDefaultArgument())
2146 return TemplateArgumentLoc();
2147
John McCalla93c9342009-12-07 02:54:59 +00002148 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002149 TemplateLoc,
2150 RAngleLoc,
2151 TypeParm,
2152 Converted);
2153 if (DI)
2154 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2155
2156 return TemplateArgumentLoc();
2157 }
2158
2159 if (NonTypeTemplateParmDecl *NonTypeParm
2160 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2161 if (!NonTypeParm->hasDefaultArgument())
2162 return TemplateArgumentLoc();
2163
John McCall60d7b3a2010-08-24 06:29:42 +00002164 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002165 TemplateLoc,
2166 RAngleLoc,
2167 NonTypeParm,
2168 Converted);
2169 if (Arg.isInvalid())
2170 return TemplateArgumentLoc();
2171
2172 Expr *ArgE = Arg.takeAs<Expr>();
2173 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2174 }
2175
2176 TemplateTemplateParmDecl *TempTempParm
2177 = cast<TemplateTemplateParmDecl>(Param);
2178 if (!TempTempParm->hasDefaultArgument())
2179 return TemplateArgumentLoc();
2180
2181 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2182 TemplateLoc,
2183 RAngleLoc,
2184 TempTempParm,
2185 Converted);
2186 if (TName.isNull())
2187 return TemplateArgumentLoc();
2188
2189 return TemplateArgumentLoc(TemplateArgument(TName),
2190 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2191 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2192}
2193
Douglas Gregore7526412009-11-11 19:31:23 +00002194/// \brief Check that the given template argument corresponds to the given
2195/// template parameter.
2196bool Sema::CheckTemplateArgument(NamedDecl *Param,
2197 const TemplateArgumentLoc &Arg,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002198 NamedDecl *Template,
Douglas Gregore7526412009-11-11 19:31:23 +00002199 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002200 SourceLocation RAngleLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002201 llvm::SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor02024a92010-03-28 02:42:43 +00002202 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002203 // Check template type parameters.
2204 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002205 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002206
Douglas Gregord9e15302009-11-11 19:41:09 +00002207 // Check non-type template parameters.
2208 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002209 // Do substitution on the type of the non-type template parameter
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002210 // with the template arguments we've seen thus far. But if the
2211 // template has a dependent context then we cannot substitute yet.
Douglas Gregore7526412009-11-11 19:31:23 +00002212 QualType NTTPType = NTTP->getType();
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002213 if (NTTPType->isDependentType() &&
2214 !isa<TemplateTemplateParmDecl>(Template) &&
2215 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002216 // Do substitution on the type of the non-type template parameter.
2217 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002218 NTTP, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002219 SourceRange(TemplateLoc, RAngleLoc));
2220
Douglas Gregor910f8002010-11-07 23:05:16 +00002221 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2222 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002223 NTTPType = SubstType(NTTPType,
2224 MultiLevelTemplateArgumentList(TemplateArgs),
2225 NTTP->getLocation(),
2226 NTTP->getDeclName());
2227 // If that worked, check the non-type template parameter type
2228 // for validity.
2229 if (!NTTPType.isNull())
2230 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2231 NTTP->getLocation());
2232 if (NTTPType.isNull())
2233 return true;
2234 }
2235
2236 switch (Arg.getArgument().getKind()) {
2237 case TemplateArgument::Null:
2238 assert(false && "Should never see a NULL template argument here");
2239 return true;
2240
2241 case TemplateArgument::Expression: {
2242 Expr *E = Arg.getArgument().getAsExpr();
2243 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002244 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002245 return true;
2246
Douglas Gregor910f8002010-11-07 23:05:16 +00002247 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002248 break;
2249 }
2250
2251 case TemplateArgument::Declaration:
2252 case TemplateArgument::Integral:
2253 // We've already checked this template argument, so just copy
2254 // it to the list of converted arguments.
Douglas Gregor910f8002010-11-07 23:05:16 +00002255 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002256 break;
2257
2258 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00002259 case TemplateArgument::TemplateExpansion:
Douglas Gregore7526412009-11-11 19:31:23 +00002260 // We were given a template template argument. It may not be ill-formed;
2261 // see below.
2262 if (DependentTemplateName *DTN
Douglas Gregora7fc9012011-01-05 18:58:31 +00002263 = Arg.getArgument().getAsTemplateOrTemplatePattern()
2264 .getAsDependentTemplateName()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002265 // We have a template argument such as \c T::template X, which we
2266 // parsed as a template template argument. However, since we now
2267 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002268 // template name into an expression.
2269
2270 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2271 Arg.getTemplateNameLoc());
2272
John McCallf7a1a742009-11-24 19:00:30 +00002273 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2274 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002275 Arg.getTemplateQualifierRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002276 NameInfo);
Douglas Gregore7526412009-11-11 19:31:23 +00002277
Douglas Gregora7fc9012011-01-05 18:58:31 +00002278 // If we parsed the template argument as a pack expansion, create a
2279 // pack expansion expression.
2280 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
2281 ExprResult Expansion = ActOnPackExpansion(E,
2282 Arg.getTemplateEllipsisLoc());
2283 if (Expansion.isInvalid())
2284 return true;
2285
2286 E = Expansion.get();
2287 }
2288
Douglas Gregore7526412009-11-11 19:31:23 +00002289 TemplateArgument Result;
2290 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2291 return true;
2292
Douglas Gregor910f8002010-11-07 23:05:16 +00002293 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002294 break;
2295 }
2296
2297 // We have a template argument that actually does refer to a class
2298 // template, template alias, or template template parameter, and
2299 // therefore cannot be a non-type template argument.
2300 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2301 << Arg.getSourceRange();
2302
2303 Diag(Param->getLocation(), diag::note_template_param_here);
2304 return true;
2305
2306 case TemplateArgument::Type: {
2307 // We have a non-type template parameter but the template
2308 // argument is a type.
2309
2310 // C++ [temp.arg]p2:
2311 // In a template-argument, an ambiguity between a type-id and
2312 // an expression is resolved to a type-id, regardless of the
2313 // form of the corresponding template-parameter.
2314 //
2315 // We warn specifically about this case, since it can be rather
2316 // confusing for users.
2317 QualType T = Arg.getArgument().getAsType();
2318 SourceRange SR = Arg.getSourceRange();
2319 if (T->isFunctionType())
2320 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2321 else
2322 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2323 Diag(Param->getLocation(), diag::note_template_param_here);
2324 return true;
2325 }
2326
2327 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002328 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002329 break;
2330 }
2331
2332 return false;
2333 }
2334
2335
2336 // Check template template parameters.
2337 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2338
2339 // Substitute into the template parameter list of the template
2340 // template parameter, since previously-supplied template arguments
2341 // may appear within the template template parameter.
2342 {
2343 // Set up a template instantiation context.
2344 LocalInstantiationScope Scope(*this);
2345 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002346 TempParm, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002347 SourceRange(TemplateLoc, RAngleLoc));
2348
Douglas Gregor910f8002010-11-07 23:05:16 +00002349 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2350 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002351 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2352 SubstDecl(TempParm, CurContext,
2353 MultiLevelTemplateArgumentList(TemplateArgs)));
2354 if (!TempParm)
2355 return true;
Douglas Gregore7526412009-11-11 19:31:23 +00002356 }
2357
2358 switch (Arg.getArgument().getKind()) {
2359 case TemplateArgument::Null:
2360 assert(false && "Should never see a NULL template argument here");
2361 return true;
2362
2363 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00002364 case TemplateArgument::TemplateExpansion:
Douglas Gregore7526412009-11-11 19:31:23 +00002365 if (CheckTemplateArgument(TempParm, Arg))
2366 return true;
2367
Douglas Gregor910f8002010-11-07 23:05:16 +00002368 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002369 break;
2370
2371 case TemplateArgument::Expression:
2372 case TemplateArgument::Type:
2373 // We have a template template parameter but the template
2374 // argument does not refer to a template.
2375 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2376 return true;
2377
2378 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002379 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002380 "Declaration argument with template template parameter");
2381 break;
2382 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002383 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002384 "Integral argument with template template parameter");
2385 break;
2386
2387 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002388 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002389 break;
2390 }
2391
2392 return false;
2393}
2394
Douglas Gregorc15cb382009-02-09 23:23:08 +00002395/// \brief Check that the given template argument list is well-formed
2396/// for specializing the given template.
2397bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2398 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002399 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002400 bool PartialTemplateArgs,
Douglas Gregor910f8002010-11-07 23:05:16 +00002401 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002402 TemplateParameterList *Params = Template->getTemplateParameters();
2403 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002404 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002405 bool Invalid = false;
2406
John McCalld5532b62009-11-23 01:53:49 +00002407 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2408
Mike Stump1eb44332009-09-09 15:08:12 +00002409 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002410 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002411
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002412 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002413 (NumArgs < Params->getMinRequiredArguments() &&
2414 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002415 // FIXME: point at either the first arg beyond what we can handle,
2416 // or the '>', depending on whether we have too many or too few
2417 // arguments.
2418 SourceRange Range;
2419 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002420 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002421 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2422 << (NumArgs > NumParams)
2423 << (isa<ClassTemplateDecl>(Template)? 0 :
2424 isa<FunctionTemplateDecl>(Template)? 1 :
2425 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2426 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002427 Diag(Template->getLocation(), diag::note_template_decl_here)
2428 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002429 Invalid = true;
2430 }
Mike Stump1eb44332009-09-09 15:08:12 +00002431
2432 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002433 // [...] The type and form of each template-argument specified in
2434 // a template-id shall match the type and form specified for the
2435 // corresponding parameter declared by the template in its
2436 // template-parameter-list.
Douglas Gregor14be16b2010-12-20 16:57:52 +00002437 llvm::SmallVector<TemplateArgument, 2> ArgumentPack;
2438 TemplateParameterList::iterator Param = Params->begin(),
2439 ParamEnd = Params->end();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002440 unsigned ArgIdx = 0;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002441 while (Param != ParamEnd) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002442 if (ArgIdx > NumArgs && PartialTemplateArgs)
2443 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002444
Douglas Gregorf35f8282009-11-11 21:54:23 +00002445 if (ArgIdx < NumArgs) {
2446 // Check the template argument we were given.
2447 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2448 TemplateLoc, RAngleLoc, Converted))
2449 return true;
2450
Douglas Gregor14be16b2010-12-20 16:57:52 +00002451 if ((*Param)->isTemplateParameterPack()) {
2452 // The template parameter was a template parameter pack, so take the
2453 // deduced argument and place it on the argument pack. Note that we
2454 // stay on the same template parameter so that we can deduce more
2455 // arguments.
2456 ArgumentPack.push_back(Converted.back());
2457 Converted.pop_back();
2458 } else {
2459 // Move to the next template parameter.
2460 ++Param;
2461 }
2462 ++ArgIdx;
Douglas Gregorf35f8282009-11-11 21:54:23 +00002463 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002464 }
Douglas Gregore7526412009-11-11 19:31:23 +00002465
Douglas Gregor14be16b2010-12-20 16:57:52 +00002466 // If we have a template parameter pack with no more corresponding
2467 // arguments, just break out now and we'll fill in the argument pack below.
2468 if ((*Param)->isTemplateParameterPack())
2469 break;
2470
Douglas Gregorf35f8282009-11-11 21:54:23 +00002471 // We have a default template argument that we will use.
2472 TemplateArgumentLoc Arg;
2473
2474 // Retrieve the default template argument from the template
2475 // parameter. For each kind of template parameter, we substitute the
2476 // template arguments provided thus far and any "outer" template arguments
2477 // (when the template parameter was part of a nested template) into
2478 // the default argument.
2479 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2480 if (!TTP->hasDefaultArgument()) {
2481 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2482 break;
2483 }
2484
John McCalla93c9342009-12-07 02:54:59 +00002485 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002486 Template,
2487 TemplateLoc,
2488 RAngleLoc,
2489 TTP,
2490 Converted);
2491 if (!ArgType)
2492 return true;
2493
2494 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2495 ArgType);
2496 } else if (NonTypeTemplateParmDecl *NTTP
2497 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2498 if (!NTTP->hasDefaultArgument()) {
2499 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2500 break;
2501 }
2502
John McCall60d7b3a2010-08-24 06:29:42 +00002503 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002504 TemplateLoc,
2505 RAngleLoc,
2506 NTTP,
2507 Converted);
2508 if (E.isInvalid())
2509 return true;
2510
2511 Expr *Ex = E.takeAs<Expr>();
2512 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2513 } else {
2514 TemplateTemplateParmDecl *TempParm
2515 = cast<TemplateTemplateParmDecl>(*Param);
2516
2517 if (!TempParm->hasDefaultArgument()) {
2518 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2519 break;
2520 }
2521
2522 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2523 TemplateLoc,
2524 RAngleLoc,
2525 TempParm,
2526 Converted);
2527 if (Name.isNull())
2528 return true;
2529
2530 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2531 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2532 TempParm->getDefaultArgument().getTemplateNameLoc());
2533 }
2534
2535 // Introduce an instantiation record that describes where we are using
2536 // the default template argument.
2537 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002538 Converted.data(), Converted.size(),
Douglas Gregorf35f8282009-11-11 21:54:23 +00002539 SourceRange(TemplateLoc, RAngleLoc));
2540
2541 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002542 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002543 RAngleLoc, Converted))
2544 return true;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002545
2546 // Move to the next template parameter and argument.
2547 ++Param;
2548 ++ArgIdx;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002549 }
Douglas Gregor14be16b2010-12-20 16:57:52 +00002550
2551 // Form argument packs for each of the parameter packs remaining.
2552 while (Param != ParamEnd) {
Douglas Gregord3731192011-01-10 07:32:04 +00002553 // If we're checking a partial list of template arguments, don't fill
2554 // in arguments for non-template parameter packs.
2555
Douglas Gregor14be16b2010-12-20 16:57:52 +00002556 if ((*Param)->isTemplateParameterPack()) {
Douglas Gregord3731192011-01-10 07:32:04 +00002557 if (PartialTemplateArgs && ArgumentPack.empty()) {
2558 Converted.push_back(TemplateArgument());
Douglas Gregor203e6a32011-01-11 23:09:57 +00002559 } else if (ArgumentPack.empty())
Douglas Gregor14be16b2010-12-20 16:57:52 +00002560 Converted.push_back(TemplateArgument(0, 0));
Douglas Gregor203e6a32011-01-11 23:09:57 +00002561 else {
2562 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
2563 ArgumentPack.data(),
2564 ArgumentPack.size()));
Douglas Gregor14be16b2010-12-20 16:57:52 +00002565 ArgumentPack.clear();
2566 }
2567 }
2568
2569 ++Param;
2570 }
2571
Douglas Gregorc15cb382009-02-09 23:23:08 +00002572 return Invalid;
2573}
2574
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002575namespace {
2576 class UnnamedLocalNoLinkageFinder
2577 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2578 {
2579 Sema &S;
2580 SourceRange SR;
2581
2582 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2583
2584 public:
2585 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2586
2587 bool Visit(QualType T) {
2588 return inherited::Visit(T.getTypePtr());
2589 }
2590
2591#define TYPE(Class, Parent) \
2592 bool Visit##Class##Type(const Class##Type *);
2593#define ABSTRACT_TYPE(Class, Parent) \
2594 bool Visit##Class##Type(const Class##Type *) { return false; }
2595#define NON_CANONICAL_TYPE(Class, Parent) \
2596 bool Visit##Class##Type(const Class##Type *) { return false; }
2597#include "clang/AST/TypeNodes.def"
2598
2599 bool VisitTagDecl(const TagDecl *Tag);
2600 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2601 };
2602}
2603
2604bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2605 return false;
2606}
2607
2608bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2609 return Visit(T->getElementType());
2610}
2611
2612bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2613 return Visit(T->getPointeeType());
2614}
2615
2616bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2617 const BlockPointerType* T) {
2618 return Visit(T->getPointeeType());
2619}
2620
2621bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2622 const LValueReferenceType* T) {
2623 return Visit(T->getPointeeType());
2624}
2625
2626bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2627 const RValueReferenceType* T) {
2628 return Visit(T->getPointeeType());
2629}
2630
2631bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2632 const MemberPointerType* T) {
2633 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2634}
2635
2636bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2637 const ConstantArrayType* T) {
2638 return Visit(T->getElementType());
2639}
2640
2641bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2642 const IncompleteArrayType* T) {
2643 return Visit(T->getElementType());
2644}
2645
2646bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2647 const VariableArrayType* T) {
2648 return Visit(T->getElementType());
2649}
2650
2651bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2652 const DependentSizedArrayType* T) {
2653 return Visit(T->getElementType());
2654}
2655
2656bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2657 const DependentSizedExtVectorType* T) {
2658 return Visit(T->getElementType());
2659}
2660
2661bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2662 return Visit(T->getElementType());
2663}
2664
2665bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2666 return Visit(T->getElementType());
2667}
2668
2669bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2670 const FunctionProtoType* T) {
2671 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2672 AEnd = T->arg_type_end();
2673 A != AEnd; ++A) {
2674 if (Visit(*A))
2675 return true;
2676 }
2677
2678 return Visit(T->getResultType());
2679}
2680
2681bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2682 const FunctionNoProtoType* T) {
2683 return Visit(T->getResultType());
2684}
2685
2686bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2687 const UnresolvedUsingType*) {
2688 return false;
2689}
2690
2691bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2692 return false;
2693}
2694
2695bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2696 return Visit(T->getUnderlyingType());
2697}
2698
2699bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2700 return false;
2701}
2702
2703bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2704 return VisitTagDecl(T->getDecl());
2705}
2706
2707bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2708 return VisitTagDecl(T->getDecl());
2709}
2710
2711bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2712 const TemplateTypeParmType*) {
2713 return false;
2714}
2715
2716bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2717 const TemplateSpecializationType*) {
2718 return false;
2719}
2720
2721bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2722 const InjectedClassNameType* T) {
2723 return VisitTagDecl(T->getDecl());
2724}
2725
2726bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2727 const DependentNameType* T) {
2728 return VisitNestedNameSpecifier(T->getQualifier());
2729}
2730
2731bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2732 const DependentTemplateSpecializationType* T) {
2733 return VisitNestedNameSpecifier(T->getQualifier());
2734}
2735
Douglas Gregor7536dd52010-12-20 02:24:11 +00002736bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
2737 const PackExpansionType* T) {
2738 return Visit(T->getPattern());
2739}
2740
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002741bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2742 return false;
2743}
2744
2745bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2746 const ObjCInterfaceType *) {
2747 return false;
2748}
2749
2750bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2751 const ObjCObjectPointerType *) {
2752 return false;
2753}
2754
2755bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2756 if (Tag->getDeclContext()->isFunctionOrMethod()) {
2757 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2758 << S.Context.getTypeDeclType(Tag) << SR;
2759 return true;
2760 }
2761
2762 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2763 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2764 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2765 return true;
2766 }
2767
2768 return false;
2769}
2770
2771bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2772 NestedNameSpecifier *NNS) {
2773 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2774 return true;
2775
2776 switch (NNS->getKind()) {
2777 case NestedNameSpecifier::Identifier:
2778 case NestedNameSpecifier::Namespace:
2779 case NestedNameSpecifier::Global:
2780 return false;
2781
2782 case NestedNameSpecifier::TypeSpec:
2783 case NestedNameSpecifier::TypeSpecWithTemplate:
2784 return Visit(QualType(NNS->getAsType(), 0));
2785 }
Fariborz Jahanian7b1ec6c2010-10-13 16:19:16 +00002786 return false;
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002787}
2788
2789
Douglas Gregorc15cb382009-02-09 23:23:08 +00002790/// \brief Check a template argument against its corresponding
2791/// template type parameter.
2792///
2793/// This routine implements the semantics of C++ [temp.arg.type]. It
2794/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002795bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002796 TypeSourceInfo *ArgInfo) {
2797 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002798 QualType Arg = ArgInfo->getType();
Douglas Gregor0fddb972010-05-22 16:17:30 +00002799 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth17fb8552010-09-03 21:12:34 +00002800
2801 if (Arg->isVariablyModifiedType()) {
2802 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002803 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00002804 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002805 }
2806
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002807 // C++03 [temp.arg.type]p2:
2808 // A local type, a type with no linkage, an unnamed type or a type
2809 // compounded from any of these types shall not be used as a
2810 // template-argument for a template type-parameter.
2811 //
2812 // C++0x allows these, and even in C++03 we allow them as an extension with
2813 // a warning.
Douglas Gregordb4d4bb2010-10-13 18:05:20 +00002814 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002815 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2816 (void)Finder.Visit(Context.getCanonicalType(Arg));
2817 }
2818
Douglas Gregorc15cb382009-02-09 23:23:08 +00002819 return false;
2820}
2821
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002822/// \brief Checks whether the given template argument is the address
2823/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002824static bool
2825CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2826 NonTypeTemplateParmDecl *Param,
2827 QualType ParamType,
2828 Expr *ArgIn,
2829 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002830 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002831 Expr *Arg = ArgIn;
2832 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002833
2834 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002835 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002836 Arg = Cast->getSubExpr();
2837
2838 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002839 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002840 // A template-argument for a non-type, non-template
2841 // template-parameter shall be one of: [...]
2842 //
2843 // -- the address of an object or function with external
2844 // linkage, including function templates and function
2845 // template-ids but excluding non-static class members,
2846 // expressed as & id-expression where the & is optional if
2847 // the name refers to a function or array, or if the
2848 // corresponding template-parameter is a reference; or
2849 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002851 // In C++98/03 mode, give an extension warning on any extra parentheses.
2852 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2853 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002854 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002855 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002856 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002857 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002858 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002859 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002860 }
2861
2862 Arg = Parens->getSubExpr();
2863 }
2864
Douglas Gregorb7a09262010-04-01 18:32:35 +00002865 bool AddressTaken = false;
2866 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002867 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002868 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002869 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002870 AddressTaken = true;
2871 AddrOpLoc = UnOp->getOperatorLoc();
2872 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002873 } else
2874 DRE = dyn_cast<DeclRefExpr>(Arg);
2875
Douglas Gregorb7a09262010-04-01 18:32:35 +00002876 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002877 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2878 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002879 S.Diag(Param->getLocation(), diag::note_template_param_here);
2880 return true;
2881 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002882
2883 // Stop checking the precise nature of the argument if it is value dependent,
2884 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002885 if (Arg->isValueDependent()) {
John McCall3fa5cae2010-10-26 07:05:15 +00002886 Converted = TemplateArgument(ArgIn);
Chandler Carruth038cc392010-01-31 10:01:20 +00002887 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002888 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002889
Douglas Gregorb7a09262010-04-01 18:32:35 +00002890 if (!isa<ValueDecl>(DRE->getDecl())) {
2891 S.Diag(Arg->getSourceRange().getBegin(),
2892 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002893 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002894 S.Diag(Param->getLocation(), diag::note_template_param_here);
2895 return true;
2896 }
2897
2898 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002899
2900 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002901 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2902 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002903 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002904 S.Diag(Param->getLocation(), diag::note_template_param_here);
2905 return true;
2906 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002907
2908 // Cannot refer to non-static member functions
2909 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002910 if (!Method->isStatic()) {
2911 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002912 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002913 S.Diag(Param->getLocation(), diag::note_template_param_here);
2914 return true;
2915 }
Mike Stump1eb44332009-09-09 15:08:12 +00002916
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002917 // Functions must have external linkage.
2918 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002919 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002920 S.Diag(Arg->getSourceRange().getBegin(),
2921 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002922 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002923 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002924 << true;
2925 return true;
2926 }
2927
2928 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002929 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002930
Douglas Gregorb7a09262010-04-01 18:32:35 +00002931 // If the template parameter has pointer type, the function decays.
2932 if (ParamType->isPointerType() && !AddressTaken)
2933 ArgType = S.Context.getPointerType(Func->getType());
2934 else if (AddressTaken && ParamType->isReferenceType()) {
2935 // If we originally had an address-of operator, but the
2936 // parameter has reference type, complain and (if things look
2937 // like they will work) drop the address-of operator.
2938 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2939 ParamType.getNonReferenceType())) {
2940 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2941 << ParamType;
2942 S.Diag(Param->getLocation(), diag::note_template_param_here);
2943 return true;
2944 }
2945
2946 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2947 << ParamType
2948 << FixItHint::CreateRemoval(AddrOpLoc);
2949 S.Diag(Param->getLocation(), diag::note_template_param_here);
2950
2951 ArgType = Func->getType();
2952 }
2953 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002954 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002955 S.Diag(Arg->getSourceRange().getBegin(),
2956 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002957 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002958 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002959 << true;
2960 return true;
2961 }
2962
Douglas Gregorb7a09262010-04-01 18:32:35 +00002963 // A value of reference type is not an object.
2964 if (Var->getType()->isReferenceType()) {
2965 S.Diag(Arg->getSourceRange().getBegin(),
2966 diag::err_template_arg_reference_var)
2967 << Var->getType() << Arg->getSourceRange();
2968 S.Diag(Param->getLocation(), diag::note_template_param_here);
2969 return true;
2970 }
2971
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002972 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002973 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002974
2975 // If the template parameter has pointer type, we must have taken
2976 // the address of this object.
2977 if (ParamType->isReferenceType()) {
2978 if (AddressTaken) {
2979 // If we originally had an address-of operator, but the
2980 // parameter has reference type, complain and (if things look
2981 // like they will work) drop the address-of operator.
2982 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2983 ParamType.getNonReferenceType())) {
2984 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2985 << ParamType;
2986 S.Diag(Param->getLocation(), diag::note_template_param_here);
2987 return true;
2988 }
2989
2990 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2991 << ParamType
2992 << FixItHint::CreateRemoval(AddrOpLoc);
2993 S.Diag(Param->getLocation(), diag::note_template_param_here);
2994
2995 ArgType = Var->getType();
2996 }
2997 } else if (!AddressTaken && ParamType->isPointerType()) {
2998 if (Var->getType()->isArrayType()) {
2999 // Array-to-pointer decay.
3000 ArgType = S.Context.getArrayDecayedType(Var->getType());
3001 } else {
3002 // If the template parameter has pointer type but the address of
3003 // this object was not taken, complain and (possibly) recover by
3004 // taking the address of the entity.
3005 ArgType = S.Context.getPointerType(Var->getType());
3006 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
3007 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3008 << ParamType;
3009 S.Diag(Param->getLocation(), diag::note_template_param_here);
3010 return true;
3011 }
3012
3013 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3014 << ParamType
3015 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
3016
3017 S.Diag(Param->getLocation(), diag::note_template_param_here);
3018 }
3019 }
3020 } else {
3021 // We found something else, but we don't know specifically what it is.
3022 S.Diag(Arg->getSourceRange().getBegin(),
3023 diag::err_template_arg_not_object_or_func)
3024 << Arg->getSourceRange();
3025 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
3026 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003027 }
Mike Stump1eb44332009-09-09 15:08:12 +00003028
Douglas Gregorb7a09262010-04-01 18:32:35 +00003029 if (ParamType->isPointerType() &&
3030 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
3031 S.IsQualificationConversion(ArgType, ParamType)) {
3032 // For pointer-to-object types, qualification conversions are
3033 // permitted.
3034 } else {
3035 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
3036 if (!ParamRef->getPointeeType()->isFunctionType()) {
3037 // C++ [temp.arg.nontype]p5b3:
3038 // For a non-type template-parameter of type reference to
3039 // object, no conversions apply. The type referred to by the
3040 // reference may be more cv-qualified than the (otherwise
3041 // identical) type of the template- argument. The
3042 // template-parameter is bound directly to the
3043 // template-argument, which shall be an lvalue.
3044
3045 // FIXME: Other qualifiers?
3046 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
3047 unsigned ArgQuals = ArgType.getCVRQualifiers();
3048
3049 if ((ParamQuals | ArgQuals) != ParamQuals) {
3050 S.Diag(Arg->getSourceRange().getBegin(),
3051 diag::err_template_arg_ref_bind_ignores_quals)
3052 << ParamType << Arg->getType()
3053 << Arg->getSourceRange();
3054 S.Diag(Param->getLocation(), diag::note_template_param_here);
3055 return true;
3056 }
3057 }
3058 }
3059
3060 // At this point, the template argument refers to an object or
3061 // function with external linkage. We now need to check whether the
3062 // argument and parameter types are compatible.
3063 if (!S.Context.hasSameUnqualifiedType(ArgType,
3064 ParamType.getNonReferenceType())) {
3065 // We can't perform this conversion or binding.
3066 if (ParamType->isReferenceType())
3067 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
3068 << ParamType << Arg->getType() << Arg->getSourceRange();
3069 else
3070 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
3071 << Arg->getType() << ParamType << Arg->getSourceRange();
3072 S.Diag(Param->getLocation(), diag::note_template_param_here);
3073 return true;
3074 }
3075 }
3076
3077 // Create the template argument.
3078 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00003079 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00003080 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003081}
3082
3083/// \brief Checks whether the given template argument is a pointer to
3084/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003085bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
3086 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003087 bool Invalid = false;
3088
3089 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003090 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003091 Arg = Cast->getSubExpr();
3092
3093 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003094 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003095 // A template-argument for a non-type, non-template
3096 // template-parameter shall be one of: [...]
3097 //
3098 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003099 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003100
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003101 // In C++98/03 mode, give an extension warning on any extra parentheses.
3102 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3103 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003104 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003105 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00003106 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003107 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003108 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003109 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003110 }
3111
3112 Arg = Parens->getSubExpr();
3113 }
3114
Douglas Gregorcaddba02009-11-12 18:38:13 +00003115 // A pointer-to-member constant written &Class::member.
3116 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00003117 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00003118 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3119 if (DRE && !DRE->getQualifier())
3120 DRE = 0;
3121 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00003122 }
3123 // A constant of pointer-to-member type.
3124 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
3125 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
3126 if (VD->getType()->isMemberPointerType()) {
3127 if (isa<NonTypeTemplateParmDecl>(VD) ||
3128 (isa<VarDecl>(VD) &&
3129 Context.getCanonicalType(VD->getType()).isConstQualified())) {
3130 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003131 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003132 else
3133 Converted = TemplateArgument(VD->getCanonicalDecl());
3134 return Invalid;
3135 }
3136 }
3137 }
3138
3139 DRE = 0;
3140 }
3141
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003142 if (!DRE)
3143 return Diag(Arg->getSourceRange().getBegin(),
3144 diag::err_template_arg_not_pointer_to_member_form)
3145 << Arg->getSourceRange();
3146
3147 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3148 assert((isa<FieldDecl>(DRE->getDecl()) ||
3149 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3150 "Only non-static member pointers can make it here");
3151
3152 // Okay: this is the address of a non-static member, and therefore
3153 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003154 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003155 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003156 else
3157 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003158 return Invalid;
3159 }
3160
3161 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00003162 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003163 diag::err_template_arg_not_pointer_to_member_form)
3164 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003165 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003166 diag::note_template_arg_refers_here);
3167 return true;
3168}
3169
Douglas Gregorc15cb382009-02-09 23:23:08 +00003170/// \brief Check a template argument against its corresponding
3171/// non-type template parameter.
3172///
Douglas Gregor2943aed2009-03-03 04:44:36 +00003173/// This routine implements the semantics of C++ [temp.arg.nontype].
3174/// It returns true if an error occurred, and false otherwise. \p
3175/// InstantiatedParamType is the type of the non-type template
3176/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003177///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003178/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00003179bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00003180 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00003181 TemplateArgument &Converted,
3182 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00003183 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3184
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003185 // If either the parameter has a dependent type or the argument is
3186 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00003187 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3188 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003189 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003190 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00003191 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003192
3193 // C++ [temp.arg.nontype]p5:
3194 // The following conversions are performed on each expression used
3195 // as a non-type template-argument. If a non-type
3196 // template-argument cannot be converted to the type of the
3197 // corresponding template-parameter then the program is
3198 // ill-formed.
3199 //
3200 // -- for a non-type template-parameter of integral or
3201 // enumeration type, integral promotions (4.5) and integral
3202 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00003203 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00003204 QualType ArgType = Arg->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003205 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003206 // C++ [temp.arg.nontype]p1:
3207 // A template-argument for a non-type, non-template
3208 // template-parameter shall be one of:
3209 //
3210 // -- an integral constant-expression of integral or enumeration
3211 // type; or
3212 // -- the name of a non-type template-parameter; or
3213 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003214 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003215 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003216 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003217 diag::err_template_arg_not_integral_or_enumeral)
3218 << ArgType << Arg->getSourceRange();
3219 Diag(Param->getLocation(), diag::note_template_param_here);
3220 return true;
3221 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003222 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003223 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3224 << ArgType << Arg->getSourceRange();
3225 return true;
3226 }
3227
Douglas Gregor02024a92010-03-28 02:42:43 +00003228 // From here on out, all we care about are the unqualified forms
3229 // of the parameter and argument types.
3230 ParamType = ParamType.getUnqualifiedType();
3231 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003232
3233 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00003234 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003235 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00003236 } else if (CTAK == CTAK_Deduced) {
3237 // C++ [temp.deduct.type]p17:
3238 // If, in the declaration of a function template with a non-type
3239 // template-parameter, the non-type template- parameter is used
3240 // in an expression in the function parameter-list and, if the
3241 // corresponding template-argument is deduced, the
3242 // template-argument type shall match the type of the
3243 // template-parameter exactly, except that a template-argument
3244 // deduced from an array bound may be of any integral type.
3245 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3246 << ArgType << ParamType;
3247 Diag(Param->getLocation(), diag::note_template_param_here);
John McCalldaa8e4e2010-11-15 09:13:47 +00003248 return true;
3249 } else if (ParamType->isBooleanType()) {
3250 // This is an integral-to-boolean conversion.
3251 ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003252 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3253 !ParamType->isEnumeralType()) {
3254 // This is an integral promotion or conversion.
John McCall2de56d12010-08-25 11:45:40 +00003255 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003256 } else {
3257 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003258 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003259 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003260 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003261 Diag(Param->getLocation(), diag::note_template_param_here);
3262 return true;
3263 }
3264
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003265 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00003266 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003267 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003268
3269 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003270 llvm::APSInt OldValue = Value;
3271
3272 // Coerce the template argument's value to the value it will have
3273 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003274 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003275 if (Value.getBitWidth() != AllowedBits)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003276 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003277 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003278
3279 // Complain if an unsigned parameter received a negative value.
3280 if (IntegerType->isUnsignedIntegerType()
3281 && (OldValue.isSigned() && OldValue.isNegative())) {
3282 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3283 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3284 << Arg->getSourceRange();
3285 Diag(Param->getLocation(), diag::note_template_param_here);
3286 }
3287
3288 // Complain if we overflowed the template parameter's type.
3289 unsigned RequiredBits;
3290 if (IntegerType->isUnsignedIntegerType())
3291 RequiredBits = OldValue.getActiveBits();
3292 else if (OldValue.isUnsigned())
3293 RequiredBits = OldValue.getActiveBits() + 1;
3294 else
3295 RequiredBits = OldValue.getMinSignedBits();
3296 if (RequiredBits > AllowedBits) {
3297 Diag(Arg->getSourceRange().getBegin(),
3298 diag::warn_template_arg_too_large)
3299 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3300 << Arg->getSourceRange();
3301 Diag(Param->getLocation(), diag::note_template_param_here);
3302 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003303 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003304
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003305 // Add the value of this argument to the list of converted
3306 // arguments. We use the bitwidth and signedness of the template
3307 // parameter.
3308 if (Arg->isValueDependent()) {
3309 // The argument is value-dependent. Create a new
3310 // TemplateArgument with the converted expression.
3311 Converted = TemplateArgument(Arg);
3312 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003313 }
3314
John McCall833ca992009-10-29 08:12:44 +00003315 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00003316 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003317 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003318 return false;
3319 }
Douglas Gregora35284b2009-02-11 00:19:33 +00003320
John McCall6bb80172010-03-30 21:47:33 +00003321 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3322
Douglas Gregorb7a09262010-04-01 18:32:35 +00003323 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3324 // from a template argument of type std::nullptr_t to a non-type
3325 // template parameter of type pointer to object, pointer to
3326 // function, or pointer-to-member, respectively.
3327 if (ArgType->isNullPtrType() &&
3328 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3329 Converted = TemplateArgument((NamedDecl *)0);
3330 return false;
3331 }
3332
Douglas Gregorb86b0572009-02-11 01:18:59 +00003333 // Handle pointer-to-function, reference-to-function, and
3334 // pointer-to-member-function all in (roughly) the same way.
3335 if (// -- For a non-type template-parameter of type pointer to
3336 // function, only the function-to-pointer conversion (4.3) is
3337 // applied. If the template-argument represents a set of
3338 // overloaded functions (or a pointer to such), the matching
3339 // function is selected from the set (13.4).
3340 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003341 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003342 // -- For a non-type template-parameter of type reference to
3343 // function, no conversions apply. If the template-argument
3344 // represents a set of overloaded functions, the matching
3345 // function is selected from the set (13.4).
3346 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003347 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003348 // -- For a non-type template-parameter of type pointer to
3349 // member function, no conversions apply. If the
3350 // template-argument represents a set of overloaded member
3351 // functions, the matching member function is selected from
3352 // the set (13.4).
3353 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003354 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00003355 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003356
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003357 if (Arg->getType() == Context.OverloadTy) {
3358 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3359 true,
3360 FoundResult)) {
3361 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3362 return true;
3363
3364 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3365 ArgType = Arg->getType();
3366 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003367 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00003368 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003369
Douglas Gregorb7a09262010-04-01 18:32:35 +00003370 if (!ParamType->isMemberPointerType())
3371 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3372 ParamType,
3373 Arg, Converted);
3374
3375 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCall2de56d12010-08-25 11:45:40 +00003376 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb7a09262010-04-01 18:32:35 +00003377 } else if (!Context.hasSameUnqualifiedType(ArgType,
3378 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00003379 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003380 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00003381 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003382 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00003383 Diag(Param->getLocation(), diag::note_template_param_here);
3384 return true;
3385 }
Mike Stump1eb44332009-09-09 15:08:12 +00003386
Douglas Gregorb7a09262010-04-01 18:32:35 +00003387 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00003388 }
3389
Chris Lattnerfe90de72009-02-20 21:37:53 +00003390 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003391 // -- for a non-type template-parameter of type pointer to
3392 // object, qualification conversions (4.4) and the
3393 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00003394 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00003395 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003396 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003397
Douglas Gregorb7a09262010-04-01 18:32:35 +00003398 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3399 ParamType,
3400 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003401 }
Mike Stump1eb44332009-09-09 15:08:12 +00003402
Ted Kremenek6217b802009-07-29 21:53:49 +00003403 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003404 // -- For a non-type template-parameter of type reference to
3405 // object, no conversions apply. The type referred to by the
3406 // reference may be more cv-qualified than the (otherwise
3407 // identical) type of the template-argument. The
3408 // template-parameter is bound directly to the
3409 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00003410 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003411 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003412
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003413 if (Arg->getType() == Context.OverloadTy) {
3414 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3415 ParamRefType->getPointeeType(),
3416 true,
3417 FoundResult)) {
3418 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3419 return true;
3420
3421 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3422 ArgType = Arg->getType();
3423 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00003424 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00003425 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003426
Douglas Gregorb7a09262010-04-01 18:32:35 +00003427 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3428 ParamType,
3429 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00003430 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00003431
3432 // -- For a non-type template-parameter of type pointer to data
3433 // member, qualification conversions (4.4) are applied.
3434 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3435
Douglas Gregor8e6563b2009-02-11 18:22:40 +00003436 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00003437 // Types match exactly: nothing more to do here.
3438 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCall2de56d12010-08-25 11:45:40 +00003439 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor658bbb52009-02-11 16:16:59 +00003440 } else {
3441 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003442 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00003443 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003444 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00003445 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00003446 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00003447 }
3448
Douglas Gregorcaddba02009-11-12 18:38:13 +00003449 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00003450}
3451
3452/// \brief Check a template argument against its corresponding
3453/// template template parameter.
3454///
3455/// This routine implements the semantics of C++ [temp.arg.template].
3456/// It returns true if an error occurred, and false otherwise.
3457bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003458 const TemplateArgumentLoc &Arg) {
3459 TemplateName Name = Arg.getArgument().getAsTemplate();
3460 TemplateDecl *Template = Name.getAsTemplateDecl();
3461 if (!Template) {
3462 // Any dependent template name is fine.
3463 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3464 return false;
3465 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003466
3467 // C++ [temp.arg.template]p1:
3468 // A template-argument for a template template-parameter shall be
3469 // the name of a class template, expressed as id-expression. Only
3470 // primary class templates are considered when matching the
3471 // template template argument with the corresponding parameter;
3472 // partial specializations are not considered even if their
3473 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003474 //
3475 // Note that we also allow template template parameters here, which
3476 // will happen when we are dealing with, e.g., class template
3477 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003478 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003479 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003480 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003481 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003482 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003483 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003484 << Template;
3485 }
3486
3487 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3488 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003489 true,
3490 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003491 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003492}
3493
Douglas Gregor02024a92010-03-28 02:42:43 +00003494/// \brief Given a non-type template argument that refers to a
3495/// declaration and the type of its corresponding non-type template
3496/// parameter, produce an expression that properly refers to that
3497/// declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00003498ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003499Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3500 QualType ParamType,
3501 SourceLocation Loc) {
3502 assert(Arg.getKind() == TemplateArgument::Declaration &&
3503 "Only declaration template arguments permitted here");
3504 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3505
3506 if (VD->getDeclContext()->isRecord() &&
3507 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3508 // If the value is a class member, we might have a pointer-to-member.
3509 // Determine whether the non-type template template parameter is of
3510 // pointer-to-member type. If so, we need to build an appropriate
3511 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3512 // would refer to the member itself.
3513 if (ParamType->isMemberPointerType()) {
3514 QualType ClassType
3515 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3516 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00003517 = NestedNameSpecifier::Create(Context, 0, false,
3518 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00003519 CXXScopeSpec SS;
3520 SS.setScopeRep(Qualifier);
John McCalldfa1edb2010-11-23 20:48:44 +00003521
3522 // The actual value-ness of this is unimportant, but for
3523 // internal consistency's sake, references to instance methods
3524 // are r-values.
3525 ExprValueKind VK = VK_LValue;
3526 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
3527 VK = VK_RValue;
3528
John McCall60d7b3a2010-08-24 06:29:42 +00003529 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCallf89e55a2010-11-18 06:31:45 +00003530 VD->getType().getNonReferenceType(),
John McCalldfa1edb2010-11-23 20:48:44 +00003531 VK,
John McCallf89e55a2010-11-18 06:31:45 +00003532 Loc,
3533 &SS);
Douglas Gregor02024a92010-03-28 02:42:43 +00003534 if (RefExpr.isInvalid())
3535 return ExprError();
3536
John McCall2de56d12010-08-25 11:45:40 +00003537 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorc0c83002010-04-30 21:46:38 +00003538
3539 // We might need to perform a trailing qualification conversion, since
3540 // the element type on the parameter could be more qualified than the
3541 // element type in the expression we constructed.
3542 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3543 ParamType.getUnqualifiedType())) {
3544 Expr *RefE = RefExpr.takeAs<Expr>();
John McCall2de56d12010-08-25 11:45:40 +00003545 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorc0c83002010-04-30 21:46:38 +00003546 RefExpr = Owned(RefE);
3547 }
3548
Douglas Gregor02024a92010-03-28 02:42:43 +00003549 assert(!RefExpr.isInvalid() &&
3550 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003551 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003552 return move(RefExpr);
3553 }
3554 }
3555
3556 QualType T = VD->getType().getNonReferenceType();
3557 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003558 // When the non-type template parameter is a pointer, take the
3559 // address of the declaration.
John McCallf89e55a2010-11-18 06:31:45 +00003560 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003561 if (RefExpr.isInvalid())
3562 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003563
3564 if (T->isFunctionType() || T->isArrayType()) {
3565 // Decay functions and arrays.
3566 Expr *RefE = (Expr *)RefExpr.get();
3567 DefaultFunctionArrayConversion(RefE);
3568 if (RefE != RefExpr.get()) {
3569 RefExpr.release();
3570 RefExpr = Owned(RefE);
3571 }
3572
3573 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003574 }
3575
Douglas Gregorb7a09262010-04-01 18:32:35 +00003576 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00003577 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00003578 }
3579
John McCallf89e55a2010-11-18 06:31:45 +00003580 ExprValueKind VK = VK_RValue;
3581
Douglas Gregor02024a92010-03-28 02:42:43 +00003582 // If the non-type template parameter has reference type, qualify the
3583 // resulting declaration reference with the extra qualifiers on the
3584 // type that the reference refers to.
John McCallf89e55a2010-11-18 06:31:45 +00003585 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
3586 VK = VK_LValue;
3587 T = Context.getQualifiedType(T,
3588 TargetRef->getPointeeType().getQualifiers());
3589 }
Douglas Gregor02024a92010-03-28 02:42:43 +00003590
John McCallf89e55a2010-11-18 06:31:45 +00003591 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003592}
3593
3594/// \brief Construct a new expression that refers to the given
3595/// integral template argument with the given source-location
3596/// information.
3597///
3598/// This routine takes care of the mapping from an integral template
3599/// argument (which may have any integral type) to the appropriate
3600/// literal value.
John McCall60d7b3a2010-08-24 06:29:42 +00003601ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003602Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3603 SourceLocation Loc) {
3604 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregord3731192011-01-10 07:32:04 +00003605 "Operation is only valid for integral template arguments");
Douglas Gregor02024a92010-03-28 02:42:43 +00003606 QualType T = Arg.getIntegralType();
3607 if (T->isCharType() || T->isWideCharType())
3608 return Owned(new (Context) CharacterLiteral(
3609 Arg.getAsIntegral()->getZExtValue(),
3610 T->isWideCharType(),
3611 T,
3612 Loc));
3613 if (T->isBooleanType())
3614 return Owned(new (Context) CXXBoolLiteralExpr(
3615 Arg.getAsIntegral()->getBoolValue(),
3616 T,
3617 Loc));
3618
Peter Collingbournefb7b3632010-12-15 15:06:14 +00003619 QualType BT;
3620 if (const EnumType *ET = T->getAs<EnumType>())
3621 BT = ET->getDecl()->getPromotionType();
3622 else
3623 BT = T;
3624
3625 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
3626 ImpCastExprToType(E, T, CK_IntegralCast);
3627
3628 return Owned(E);
Douglas Gregor02024a92010-03-28 02:42:43 +00003629}
3630
3631
Douglas Gregorddc29e12009-02-06 22:42:48 +00003632/// \brief Determine whether the given template parameter lists are
3633/// equivalent.
3634///
Mike Stump1eb44332009-09-09 15:08:12 +00003635/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003636/// source code as part of a new template declaration.
3637///
3638/// \param Old The old template parameter list, typically found via
3639/// name lookup of the template declared with this template parameter
3640/// list.
3641///
3642/// \param Complain If true, this routine will produce a diagnostic if
3643/// the template parameter lists are not equivalent.
3644///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003645/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003646///
3647/// \param TemplateArgLoc If this source location is valid, then we
3648/// are actually checking the template parameter list of a template
3649/// argument (New) against the template parameter list of its
3650/// corresponding template template parameter (Old). We produce
3651/// slightly different diagnostics in this scenario.
3652///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003653/// \returns True if the template parameter lists are equal, false
3654/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003655bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003656Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3657 TemplateParameterList *Old,
3658 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003659 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003660 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003661 if (Old->size() != New->size()) {
3662 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003663 unsigned NextDiag = diag::err_template_param_list_different_arity;
3664 if (TemplateArgLoc.isValid()) {
3665 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3666 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003667 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003668 Diag(New->getTemplateLoc(), NextDiag)
3669 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003670 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003671 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003672 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003673 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003674 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3675 }
3676
3677 return false;
3678 }
3679
3680 for (TemplateParameterList::iterator OldParm = Old->begin(),
3681 OldParmEnd = Old->end(), NewParm = New->begin();
3682 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3683 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003684 if (Complain) {
3685 unsigned NextDiag = diag::err_template_param_different_kind;
3686 if (TemplateArgLoc.isValid()) {
3687 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3688 NextDiag = diag::note_template_param_different_kind;
3689 }
3690 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003691 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003692 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003693 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003694 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003695 return false;
3696 }
3697
Douglas Gregora417b872010-06-04 08:34:32 +00003698 if (TemplateTypeParmDecl *OldTTP
3699 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3700 // Template type parameters are equivalent if either both are template
3701 // type parameter packs or neither are (since we know we're at the same
3702 // index).
3703 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3704 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3705 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3706 // allow one to match a template parameter pack in the template
3707 // parameter list of a template template parameter to one or more
3708 // template parameters in the template parameter list of the
3709 // corresponding template template argument.
3710 if (Complain) {
3711 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3712 if (TemplateArgLoc.isValid()) {
3713 Diag(TemplateArgLoc,
3714 diag::err_template_arg_template_params_mismatch);
3715 NextDiag = diag::note_template_parameter_pack_non_pack;
3716 }
3717 Diag(NewTTP->getLocation(), NextDiag)
3718 << 0 << NewTTP->isParameterPack();
3719 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3720 << 0 << OldTTP->isParameterPack();
3721 }
3722 return false;
3723 }
Mike Stump1eb44332009-09-09 15:08:12 +00003724 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003725 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3726 // The types of non-type template parameters must agree.
3727 NonTypeTemplateParmDecl *NewNTTP
3728 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003729
Douglas Gregorf457c1a2011-01-05 16:01:49 +00003730 if (OldNTTP->isParameterPack() != NewNTTP->isParameterPack()) {
3731 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3732 // allow one to match a template parameter pack in the template
3733 // parameter list of a template template parameter to one or more
3734 // template parameters in the template parameter list of the
3735 // corresponding template template argument.
3736 if (Complain) {
3737 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3738 if (TemplateArgLoc.isValid()) {
3739 Diag(TemplateArgLoc,
3740 diag::err_template_arg_template_params_mismatch);
3741 NextDiag = diag::note_template_parameter_pack_non_pack;
3742 }
3743 Diag(NewNTTP->getLocation(), NextDiag)
3744 << 1 << NewNTTP->isParameterPack();
3745 Diag(OldNTTP->getLocation(), diag::note_template_parameter_pack_here)
3746 << 1 << OldNTTP->isParameterPack();
3747 }
3748 return false;
3749 }
3750
Douglas Gregorfb898e12009-11-12 16:20:59 +00003751 // If we are matching a template template argument to a template
3752 // template parameter and one of the non-type template parameter types
3753 // is dependent, then we must wait until template instantiation time
3754 // to actually compare the arguments.
3755 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3756 (OldNTTP->getType()->isDependentType() ||
3757 NewNTTP->getType()->isDependentType()))
3758 continue;
3759
Douglas Gregorddc29e12009-02-06 22:42:48 +00003760 if (Context.getCanonicalType(OldNTTP->getType()) !=
3761 Context.getCanonicalType(NewNTTP->getType())) {
3762 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003763 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3764 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003765 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003766 diag::err_template_arg_template_params_mismatch);
3767 NextDiag = diag::note_template_nontype_parm_different_type;
3768 }
3769 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003770 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003771 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003772 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003773 diag::note_template_nontype_parm_prev_declaration)
3774 << OldNTTP->getType();
3775 }
3776 return false;
3777 }
3778 } else {
3779 // The template parameter lists of template template
3780 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003781 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003782 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003783 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003784 = cast<TemplateTemplateParmDecl>(*OldParm);
3785 TemplateTemplateParmDecl *NewTTP
3786 = cast<TemplateTemplateParmDecl>(*NewParm);
Douglas Gregorf457c1a2011-01-05 16:01:49 +00003787
3788 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3789 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3790 // allow one to match a template parameter pack in the template
3791 // parameter list of a template template parameter to one or more
3792 // template parameters in the template parameter list of the
3793 // corresponding template template argument.
3794 if (Complain) {
3795 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3796 if (TemplateArgLoc.isValid()) {
3797 Diag(TemplateArgLoc,
3798 diag::err_template_arg_template_params_mismatch);
3799 NextDiag = diag::note_template_parameter_pack_non_pack;
3800 }
3801 Diag(NewTTP->getLocation(), NextDiag)
3802 << 2 << NewTTP->isParameterPack();
3803 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3804 << 2 << OldTTP->isParameterPack();
3805 }
3806 return false;
3807 }
3808
Douglas Gregorddc29e12009-02-06 22:42:48 +00003809 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3810 OldTTP->getTemplateParameters(),
3811 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003812 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003813 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003814 return false;
3815 }
3816 }
3817
3818 return true;
3819}
3820
3821/// \brief Check whether a template can be declared within this scope.
3822///
3823/// If the template declaration is valid in this scope, returns
3824/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003825bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003826Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003827 // Find the nearest enclosing declaration scope.
3828 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3829 (S->getFlags() & Scope::TemplateParamScope) != 0)
3830 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003831
Douglas Gregorddc29e12009-02-06 22:42:48 +00003832 // C++ [temp]p2:
3833 // A template-declaration can appear only as a namespace scope or
3834 // class scope declaration.
3835 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003836 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3837 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003838 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003839 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003840
Eli Friedman1503f772009-07-31 01:43:05 +00003841 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003842 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003843
3844 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3845 return false;
3846
Mike Stump1eb44332009-09-09 15:08:12 +00003847 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003848 diag::err_template_outside_namespace_or_class_scope)
3849 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003850}
Douglas Gregorcc636682009-02-17 23:15:12 +00003851
Douglas Gregord5cb8762009-10-07 00:13:32 +00003852/// \brief Determine what kind of template specialization the given declaration
3853/// is.
3854static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3855 if (!D)
3856 return TSK_Undeclared;
3857
Douglas Gregorf6b11852009-10-08 15:14:33 +00003858 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3859 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003860 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3861 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003862 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3863 return Var->getTemplateSpecializationKind();
3864
Douglas Gregord5cb8762009-10-07 00:13:32 +00003865 return TSK_Undeclared;
3866}
3867
Douglas Gregor9302da62009-10-14 23:50:59 +00003868/// \brief Check whether a specialization is well-formed in the current
3869/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003870///
Douglas Gregor9302da62009-10-14 23:50:59 +00003871/// This routine determines whether a template specialization can be declared
3872/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003873///
3874/// \param S the semantic analysis object for which this check is being
3875/// performed.
3876///
3877/// \param Specialized the entity being specialized or instantiated, which
3878/// may be a kind of template (class template, function template, etc.) or
3879/// a member of a class template (member function, static data member,
3880/// member class).
3881///
3882/// \param PrevDecl the previous declaration of this entity, if any.
3883///
3884/// \param Loc the location of the explicit specialization or instantiation of
3885/// this entity.
3886///
3887/// \param IsPartialSpecialization whether this is a partial specialization of
3888/// a class template.
3889///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003890/// \returns true if there was an error that we cannot recover from, false
3891/// otherwise.
3892static bool CheckTemplateSpecializationScope(Sema &S,
3893 NamedDecl *Specialized,
3894 NamedDecl *PrevDecl,
3895 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003896 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003897 // Keep these "kind" numbers in sync with the %select statements in the
3898 // various diagnostics emitted by this routine.
3899 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003900 bool isTemplateSpecialization = false;
3901 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003902 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003903 isTemplateSpecialization = true;
3904 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003905 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003906 isTemplateSpecialization = true;
3907 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003908 EntityKind = 3;
3909 else if (isa<VarDecl>(Specialized))
3910 EntityKind = 4;
3911 else if (isa<RecordDecl>(Specialized))
3912 EntityKind = 5;
3913 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003914 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3915 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003916 return true;
3917 }
3918
Douglas Gregor88b70942009-02-25 22:02:03 +00003919 // C++ [temp.expl.spec]p2:
3920 // An explicit specialization shall be declared in the namespace
3921 // of which the template is a member, or, for member templates, in
3922 // the namespace of which the enclosing class or enclosing class
3923 // template is a member. An explicit specialization of a member
3924 // function, member class or static data member of a class
3925 // template shall be declared in the namespace of which the class
3926 // template is a member. Such a declaration may also be a
3927 // definition. If the declaration is not a definition, the
3928 // specialization may be defined later in the name- space in which
3929 // the explicit specialization was declared, or in a namespace
3930 // that encloses the one in which the explicit specialization was
3931 // declared.
Sebastian Redl7a126a42010-08-31 00:36:30 +00003932 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003933 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003934 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003935 return true;
3936 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003937
Douglas Gregor0a407472009-10-07 17:30:37 +00003938 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3939 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003940 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003941 return true;
3942 }
3943
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003944 // C++ [temp.class.spec]p6:
3945 // A class template partial specialization may be declared or redeclared
3946 // in any namespace scope in which its definition may be defined (14.5.1
3947 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003948 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003949 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003950 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003951 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003952 if ((!PrevDecl ||
3953 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3954 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregor121dc9a2010-09-12 05:08:28 +00003955 // C++ [temp.exp.spec]p2:
3956 // An explicit specialization shall be declared in the namespace of which
3957 // the template is a member, or, for member templates, in the namespace
3958 // of which the enclosing class or enclosing class template is a member.
3959 // An explicit specialization of a member function, member class or
3960 // static data member of a class template shall be declared in the
3961 // namespace of which the class template is a member.
3962 //
3963 // C++0x [temp.expl.spec]p2:
3964 // An explicit specialization shall be declared in a namespace enclosing
3965 // the specialized template.
3966 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3967 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregora4d5de52010-09-12 05:24:55 +00003968 bool IsCPlusPlus0xExtension
3969 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003970 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003971 S.Diag(Loc, IsCPlusPlus0xExtension
3972 ? diag::ext_template_spec_decl_out_of_scope_global
3973 : diag::err_template_spec_decl_out_of_scope_global)
3974 << EntityKind << Specialized;
Douglas Gregor9302da62009-10-14 23:50:59 +00003975 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003976 S.Diag(Loc, IsCPlusPlus0xExtension
3977 ? diag::ext_template_spec_decl_out_of_scope
3978 : diag::err_template_spec_decl_out_of_scope)
3979 << EntityKind << Specialized
3980 << cast<NamedDecl>(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003981
3982 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3983 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003984 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003985 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003986
3987 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003988 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003989 // Note that HandleDeclarator() performs this check for explicit
3990 // specializations of function templates, static data members, and member
3991 // functions, so we skip the check here for those kinds of entities.
3992 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003993 // Should we refactor that check, so that it occurs later?
3994 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003995 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3996 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003997 if (isa<TranslationUnitDecl>(SpecializedContext))
3998 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3999 << EntityKind << Specialized;
4000 else if (isa<NamespaceDecl>(SpecializedContext))
4001 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
4002 << EntityKind << Specialized
4003 << cast<NamedDecl>(SpecializedContext);
4004
Douglas Gregor9302da62009-10-14 23:50:59 +00004005 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00004006 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00004007
4008 // FIXME: check for specialization-after-instantiation errors and such.
4009
Douglas Gregor88b70942009-02-25 22:02:03 +00004010 return false;
4011}
Douglas Gregorbacb9492011-01-03 21:13:47 +00004012
4013/// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
4014/// that checks non-type template partial specialization arguments.
4015static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
4016 NonTypeTemplateParmDecl *Param,
4017 const TemplateArgument *Args,
4018 unsigned NumArgs) {
4019 for (unsigned I = 0; I != NumArgs; ++I) {
4020 if (Args[I].getKind() == TemplateArgument::Pack) {
4021 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
4022 Args[I].pack_begin(),
4023 Args[I].pack_size()))
4024 return true;
4025
Douglas Gregore94866f2009-06-12 21:21:02 +00004026 continue;
Douglas Gregorbacb9492011-01-03 21:13:47 +00004027 }
4028
4029 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004030 if (!ArgExpr) {
Douglas Gregore94866f2009-06-12 21:21:02 +00004031 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004032 }
Douglas Gregore94866f2009-06-12 21:21:02 +00004033
Douglas Gregor7a21fd42011-01-03 21:37:45 +00004034 // We can have a pack expansion of any of the bullets below.
Douglas Gregorbacb9492011-01-03 21:13:47 +00004035 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
4036 ArgExpr = Expansion->getPattern();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00004037
4038 // Strip off any implicit casts we added as part of type checking.
4039 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4040 ArgExpr = ICE->getSubExpr();
Douglas Gregorb9c66312010-12-23 17:13:55 +00004041
Douglas Gregore94866f2009-06-12 21:21:02 +00004042 // C++ [temp.class.spec]p8:
4043 // A non-type argument is non-specialized if it is the name of a
4044 // non-type parameter. All other non-type arguments are
4045 // specialized.
4046 //
4047 // Below, we check the two conditions that only apply to
4048 // specialized non-type arguments, so skip any non-specialized
4049 // arguments.
4050 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00004051 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregore94866f2009-06-12 21:21:02 +00004052 continue;
Douglas Gregorb9c66312010-12-23 17:13:55 +00004053
Douglas Gregore94866f2009-06-12 21:21:02 +00004054 // C++ [temp.class.spec]p9:
4055 // Within the argument list of a class template partial
4056 // specialization, the following restrictions apply:
4057 // -- A partially specialized non-type argument expression
4058 // shall not involve a template parameter of the partial
4059 // specialization except when the argument expression is a
4060 // simple identifier.
4061 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004062 S.Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00004063 diag::err_dependent_non_type_arg_in_partial_spec)
4064 << ArgExpr->getSourceRange();
4065 return true;
4066 }
Douglas Gregorbacb9492011-01-03 21:13:47 +00004067
Douglas Gregore94866f2009-06-12 21:21:02 +00004068 // -- The type of a template parameter corresponding to a
4069 // specialized non-type argument shall not be dependent on a
4070 // parameter of the specialization.
4071 if (Param->getType()->isDependentType()) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004072 S.Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00004073 diag::err_dependent_typed_non_type_arg_in_partial_spec)
4074 << Param->getType()
4075 << ArgExpr->getSourceRange();
Douglas Gregorbacb9492011-01-03 21:13:47 +00004076 S.Diag(Param->getLocation(), diag::note_template_param_here);
Douglas Gregore94866f2009-06-12 21:21:02 +00004077 return true;
4078 }
4079 }
Douglas Gregorbacb9492011-01-03 21:13:47 +00004080
4081 return false;
4082}
4083
4084/// \brief Check the non-type template arguments of a class template
4085/// partial specialization according to C++ [temp.class.spec]p9.
4086///
4087/// \param TemplateParams the template parameters of the primary class
4088/// template.
4089///
4090/// \param TemplateArg the template arguments of the class template
4091/// partial specialization.
4092///
4093/// \returns true if there was an error, false otherwise.
4094static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
4095 TemplateParameterList *TemplateParams,
4096 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs) {
4097 const TemplateArgument *ArgList = TemplateArgs.data();
4098
4099 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4100 NonTypeTemplateParmDecl *Param
4101 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
4102 if (!Param)
4103 continue;
4104
4105 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
4106 &ArgList[I], 1))
4107 return true;
4108 }
Douglas Gregore94866f2009-06-12 21:21:02 +00004109
4110 return false;
4111}
4112
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004113/// \brief Retrieve the previous declaration of the given declaration.
4114static NamedDecl *getPreviousDecl(NamedDecl *ND) {
4115 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4116 return VD->getPreviousDeclaration();
4117 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
4118 return FD->getPreviousDeclaration();
4119 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
4120 return TD->getPreviousDeclaration();
4121 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
4122 return TD->getPreviousDeclaration();
4123 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4124 return FTD->getPreviousDeclaration();
4125 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
4126 return CTD->getPreviousDeclaration();
4127 return 0;
4128}
4129
John McCalld226f652010-08-21 09:40:31 +00004130DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00004131Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
4132 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00004133 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004134 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004135 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00004136 SourceLocation TemplateNameLoc,
4137 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00004138 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00004139 SourceLocation RAngleLoc,
4140 AttributeList *Attr,
4141 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004142 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00004143
Douglas Gregorcc636682009-02-17 23:15:12 +00004144 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00004145 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004146 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00004147 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
4148
4149 if (!ClassTemplate) {
4150 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
4151 << (Name.getAsTemplateDecl() &&
4152 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
4153 return true;
4154 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004155
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004156 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004157 bool isPartialSpecialization = false;
4158
Douglas Gregor88b70942009-02-25 22:02:03 +00004159 // Check the validity of the template headers that introduce this
4160 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004161 // FIXME: We probably shouldn't complain about these headers for
4162 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004163 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00004164 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00004165 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
4166 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004167 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00004168 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004169 isExplicitSpecialization,
4170 Invalid);
4171 if (Invalid)
4172 return true;
4173
Abramo Bagnara9b934882010-06-12 08:15:14 +00004174 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
4175 if (TemplateParams)
4176 --NumMatchedTemplateParamLists;
4177
Douglas Gregor05396e22009-08-25 17:23:04 +00004178 if (TemplateParams && TemplateParams->size() > 0) {
4179 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00004180
Douglas Gregorb0ee93c2010-12-21 08:14:57 +00004181 if (TUK == TUK_Friend) {
4182 Diag(KWLoc, diag::err_partial_specialization_friend)
4183 << SourceRange(LAngleLoc, RAngleLoc);
4184 return true;
4185 }
4186
Douglas Gregor05396e22009-08-25 17:23:04 +00004187 // C++ [temp.class.spec]p10:
4188 // The template parameter list of a specialization shall not
4189 // contain default template argument values.
4190 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4191 Decl *Param = TemplateParams->getParam(I);
4192 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4193 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004194 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004195 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00004196 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004197 }
4198 } else if (NonTypeTemplateParmDecl *NTTP
4199 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4200 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004201 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004202 diag::err_default_arg_in_partial_spec)
4203 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004204 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004205 }
4206 } else {
4207 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00004208 if (TTP->hasDefaultArgument()) {
4209 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004210 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00004211 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004212 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004213 }
4214 }
4215 }
Douglas Gregora735b202009-10-13 14:39:41 +00004216 } else if (TemplateParams) {
4217 if (TUK == TUK_Friend)
4218 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00004219 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00004220 SourceRange(TemplateParams->getTemplateLoc(),
4221 TemplateParams->getRAngleLoc()))
4222 << SourceRange(LAngleLoc, RAngleLoc);
4223 else
4224 isExplicitSpecialization = true;
4225 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00004226 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00004227 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004228 isExplicitSpecialization = true;
4229 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004230
Douglas Gregorcc636682009-02-17 23:15:12 +00004231 // Check that the specialization uses the same tag kind as the
4232 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004233 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4234 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004235 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004236 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004237 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004238 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00004239 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004240 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00004241 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004242 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004243 diag::note_previous_use);
4244 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4245 }
4246
Douglas Gregor40808ce2009-03-09 23:48:35 +00004247 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004248 TemplateArgumentListInfo TemplateArgs;
4249 TemplateArgs.setLAngleLoc(LAngleLoc);
4250 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004251 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00004252
Douglas Gregor925910d2011-01-03 20:35:03 +00004253 // Check for unexpanded parameter packs in any of the template arguments.
4254 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4255 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4256 UPPC_PartialSpecialization))
4257 return true;
4258
Douglas Gregorcc636682009-02-17 23:15:12 +00004259 // Check that the template argument list is well-formed for this
4260 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00004261 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00004262 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4263 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004264 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004265
Douglas Gregor910f8002010-11-07 23:05:16 +00004266 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregorcc636682009-02-17 23:15:12 +00004267 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004268
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004269 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00004270 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004271 if (isPartialSpecialization) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004272 if (CheckClassTemplatePartialSpecializationArgs(*this,
Douglas Gregore94866f2009-06-12 21:21:02 +00004273 ClassTemplate->getTemplateParameters(),
Douglas Gregorb9c66312010-12-23 17:13:55 +00004274 Converted))
Douglas Gregore94866f2009-06-12 21:21:02 +00004275 return true;
4276
Douglas Gregorde090962010-02-09 00:37:32 +00004277 if (!Name.isDependent() &&
4278 !TemplateSpecializationType::anyDependentTemplateArguments(
4279 TemplateArgs.getArgumentArray(),
4280 TemplateArgs.size())) {
4281 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4282 << ClassTemplate->getDeclName();
4283 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00004284 }
4285 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004286
Douglas Gregorcc636682009-02-17 23:15:12 +00004287 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004288 ClassTemplateSpecializationDecl *PrevDecl = 0;
4289
4290 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004291 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004292 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004293 = ClassTemplate->findPartialSpecialization(Converted.data(),
4294 Converted.size(),
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004295 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004296 else
4297 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004298 = ClassTemplate->findSpecialization(Converted.data(),
4299 Converted.size(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00004300
4301 ClassTemplateSpecializationDecl *Specialization = 0;
4302
Douglas Gregor88b70942009-02-25 22:02:03 +00004303 // Check whether we can declare a class template specialization in
4304 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004305 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00004306 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00004307 TemplateNameLoc,
4308 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004309 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004310
Douglas Gregorb88e8882009-07-30 17:40:51 +00004311 // The canonical type
4312 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004313 if (PrevDecl &&
4314 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00004315 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004316 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004317 // arguments was referenced but not declared, or we're only
4318 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00004319 // declaration node as our own, updating its source location to
4320 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004321 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004322 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00004323 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00004324 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004325 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00004326 // Build the canonical type that describes the converted template
4327 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00004328 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4329 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb9c66312010-12-23 17:13:55 +00004330 Converted.data(),
4331 Converted.size());
4332
4333 if (Context.hasSameType(CanonType,
4334 ClassTemplate->getInjectedClassNameSpecialization())) {
4335 // C++ [temp.class.spec]p9b3:
4336 //
4337 // -- The argument list of the specialization shall not be identical
4338 // to the implicit argument list of the primary template.
4339 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4340 << (TUK == TUK_Definition)
4341 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4342 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
4343 ClassTemplate->getIdentifier(),
4344 TemplateNameLoc,
4345 Attr,
4346 TemplateParams,
4347 AS_none);
4348 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00004349
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004350 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004351 ClassTemplatePartialSpecializationDecl *PrevPartial
4352 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004353 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004354 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00004355 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00004356 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004357 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00004358 TemplateNameLoc,
4359 TemplateParams,
4360 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004361 Converted.data(),
4362 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00004363 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00004364 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004365 PrevPartial,
4366 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00004367 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004368 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004369 Partial->setTemplateParameterListsInfo(Context,
4370 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004371 (TemplateParameterList**) TemplateParameterLists.release());
4372 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004373
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004374 if (!PrevPartial)
4375 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004376 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00004377
Douglas Gregored9c0f92009-10-29 00:04:11 +00004378 // If we are providing an explicit specialization of a member class
4379 // template specialization, make a note of that.
4380 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4381 PrevPartial->setMemberSpecialization();
4382
Douglas Gregor031a5882009-06-13 00:26:55 +00004383 // Check that all of the template parameters of the class template
4384 // partial specialization are deducible from the template
4385 // arguments. If not, this class template partial specialization
4386 // will never be used.
4387 llvm::SmallVector<bool, 8> DeducibleParams;
4388 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00004389 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004390 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00004391 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00004392 unsigned NumNonDeducible = 0;
4393 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4394 if (!DeducibleParams[I])
4395 ++NumNonDeducible;
4396
4397 if (NumNonDeducible) {
4398 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4399 << (NumNonDeducible > 1)
4400 << SourceRange(TemplateNameLoc, RAngleLoc);
4401 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4402 if (!DeducibleParams[I]) {
4403 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4404 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00004405 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004406 diag::note_partial_spec_unused_parameter)
4407 << Param->getDeclName();
4408 else
Mike Stump1eb44332009-09-09 15:08:12 +00004409 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004410 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00004411 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00004412 }
4413 }
4414 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004415 } else {
4416 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004417 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004418 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004419 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00004420 ClassTemplate->getDeclContext(),
4421 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004422 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004423 Converted.data(),
4424 Converted.size(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004425 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004426 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004427 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004428 Specialization->setTemplateParameterListsInfo(Context,
4429 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004430 (TemplateParameterList**) TemplateParameterLists.release());
4431 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004432
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004433 if (!PrevDecl)
4434 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00004435
4436 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004437 }
4438
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004439 // C++ [temp.expl.spec]p6:
4440 // If a template, a member template or the member of a class template is
4441 // explicitly specialized then that specialization shall be declared
4442 // before the first use of that specialization that would cause an implicit
4443 // instantiation to take place, in every translation unit in which such a
4444 // use occurs; no diagnostic is required.
4445 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004446 bool Okay = false;
4447 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4448 // Is there any previous explicit specialization declaration?
4449 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4450 Okay = true;
4451 break;
4452 }
4453 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004454
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004455 if (!Okay) {
4456 SourceRange Range(TemplateNameLoc, RAngleLoc);
4457 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4458 << Context.getTypeDeclType(Specialization) << Range;
4459
4460 Diag(PrevDecl->getPointOfInstantiation(),
4461 diag::note_instantiation_required_here)
4462 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004463 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004464 return true;
4465 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004466 }
4467
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004468 // If this is not a friend, note that this is an explicit specialization.
4469 if (TUK != TUK_Friend)
4470 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004471
4472 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004473 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00004474 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004475 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004476 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004477 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00004478 Diag(Def->getLocation(), diag::note_previous_definition);
4479 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00004480 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004481 }
4482 }
4483
John McCall7f1b9872010-12-18 03:30:47 +00004484 if (Attr)
4485 ProcessDeclAttributeList(S, Specialization, Attr);
4486
Douglas Gregorfc705b82009-02-26 22:19:44 +00004487 // Build the fully-sugared type for this class template
4488 // specialization as the user wrote in the specialization
4489 // itself. This means that we'll pretty-print the type retrieved
4490 // from the specialization's declaration the way that the user
4491 // actually wrote the specialization, rather than formatting the
4492 // name based on the "canonical" representation used to store the
4493 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004494 TypeSourceInfo *WrittenTy
4495 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4496 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004497 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004498 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor7e9b57b2010-07-06 18:33:12 +00004499 if (TemplateParams)
4500 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004501 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00004502 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00004503
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004504 // C++ [temp.expl.spec]p9:
4505 // A template explicit specialization is in the scope of the
4506 // namespace in which the template was defined.
4507 //
4508 // We actually implement this paragraph where we set the semantic
4509 // context (in the creation of the ClassTemplateSpecializationDecl),
4510 // but we also maintain the lexical context where the actual
4511 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00004512 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004513
Douglas Gregorcc636682009-02-17 23:15:12 +00004514 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004515 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00004516 Specialization->startDefinition();
4517
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004518 if (TUK == TUK_Friend) {
4519 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4520 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00004521 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004522 /*FIXME:*/KWLoc);
4523 Friend->setAccess(AS_public);
4524 CurContext->addDecl(Friend);
4525 } else {
4526 // Add the specialization into its lexical context, so that it can
4527 // be seen when iterating through the list of declarations in that
4528 // context. However, specializations are not found by name lookup.
4529 CurContext->addDecl(Specialization);
4530 }
John McCalld226f652010-08-21 09:40:31 +00004531 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00004532}
Douglas Gregord57959a2009-03-27 23:10:48 +00004533
John McCalld226f652010-08-21 09:40:31 +00004534Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00004535 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004536 Declarator &D) {
Douglas Gregore542c862009-06-23 23:11:28 +00004537 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4538}
4539
John McCalld226f652010-08-21 09:40:31 +00004540Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004541 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004542 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00004543 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004544 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00004545
Douglas Gregor52591bf2009-06-24 00:54:41 +00004546 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004547 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00004548 }
Mike Stump1eb44332009-09-09 15:08:12 +00004549
Douglas Gregor52591bf2009-06-24 00:54:41 +00004550 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004551
John McCalld226f652010-08-21 09:40:31 +00004552 Decl *DP = HandleDeclarator(ParentScope, D,
4553 move(TemplateParameterLists),
4554 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004555 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00004556 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00004557 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00004558 FunctionTemplate->getTemplatedDecl());
4559 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4560 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4561 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00004562}
4563
John McCall75042392010-02-11 01:33:53 +00004564/// \brief Strips various properties off an implicit instantiation
4565/// that has just been explicitly specialized.
4566static void StripImplicitInstantiation(NamedDecl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00004567 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00004568
4569 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4570 FD->setInlineSpecified(false);
4571 }
4572}
4573
Douglas Gregor454885e2009-10-15 15:54:05 +00004574/// \brief Diagnose cases where we have an explicit template specialization
4575/// before/after an explicit template instantiation, producing diagnostics
4576/// for those cases where they are required and determining whether the
4577/// new specialization/instantiation will have any effect.
4578///
Douglas Gregor454885e2009-10-15 15:54:05 +00004579/// \param NewLoc the location of the new explicit specialization or
4580/// instantiation.
4581///
4582/// \param NewTSK the kind of the new explicit specialization or instantiation.
4583///
4584/// \param PrevDecl the previous declaration of the entity.
4585///
4586/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4587///
4588/// \param PrevPointOfInstantiation if valid, indicates where the previus
4589/// declaration was instantiated (either implicitly or explicitly).
4590///
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004591/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00004592/// specialization or instantiation has no effect and should be ignored.
4593///
4594/// \returns true if there was an error that should prevent the introduction of
4595/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004596bool
4597Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4598 TemplateSpecializationKind NewTSK,
4599 NamedDecl *PrevDecl,
4600 TemplateSpecializationKind PrevTSK,
4601 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004602 bool &HasNoEffect) {
4603 HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004604
4605 switch (NewTSK) {
4606 case TSK_Undeclared:
4607 case TSK_ImplicitInstantiation:
4608 assert(false && "Don't check implicit instantiations here");
4609 return false;
4610
4611 case TSK_ExplicitSpecialization:
4612 switch (PrevTSK) {
4613 case TSK_Undeclared:
4614 case TSK_ExplicitSpecialization:
4615 // Okay, we're just specializing something that is either already
4616 // explicitly specialized or has merely been mentioned without any
4617 // instantiation.
4618 return false;
4619
4620 case TSK_ImplicitInstantiation:
4621 if (PrevPointOfInstantiation.isInvalid()) {
4622 // The declaration itself has not actually been instantiated, so it is
4623 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004624 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004625 return false;
4626 }
4627 // Fall through
4628
4629 case TSK_ExplicitInstantiationDeclaration:
4630 case TSK_ExplicitInstantiationDefinition:
4631 assert((PrevTSK == TSK_ImplicitInstantiation ||
4632 PrevPointOfInstantiation.isValid()) &&
4633 "Explicit instantiation without point of instantiation?");
4634
4635 // C++ [temp.expl.spec]p6:
4636 // If a template, a member template or the member of a class template
4637 // is explicitly specialized then that specialization shall be declared
4638 // before the first use of that specialization that would cause an
4639 // implicit instantiation to take place, in every translation unit in
4640 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004641 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4642 // Is there any previous explicit specialization declaration?
4643 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4644 return false;
4645 }
4646
Douglas Gregor0d035142009-10-27 18:42:08 +00004647 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004648 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004649 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004650 << (PrevTSK != TSK_ImplicitInstantiation);
4651
4652 return true;
4653 }
4654 break;
4655
4656 case TSK_ExplicitInstantiationDeclaration:
4657 switch (PrevTSK) {
4658 case TSK_ExplicitInstantiationDeclaration:
4659 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004660 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004661 return false;
4662
4663 case TSK_Undeclared:
4664 case TSK_ImplicitInstantiation:
4665 // We're explicitly instantiating something that may have already been
4666 // implicitly instantiated; that's fine.
4667 return false;
4668
4669 case TSK_ExplicitSpecialization:
4670 // C++0x [temp.explicit]p4:
4671 // For a given set of template parameters, if an explicit instantiation
4672 // of a template appears after a declaration of an explicit
4673 // specialization for that template, the explicit instantiation has no
4674 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004675 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004676 return false;
4677
4678 case TSK_ExplicitInstantiationDefinition:
4679 // C++0x [temp.explicit]p10:
4680 // If an entity is the subject of both an explicit instantiation
4681 // declaration and an explicit instantiation definition in the same
4682 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004683 Diag(NewLoc,
4684 diag::err_explicit_instantiation_declaration_after_definition);
4685 Diag(PrevPointOfInstantiation,
4686 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004687 assert(PrevPointOfInstantiation.isValid() &&
4688 "Explicit instantiation without point of instantiation?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004689 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004690 return false;
4691 }
4692 break;
4693
4694 case TSK_ExplicitInstantiationDefinition:
4695 switch (PrevTSK) {
4696 case TSK_Undeclared:
4697 case TSK_ImplicitInstantiation:
4698 // We're explicitly instantiating something that may have already been
4699 // implicitly instantiated; that's fine.
4700 return false;
4701
4702 case TSK_ExplicitSpecialization:
4703 // C++ DR 259, C++0x [temp.explicit]p4:
4704 // For a given set of template parameters, if an explicit
4705 // instantiation of a template appears after a declaration of
4706 // an explicit specialization for that template, the explicit
4707 // instantiation has no effect.
4708 //
4709 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004710 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004711 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004712 if (!getLangOptions().CPlusPlus0x) {
4713 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004714 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004715 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004716 diag::note_previous_template_specialization);
4717 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004718 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004719 return false;
4720
4721 case TSK_ExplicitInstantiationDeclaration:
4722 // We're explicity instantiating a definition for something for which we
4723 // were previously asked to suppress instantiations. That's fine.
4724 return false;
4725
4726 case TSK_ExplicitInstantiationDefinition:
4727 // C++0x [temp.spec]p5:
4728 // For a given template and a given set of template-arguments,
4729 // - an explicit instantiation definition shall appear at most once
4730 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004731 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004732 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004733 Diag(PrevPointOfInstantiation,
4734 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004735 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004736 return false;
4737 }
4738 break;
4739 }
4740
4741 assert(false && "Missing specialization/instantiation case?");
4742
4743 return false;
4744}
4745
John McCallaf2094e2010-04-08 09:05:18 +00004746/// \brief Perform semantic analysis for the given dependent function
4747/// template specialization. The only possible way to get a dependent
4748/// function template specialization is with a friend declaration,
4749/// like so:
4750///
4751/// template <class T> void foo(T);
4752/// template <class T> class A {
4753/// friend void foo<>(T);
4754/// };
4755///
4756/// There really isn't any useful analysis we can do here, so we
4757/// just store the information.
4758bool
4759Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4760 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4761 LookupResult &Previous) {
4762 // Remove anything from Previous that isn't a function template in
4763 // the correct context.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004764 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallaf2094e2010-04-08 09:05:18 +00004765 LookupResult::Filter F = Previous.makeFilter();
4766 while (F.hasNext()) {
4767 NamedDecl *D = F.next()->getUnderlyingDecl();
4768 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl7a126a42010-08-31 00:36:30 +00004769 !FDLookupContext->InEnclosingNamespaceSetOf(
4770 D->getDeclContext()->getRedeclContext()))
John McCallaf2094e2010-04-08 09:05:18 +00004771 F.erase();
4772 }
4773 F.done();
4774
4775 // Should this be diagnosed here?
4776 if (Previous.empty()) return true;
4777
4778 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4779 ExplicitTemplateArgs);
4780 return false;
4781}
4782
Abramo Bagnarae03db982010-05-20 15:32:11 +00004783/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004784/// specialization.
4785///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004786/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004787/// explicit function template specialization. On successful completion,
4788/// the function declaration \p FD will become a function template
4789/// specialization.
4790///
4791/// \param FD the function declaration, which will be updated to become a
4792/// function template specialization.
4793///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004794/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4795/// if any. Note that this may be valid info even when 0 arguments are
4796/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4797/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004798///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004799/// \param PrevDecl the set of declarations that may be specialized by
4800/// this function specialization.
4801bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004802Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004803 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004804 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004805 // The set of function template specializations that could match this
4806 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004807 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004808
Sebastian Redl7a126a42010-08-31 00:36:30 +00004809 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall68263142009-11-18 22:49:29 +00004810 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4811 I != E; ++I) {
4812 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4813 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004814 // Only consider templates found within the same semantic lookup scope as
4815 // FD.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004816 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4817 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004818 continue;
4819
4820 // C++ [temp.expl.spec]p11:
4821 // A trailing template-argument can be left unspecified in the
4822 // template-id naming an explicit function template specialization
4823 // provided it can be deduced from the function argument type.
4824 // Perform template argument deduction to determine whether we may be
4825 // specializing this template.
4826 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004827 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004828 FunctionDecl *Specialization = 0;
4829 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004830 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004831 FD->getType(),
4832 Specialization,
4833 Info)) {
4834 // FIXME: Template argument deduction failed; record why it failed, so
4835 // that we can provide nifty diagnostics.
4836 (void)TDK;
4837 continue;
4838 }
4839
4840 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004841 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004842 }
4843 }
4844
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004845 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004846 UnresolvedSetIterator Result
4847 = getMostSpecialized(Candidates.begin(), Candidates.end(),
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004848 TPOC_Other, 0, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004849 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004850 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004851 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004852 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004853 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004854 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004855 return true;
John McCallc373d482010-01-27 01:50:18 +00004856
4857 // Ignore access information; it doesn't figure into redeclaration checking.
4858 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004859 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004860
4861 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004862 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004863
4864 // If this is a friend declaration, then we're not really declaring
4865 // an explicit specialization.
4866 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004867
Douglas Gregord5cb8762009-10-07 00:13:32 +00004868 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004869 if (!isFriend &&
4870 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004871 Specialization->getPrimaryTemplate(),
4872 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004873 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004874 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004875
4876 // C++ [temp.expl.spec]p6:
4877 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004878 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004879 // before the first use of that specialization that would cause an implicit
4880 // instantiation to take place, in every translation unit in which such a
4881 // use occurs; no diagnostic is required.
4882 FunctionTemplateSpecializationInfo *SpecInfo
4883 = Specialization->getTemplateSpecializationInfo();
4884 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004885
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004886 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00004887 if (!isFriend &&
4888 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004889 TSK_ExplicitSpecialization,
4890 Specialization,
4891 SpecInfo->getTemplateSpecializationKind(),
4892 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004893 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004894 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004895
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004896 // Mark the prior declaration as an explicit specialization, so that later
4897 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004898 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00004899 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004900 MarkUnusedFileScopedDecl(Specialization);
4901 }
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004902
4903 // Turn the given function declaration into a function template
4904 // specialization, with the template arguments from the previous
4905 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004906 // Take copies of (semantic and syntactic) template argument lists.
4907 const TemplateArgumentList* TemplArgs = new (Context)
4908 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4909 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4910 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004911 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004912 TemplArgs, /*InsertPos=*/0,
4913 SpecInfo->getTemplateSpecializationKind(),
4914 TemplArgsAsWritten);
4915
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004916 // The "previous declaration" for this function template specialization is
4917 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004918 Previous.clear();
4919 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004920 return false;
4921}
4922
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004923/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004924/// specialization.
4925///
4926/// This routine performs all of the semantic analysis required for an
4927/// explicit member function specialization. On successful completion,
4928/// the function declaration \p FD will become a member function
4929/// specialization.
4930///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004931/// \param Member the member declaration, which will be updated to become a
4932/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004933///
John McCall68263142009-11-18 22:49:29 +00004934/// \param Previous the set of declarations, one of which may be specialized
4935/// by this function specialization; the set will be modified to contain the
4936/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004937bool
John McCall68263142009-11-18 22:49:29 +00004938Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004939 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004940
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004941 // Try to find the member we are instantiating.
4942 NamedDecl *Instantiation = 0;
4943 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004944 MemberSpecializationInfo *MSInfo = 0;
4945
John McCall68263142009-11-18 22:49:29 +00004946 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004947 // Nowhere to look anyway.
4948 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004949 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4950 I != E; ++I) {
4951 NamedDecl *D = (*I)->getUnderlyingDecl();
4952 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004953 if (Context.hasSameType(Function->getType(), Method->getType())) {
4954 Instantiation = Method;
4955 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004956 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004957 break;
4958 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004959 }
4960 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004961 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004962 VarDecl *PrevVar;
4963 if (Previous.isSingleResult() &&
4964 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004965 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004966 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004967 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004968 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004969 }
4970 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004971 CXXRecordDecl *PrevRecord;
4972 if (Previous.isSingleResult() &&
4973 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4974 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004975 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004976 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004977 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004978 }
4979
4980 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004981 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004982 // specializations are always out-of-line, the caller will complain about
4983 // this mismatch later.
4984 return false;
4985 }
John McCall77e8b112010-04-13 20:37:33 +00004986
4987 // If this is a friend, just bail out here before we start turning
4988 // things into explicit specializations.
4989 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4990 // Preserve instantiation information.
4991 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4992 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4993 cast<CXXMethodDecl>(InstantiatedFrom),
4994 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4995 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4996 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4997 cast<CXXRecordDecl>(InstantiatedFrom),
4998 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4999 }
5000
5001 Previous.clear();
5002 Previous.addDecl(Instantiation);
5003 return false;
5004 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005005
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005006 // Make sure that this is a specialization of a member.
5007 if (!InstantiatedFrom) {
5008 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
5009 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005010 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
5011 return true;
5012 }
5013
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005014 // C++ [temp.expl.spec]p6:
5015 // If a template, a member template or the member of a class template is
5016 // explicitly specialized then that spe- cialization shall be declared
5017 // before the first use of that specialization that would cause an implicit
5018 // instantiation to take place, in every translation unit in which such a
5019 // use occurs; no diagnostic is required.
5020 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00005021
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005022 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00005023 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
5024 TSK_ExplicitSpecialization,
5025 Instantiation,
5026 MSInfo->getTemplateSpecializationKind(),
5027 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005028 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005029 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005030
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005031 // Check the scope of this explicit specialization.
5032 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005033 InstantiatedFrom,
5034 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00005035 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005036 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00005037
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005038 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00005039 // the original declaration to note that it is an explicit specialization
5040 // (if it was previously an implicit instantiation). This latter step
5041 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005042 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005043 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
5044 if (InstantiationFunction->getTemplateSpecializationKind() ==
5045 TSK_ImplicitInstantiation) {
5046 InstantiationFunction->setTemplateSpecializationKind(
5047 TSK_ExplicitSpecialization);
5048 InstantiationFunction->setLocation(Member->getLocation());
5049 }
5050
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005051 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
5052 cast<CXXMethodDecl>(InstantiatedFrom),
5053 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005054 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005055 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005056 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
5057 if (InstantiationVar->getTemplateSpecializationKind() ==
5058 TSK_ImplicitInstantiation) {
5059 InstantiationVar->setTemplateSpecializationKind(
5060 TSK_ExplicitSpecialization);
5061 InstantiationVar->setLocation(Member->getLocation());
5062 }
5063
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005064 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
5065 cast<VarDecl>(InstantiatedFrom),
5066 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005067 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005068 } else {
5069 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00005070 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
5071 if (InstantiationClass->getTemplateSpecializationKind() ==
5072 TSK_ImplicitInstantiation) {
5073 InstantiationClass->setTemplateSpecializationKind(
5074 TSK_ExplicitSpecialization);
5075 InstantiationClass->setLocation(Member->getLocation());
5076 }
5077
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005078 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00005079 cast<CXXRecordDecl>(InstantiatedFrom),
5080 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005081 }
5082
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005083 // Save the caller the trouble of having to figure out which declaration
5084 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00005085 Previous.clear();
5086 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005087 return false;
5088}
5089
Douglas Gregor558c0322009-10-14 23:41:34 +00005090/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00005091///
5092/// \returns true if a serious error occurs, false otherwise.
5093static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00005094 SourceLocation InstLoc,
5095 bool WasQualifiedName) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005096 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
5097 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregor558c0322009-10-14 23:41:34 +00005098
Douglas Gregor669eed82010-07-13 00:10:04 +00005099 if (CurContext->isRecord()) {
5100 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
5101 << D;
5102 return true;
5103 }
5104
Douglas Gregor558c0322009-10-14 23:41:34 +00005105 // C++0x [temp.explicit]p2:
5106 // An explicit instantiation shall appear in an enclosing namespace of its
5107 // template.
5108 //
5109 // This is DR275, which we do not retroactively apply to C++98/03.
5110 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005111 !CurContext->Encloses(OrigContext)) {
5112 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00005113 S.Diag(InstLoc,
5114 S.getLangOptions().CPlusPlus0x?
5115 diag::err_explicit_instantiation_out_of_scope
5116 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00005117 << D << NS;
5118 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00005119 S.Diag(InstLoc,
5120 S.getLangOptions().CPlusPlus0x?
5121 diag::err_explicit_instantiation_must_be_global
5122 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00005123 << D;
5124 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00005125 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00005126 }
Sebastian Redl7a126a42010-08-31 00:36:30 +00005127
Douglas Gregor558c0322009-10-14 23:41:34 +00005128 // C++0x [temp.explicit]p2:
5129 // If the name declared in the explicit instantiation is an unqualified
5130 // name, the explicit instantiation shall appear in the namespace where
5131 // its template is declared or, if that namespace is inline (7.3.1), any
5132 // namespace from its enclosing namespace set.
5133 if (WasQualifiedName)
Douglas Gregor669eed82010-07-13 00:10:04 +00005134 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005135
5136 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor669eed82010-07-13 00:10:04 +00005137 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005138
Douglas Gregor2166beb2010-05-11 17:39:34 +00005139 S.Diag(InstLoc,
5140 S.getLangOptions().CPlusPlus0x?
5141 diag::err_explicit_instantiation_unqualified_wrong_namespace
5142 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl7a126a42010-08-31 00:36:30 +00005143 << D << OrigContext;
Douglas Gregor558c0322009-10-14 23:41:34 +00005144 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00005145 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00005146}
5147
5148/// \brief Determine whether the given scope specifier has a template-id in it.
5149static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
5150 if (!SS.isSet())
5151 return false;
5152
5153 // C++0x [temp.explicit]p2:
5154 // If the explicit instantiation is for a member function, a member class
5155 // or a static data member of a class template specialization, the name of
5156 // the class template specialization in the qualified-id for the member
5157 // name shall be a simple-template-id.
5158 //
5159 // C++98 has the same restriction, just worded differently.
5160 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
5161 NNS; NNS = NNS->getPrefix())
5162 if (Type *T = NNS->getAsType())
5163 if (isa<TemplateSpecializationType>(T))
5164 return true;
5165
5166 return false;
5167}
5168
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005169// Explicit instantiation of a class template specialization
John McCallf312b1e2010-08-26 23:41:50 +00005170DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005171Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005172 SourceLocation ExternLoc,
5173 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005174 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005175 SourceLocation KWLoc,
5176 const CXXScopeSpec &SS,
5177 TemplateTy TemplateD,
5178 SourceLocation TemplateNameLoc,
5179 SourceLocation LAngleLoc,
5180 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005181 SourceLocation RAngleLoc,
5182 AttributeList *Attr) {
5183 // Find the class template we're specializing
5184 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00005185 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005186 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
5187
5188 // Check that the specialization uses the same tag kind as the
5189 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005190 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5191 assert(Kind != TTK_Enum &&
5192 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005193 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00005194 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005195 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005196 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005197 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00005198 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005199 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00005200 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005201 diag::note_previous_use);
5202 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5203 }
5204
Douglas Gregor558c0322009-10-14 23:41:34 +00005205 // C++0x [temp.explicit]p2:
5206 // There are two forms of explicit instantiation: an explicit instantiation
5207 // definition and an explicit instantiation declaration. An explicit
5208 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00005209 TemplateSpecializationKind TSK
5210 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5211 : TSK_ExplicitInstantiationDeclaration;
5212
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005213 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00005214 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00005215 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005216
5217 // Check that the template argument list is well-formed for this
5218 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00005219 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00005220 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5221 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005222 return true;
5223
Douglas Gregor910f8002010-11-07 23:05:16 +00005224 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005225 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00005226
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005227 // Find the class template specialization declaration that
5228 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005229 void *InsertPos = 0;
5230 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00005231 = ClassTemplate->findSpecialization(Converted.data(),
5232 Converted.size(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005233
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005234 TemplateSpecializationKind PrevDecl_TSK
5235 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5236
Douglas Gregord5cb8762009-10-07 00:13:32 +00005237 // C++0x [temp.explicit]p2:
5238 // [...] An explicit instantiation shall appear in an enclosing
5239 // namespace of its template. [...]
5240 //
5241 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00005242 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5243 SS.isSet()))
5244 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00005245
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005246 ClassTemplateSpecializationDecl *Specialization = 0;
5247
Douglas Gregord78f5982009-11-25 06:01:46 +00005248 bool ReusedDecl = false;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005249 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005250 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00005251 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005252 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005253 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005254 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00005255 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005256
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005257 // Even though HasNoEffect == true means that this explicit instantiation
5258 // has no effect on semantics, we go on to put its syntax in the AST.
5259
5260 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5261 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00005262 // Since the only prior class template specialization with these
5263 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005264 // declaration node as our own, updating the source location
5265 // for the template name to reflect our new declaration.
5266 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00005267 Specialization = PrevDecl;
5268 Specialization->setLocation(TemplateNameLoc);
5269 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00005270 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00005271 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005272 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005273
Douglas Gregor52604ab2009-09-11 21:19:12 +00005274 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005275 // Create a new class template specialization declaration node for
5276 // this explicit specialization.
5277 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00005278 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005279 ClassTemplate->getDeclContext(),
5280 TemplateNameLoc,
5281 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005282 Converted.data(),
5283 Converted.size(),
5284 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00005285 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005286
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005287 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005288 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005289 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005290 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005291 }
5292
5293 // Build the fully-sugared type for this explicit instantiation as
5294 // the user wrote in the explicit instantiation itself. This means
5295 // that we'll pretty-print the type retrieved from the
5296 // specialization's declaration the way that the user actually wrote
5297 // the explicit instantiation, rather than formatting the name based
5298 // on the "canonical" representation used to store the template
5299 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00005300 TypeSourceInfo *WrittenTy
5301 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5302 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005303 Context.getTypeDeclType(Specialization));
5304 Specialization->setTypeAsWritten(WrittenTy);
5305 TemplateArgsIn.release();
5306
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005307 // Set source locations for keywords.
5308 Specialization->setExternLoc(ExternLoc);
5309 Specialization->setTemplateKeywordLoc(TemplateLoc);
5310
5311 // Add the explicit instantiation into its lexical context. However,
5312 // since explicit instantiations are never found by name lookup, we
5313 // just put it into the declaration context directly.
5314 Specialization->setLexicalDeclContext(CurContext);
5315 CurContext->addDecl(Specialization);
5316
5317 // Syntax is now OK, so return if it has no other effect on semantics.
5318 if (HasNoEffect) {
5319 // Set the template specialization kind.
5320 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005321 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00005322 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005323
5324 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005325 // A definition of a class template or class member template
5326 // shall be in scope at the point of the explicit instantiation of
5327 // the class template or class member template.
5328 //
5329 // This check comes when we actually try to perform the
5330 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005331 ClassTemplateSpecializationDecl *Def
5332 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005333 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005334 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005335 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005336 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005337 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005338 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5339 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005340
Douglas Gregor0d035142009-10-27 18:42:08 +00005341 // Instantiate the members of this class template specialization.
5342 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005343 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005344 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00005345 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5346
5347 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5348 // TSK_ExplicitInstantiationDefinition
5349 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5350 TSK == TSK_ExplicitInstantiationDefinition)
5351 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005352
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005353 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005354 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005355
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005356 // Set the template specialization kind.
5357 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005358 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005359}
5360
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005361// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00005362DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005363Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005364 SourceLocation ExternLoc,
5365 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005366 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005367 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005368 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005369 IdentifierInfo *Name,
5370 SourceLocation NameLoc,
5371 AttributeList *Attr) {
5372
Douglas Gregor402abb52009-05-28 23:31:59 +00005373 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00005374 bool IsDependent = false;
John McCallf312b1e2010-08-26 23:41:50 +00005375 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCalld226f652010-08-21 09:40:31 +00005376 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5377 MultiTemplateParamsArg(*this, 0, 0),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00005378 Owned, IsDependent, false, false,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005379 TypeResult());
John McCallc4e70192009-09-11 04:59:25 +00005380 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5381
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005382 if (!TagD)
5383 return true;
5384
John McCalld226f652010-08-21 09:40:31 +00005385 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005386 if (Tag->isEnum()) {
5387 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5388 << Context.getTypeDeclType(Tag);
5389 return true;
5390 }
5391
Douglas Gregord0c87372009-05-27 17:30:49 +00005392 if (Tag->isInvalidDecl())
5393 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00005394
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005395 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5396 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5397 if (!Pattern) {
5398 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5399 << Context.getTypeDeclType(Record);
5400 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5401 return true;
5402 }
5403
Douglas Gregor558c0322009-10-14 23:41:34 +00005404 // C++0x [temp.explicit]p2:
5405 // If the explicit instantiation is for a class or member class, the
5406 // elaborated-type-specifier in the declaration shall include a
5407 // simple-template-id.
5408 //
5409 // C++98 has the same restriction, just worded differently.
5410 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00005411 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005412 << Record << SS.getRange();
5413
5414 // C++0x [temp.explicit]p2:
5415 // There are two forms of explicit instantiation: an explicit instantiation
5416 // definition and an explicit instantiation declaration. An explicit
5417 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00005418 TemplateSpecializationKind TSK
5419 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5420 : TSK_ExplicitInstantiationDeclaration;
5421
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005422 // C++0x [temp.explicit]p2:
5423 // [...] An explicit instantiation shall appear in an enclosing
5424 // namespace of its template. [...]
5425 //
5426 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00005427 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00005428
5429 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00005430 CXXRecordDecl *PrevDecl
5431 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00005432 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00005433 PrevDecl = Record;
5434 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00005435 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005436 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00005437 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00005438 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00005439 PrevDecl,
5440 MSInfo->getTemplateSpecializationKind(),
5441 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005442 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005443 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005444 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00005445 return TagD;
5446 }
5447
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005448 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00005449 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005450 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005451 // C++ [temp.explicit]p3:
5452 // A definition of a member class of a class template shall be in scope
5453 // at the point of an explicit instantiation of the member class.
5454 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00005455 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005456 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00005457 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5458 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005459 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5460 << Pattern;
5461 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00005462 } else {
5463 if (InstantiateClass(NameLoc, Record, Def,
5464 getTemplateInstantiationArgs(Record),
5465 TSK))
5466 return true;
5467
Douglas Gregor952b0172010-02-11 01:04:33 +00005468 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00005469 if (!RecordDef)
5470 return true;
5471 }
5472 }
5473
5474 // Instantiate all of the members of the class.
5475 InstantiateClassMembers(NameLoc, RecordDef,
5476 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005477
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005478 if (TSK == TSK_ExplicitInstantiationDefinition)
5479 MarkVTableUsed(NameLoc, RecordDef, true);
5480
Mike Stump390b4cc2009-05-16 07:39:55 +00005481 // FIXME: We don't have any representation for explicit instantiations of
5482 // member classes. Such a representation is not needed for compilation, but it
5483 // should be available for clients that want to see all of the declarations in
5484 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005485 return TagD;
5486}
5487
John McCallf312b1e2010-08-26 23:41:50 +00005488DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5489 SourceLocation ExternLoc,
5490 SourceLocation TemplateLoc,
5491 Declarator &D) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005492 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00005493 // TODO: check if/when DNInfo should replace Name.
5494 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5495 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005496 if (!Name) {
5497 if (!D.isInvalidType())
5498 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5499 diag::err_explicit_instantiation_requires_name)
5500 << D.getDeclSpec().getSourceRange()
5501 << D.getSourceRange();
5502
5503 return true;
5504 }
5505
5506 // The scope passed in may not be a decl scope. Zip up the scope tree until
5507 // we find one that is.
5508 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5509 (S->getFlags() & Scope::TemplateParamScope) != 0)
5510 S = S->getParent();
5511
5512 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00005513 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5514 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005515 if (R.isNull())
5516 return true;
5517
5518 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5519 // Cannot explicitly instantiate a typedef.
5520 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5521 << Name;
5522 return true;
5523 }
5524
Douglas Gregor663b5a02009-10-14 20:14:33 +00005525 // C++0x [temp.explicit]p1:
5526 // [...] An explicit instantiation of a function template shall not use the
5527 // inline or constexpr specifiers.
5528 // Presumably, this also applies to member functions of class templates as
5529 // well.
5530 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5531 Diag(D.getDeclSpec().getInlineSpecLoc(),
5532 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00005533 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00005534
5535 // FIXME: check for constexpr specifier.
5536
Douglas Gregor558c0322009-10-14 23:41:34 +00005537 // C++0x [temp.explicit]p2:
5538 // There are two forms of explicit instantiation: an explicit instantiation
5539 // definition and an explicit instantiation declaration. An explicit
5540 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00005541 TemplateSpecializationKind TSK
5542 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5543 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00005544
Abramo Bagnara25777432010-08-11 22:01:17 +00005545 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005546 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005547
5548 if (!R->isFunctionType()) {
5549 // C++ [temp.explicit]p1:
5550 // A [...] static data member of a class template can be explicitly
5551 // instantiated from the member definition associated with its class
5552 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00005553 if (Previous.isAmbiguous())
5554 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005555
John McCall1bcee0a2009-12-02 08:25:40 +00005556 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005557 if (!Prev || !Prev->isStaticDataMember()) {
5558 // We expect to see a data data member here.
5559 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5560 << Name;
5561 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5562 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00005563 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005564 return true;
5565 }
5566
5567 if (!Prev->getInstantiatedFromStaticDataMember()) {
5568 // FIXME: Check for explicit specialization?
5569 Diag(D.getIdentifierLoc(),
5570 diag::err_explicit_instantiation_data_member_not_instantiated)
5571 << Prev;
5572 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5573 // FIXME: Can we provide a note showing where this was declared?
5574 return true;
5575 }
5576
Douglas Gregor558c0322009-10-14 23:41:34 +00005577 // C++0x [temp.explicit]p2:
5578 // If the explicit instantiation is for a member function, a member class
5579 // or a static data member of a class template specialization, the name of
5580 // the class template specialization in the qualified-id for the member
5581 // name shall be a simple-template-id.
5582 //
5583 // C++98 has the same restriction, just worded differently.
5584 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5585 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005586 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005587 << Prev << D.getCXXScopeSpec().getRange();
5588
5589 // Check the scope of this explicit instantiation.
5590 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5591
Douglas Gregor454885e2009-10-15 15:54:05 +00005592 // Verify that it is okay to explicitly instantiate here.
5593 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5594 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005595 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005596 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005597 MSInfo->getTemplateSpecializationKind(),
5598 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005599 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005600 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005601 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005602 return (Decl*) 0;
Douglas Gregor454885e2009-10-15 15:54:05 +00005603
Douglas Gregord5a423b2009-09-25 18:43:00 +00005604 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005605 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005606 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005607 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005608
5609 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00005610 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005611 }
5612
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005613 // If the declarator is a template-id, translate the parser's template
5614 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005615 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005616 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005617 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5618 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005619 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5620 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005621 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5622 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005623 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005624 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005625 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005626 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005627 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005628
Douglas Gregord5a423b2009-09-25 18:43:00 +00005629 // C++ [temp.explicit]p1:
5630 // A [...] function [...] can be explicitly instantiated from its template.
5631 // A member function [...] of a class template can be explicitly
5632 // instantiated from the member definition associated with its class
5633 // template.
John McCallc373d482010-01-27 01:50:18 +00005634 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005635 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5636 P != PEnd; ++P) {
5637 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005638 if (!HasExplicitTemplateArgs) {
5639 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5640 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5641 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005642
John McCallc373d482010-01-27 01:50:18 +00005643 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005644 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5645 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005646 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005647 }
5648 }
5649
5650 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5651 if (!FunTmpl)
5652 continue;
5653
John McCall5769d612010-02-08 23:07:23 +00005654 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005655 FunctionDecl *Specialization = 0;
5656 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005657 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005658 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005659 R, Specialization, Info)) {
5660 // FIXME: Keep track of almost-matches?
5661 (void)TDK;
5662 continue;
5663 }
5664
John McCallc373d482010-01-27 01:50:18 +00005665 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005666 }
5667
5668 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005669 UnresolvedSetIterator Result
Douglas Gregor5c7bf422011-01-11 17:34:58 +00005670 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005671 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005672 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5673 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5674 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005675
John McCallc373d482010-01-27 01:50:18 +00005676 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005677 return true;
John McCallc373d482010-01-27 01:50:18 +00005678
5679 // Ignore access control bits, we don't need them for redeclaration checking.
5680 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005681
Douglas Gregor0a897e32009-10-15 17:21:20 +00005682 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005683 Diag(D.getIdentifierLoc(),
5684 diag::err_explicit_instantiation_member_function_not_instantiated)
5685 << Specialization
5686 << (Specialization->getTemplateSpecializationKind() ==
5687 TSK_ExplicitSpecialization);
5688 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5689 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005690 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005691
Douglas Gregor0a897e32009-10-15 17:21:20 +00005692 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005693 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5694 PrevDecl = Specialization;
5695
Douglas Gregor0a897e32009-10-15 17:21:20 +00005696 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005697 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005698 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005699 PrevDecl,
5700 PrevDecl->getTemplateSpecializationKind(),
5701 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005702 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00005703 return true;
5704
5705 // FIXME: We may still want to build some representation of this
5706 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005707 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005708 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005709 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005710
5711 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005712
5713 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005714 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005715
Douglas Gregor558c0322009-10-14 23:41:34 +00005716 // C++0x [temp.explicit]p2:
5717 // If the explicit instantiation is for a member function, a member class
5718 // or a static data member of a class template specialization, the name of
5719 // the class template specialization in the qualified-id for the member
5720 // name shall be a simple-template-id.
5721 //
5722 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005723 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005724 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005725 D.getCXXScopeSpec().isSet() &&
5726 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5727 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005728 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005729 << Specialization << D.getCXXScopeSpec().getRange();
5730
5731 CheckExplicitInstantiationScope(*this,
5732 FunTmpl? (NamedDecl *)FunTmpl
5733 : Specialization->getInstantiatedFromMemberFunction(),
5734 D.getIdentifierLoc(),
5735 D.getCXXScopeSpec().isSet());
5736
Douglas Gregord5a423b2009-09-25 18:43:00 +00005737 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00005738 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005739}
5740
John McCallf312b1e2010-08-26 23:41:50 +00005741TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005742Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5743 const CXXScopeSpec &SS, IdentifierInfo *Name,
5744 SourceLocation TagLoc, SourceLocation NameLoc) {
5745 // This has to hold, because SS is expected to be defined.
5746 assert(Name && "Expected a name in a dependent tag");
5747
5748 NestedNameSpecifier *NNS
5749 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5750 if (!NNS)
5751 return true;
5752
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005753 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005754
Douglas Gregor48c89f42010-04-24 16:38:41 +00005755 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5756 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005757 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005758 return true;
5759 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005760
5761 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallb3d87482010-08-24 05:47:05 +00005762 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCallc4e70192009-09-11 04:59:25 +00005763}
5764
John McCallf312b1e2010-08-26 23:41:50 +00005765TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005766Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5767 const CXXScopeSpec &SS, const IdentifierInfo &II,
5768 SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005769 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005770 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5771 if (!NNS)
5772 return true;
5773
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005774 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5775 !getLangOptions().CPlusPlus0x)
5776 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5777 << FixItHint::CreateRemoval(TypenameLoc);
5778
Douglas Gregor107de902010-04-24 15:35:55 +00005779 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005780 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005781 if (T.isNull())
5782 return true;
John McCall63b43852010-04-29 23:50:39 +00005783
5784 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5785 if (isa<DependentNameType>(T)) {
5786 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005787 TL.setKeywordLoc(TypenameLoc);
5788 TL.setQualifierRange(SS.getRange());
5789 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005790 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005791 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005792 TL.setKeywordLoc(TypenameLoc);
5793 TL.setQualifierRange(SS.getRange());
5794 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005795 }
5796
John McCallb3d87482010-08-24 05:47:05 +00005797 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00005798}
5799
John McCallf312b1e2010-08-26 23:41:50 +00005800TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005801Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5802 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallb3d87482010-08-24 05:47:05 +00005803 ParsedType Ty) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005804 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5805 !getLangOptions().CPlusPlus0x)
5806 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5807 << FixItHint::CreateRemoval(TypenameLoc);
5808
John McCall4e449832010-05-28 23:32:21 +00005809 TypeSourceInfo *InnerTSI = 0;
5810 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCall4e449832010-05-28 23:32:21 +00005811
5812 assert(isa<TemplateSpecializationType>(T) &&
5813 "Expected a template specialization type");
Douglas Gregor17343172009-04-01 00:28:59 +00005814
Douglas Gregor6946baf2009-09-02 13:05:45 +00005815 if (computeDeclContext(SS, false)) {
5816 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005817 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005818 // track of the nested-name-specifier.
John McCall4e449832010-05-28 23:32:21 +00005819
5820 // Push the inner type, preserving its source locations if possible.
5821 TypeLocBuilder Builder;
5822 if (InnerTSI)
5823 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5824 else
5825 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5826
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005827 /* Note: NNS already embedded in template specialization type T. */
5828 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCall4e449832010-05-28 23:32:21 +00005829 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5830 TL.setKeywordLoc(TypenameLoc);
5831 TL.setQualifierRange(SS.getRange());
5832
5833 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallb3d87482010-08-24 05:47:05 +00005834 return CreateParsedType(T, TSI);
Douglas Gregor6946baf2009-09-02 13:05:45 +00005835 }
Mike Stump1eb44332009-09-09 15:08:12 +00005836
John McCall33500952010-06-11 00:33:02 +00005837 // TODO: it's really silly that we make a template specialization
5838 // type earlier only to drop it again here.
5839 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5840 DependentTemplateName *DTN =
5841 TST->getTemplateName().getAsDependentTemplateName();
5842 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005843 assert(DTN->getQualifier()
5844 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5845 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5846 DTN->getQualifier(),
John McCall33500952010-06-11 00:33:02 +00005847 DTN->getIdentifier(),
5848 TST->getNumArgs(),
5849 TST->getArgs());
John McCall63b43852010-04-29 23:50:39 +00005850 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCall33500952010-06-11 00:33:02 +00005851 DependentTemplateSpecializationTypeLoc TL =
5852 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5853 if (InnerTSI) {
5854 TemplateSpecializationTypeLoc TSTL =
5855 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5856 TL.setLAngleLoc(TSTL.getLAngleLoc());
5857 TL.setRAngleLoc(TSTL.getRAngleLoc());
5858 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5859 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5860 } else {
5861 TL.initializeLocal(SourceLocation());
5862 }
John McCall4e449832010-05-28 23:32:21 +00005863 TL.setKeywordLoc(TypenameLoc);
5864 TL.setQualifierRange(SS.getRange());
John McCallb3d87482010-08-24 05:47:05 +00005865 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00005866}
5867
Douglas Gregord57959a2009-03-27 23:10:48 +00005868/// \brief Build the type that describes a C++ typename specifier,
5869/// e.g., "typename T::type".
5870QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005871Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5872 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005873 SourceLocation KeywordLoc, SourceRange NNSRange,
5874 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005875 CXXScopeSpec SS;
5876 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005877 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005878
John McCall77bb1aa2010-05-01 00:40:08 +00005879 DeclContext *Ctx = computeDeclContext(SS);
5880 if (!Ctx) {
5881 // If the nested-name-specifier is dependent and couldn't be
5882 // resolved to a type, build a typename type.
5883 assert(NNS->isDependent());
5884 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005885 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005886
John McCall77bb1aa2010-05-01 00:40:08 +00005887 // If the nested-name-specifier refers to the current instantiation,
5888 // the "typename" keyword itself is superfluous. In C++03, the
5889 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5890 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00005891 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005892
John McCall77bb1aa2010-05-01 00:40:08 +00005893 if (RequireCompleteDeclContext(SS, Ctx))
5894 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005895
5896 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005897 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005898 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005899 unsigned DiagID = 0;
5900 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005901 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005902 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005903 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005904 break;
Douglas Gregord9545042010-12-09 00:06:27 +00005905
5906 case LookupResult::FoundUnresolvedValue: {
5907 // We found a using declaration that is a value. Most likely, the using
5908 // declaration itself is meant to have the 'typename' keyword.
5909 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5910 IILoc);
5911 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
5912 << Name << Ctx << FullRange;
5913 if (UnresolvedUsingValueDecl *Using
5914 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
5915 SourceLocation Loc = Using->getTargetNestedNameRange().getBegin();
5916 Diag(Loc, diag::note_using_value_decl_missing_typename)
5917 << FixItHint::CreateInsertion(Loc, "typename ");
5918 }
5919 }
5920 // Fall through to create a dependent typename type, from which we can recover
5921 // better.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005922
5923 case LookupResult::NotFoundInCurrentInstantiation:
5924 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005925 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005926
5927 case LookupResult::Found:
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005928 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005929 // We found a type. Build an ElaboratedType, since the
5930 // typename-specifier was just sugar.
5931 return Context.getElaboratedType(ETK_Typename, NNS,
5932 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005933 }
5934
5935 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005936 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005937 break;
5938
Douglas Gregord9545042010-12-09 00:06:27 +00005939
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005940 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005941 return QualType();
5942
Douglas Gregord57959a2009-03-27 23:10:48 +00005943 case LookupResult::FoundOverloaded:
5944 DiagID = diag::err_typename_nested_not_type;
5945 Referenced = *Result.begin();
5946 break;
5947
John McCall6e247262009-10-10 05:48:19 +00005948 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005949 return QualType();
5950 }
5951
5952 // If we get here, it's because name lookup did not find a
5953 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005954 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5955 IILoc);
5956 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005957 if (Referenced)
5958 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5959 << Name;
5960 return QualType();
5961}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005962
5963namespace {
5964 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005965 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005966 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005967 SourceLocation Loc;
5968 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005969
Douglas Gregor4a959d82009-08-06 16:20:37 +00005970 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005971 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5972
Mike Stump1eb44332009-09-09 15:08:12 +00005973 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005974 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005975 DeclarationName Entity)
5976 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005977 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005978
5979 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005980 /// transformed.
5981 ///
5982 /// For the purposes of type reconstruction, a type has already been
5983 /// transformed if it is NULL or if it is not dependent.
5984 bool AlreadyTransformed(QualType T) {
5985 return T.isNull() || !T->isDependentType();
5986 }
Mike Stump1eb44332009-09-09 15:08:12 +00005987
5988 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005989 /// rebuilt.
5990 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005991
Douglas Gregor4a959d82009-08-06 16:20:37 +00005992 /// \brief Returns the name of the entity whose type is being rebuilt.
5993 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005994
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005995 /// \brief Sets the "base" location and entity when that
5996 /// information is known based on another transformation.
5997 void setBase(SourceLocation Loc, DeclarationName Entity) {
5998 this->Loc = Loc;
5999 this->Entity = Entity;
6000 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00006001 };
6002}
6003
Douglas Gregor4a959d82009-08-06 16:20:37 +00006004/// \brief Rebuilds a type within the context of the current instantiation.
6005///
Mike Stump1eb44332009-09-09 15:08:12 +00006006/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00006007/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00006008/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00006009/// partial specialization thereof). This routine will rebuild that type now
6010/// that we have entered the declarator's scope, which may produce different
6011/// canonical types, e.g.,
6012///
6013/// \code
6014/// template<typename T>
6015/// struct X {
6016/// typedef T* pointer;
6017/// pointer data();
6018/// };
6019///
6020/// template<typename T>
6021/// typename X<T>::pointer X<T>::data() { ... }
6022/// \endcode
6023///
Douglas Gregor4714c122010-03-31 17:34:00 +00006024/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00006025/// since we do not know that we can look into X<T> when we parsed the type.
6026/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006027/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00006028/// as the canonical type of T*, allowing the return types of the out-of-line
6029/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00006030TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6031 SourceLocation Loc,
6032 DeclarationName Name) {
6033 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00006034 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00006035
Douglas Gregor4a959d82009-08-06 16:20:37 +00006036 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
6037 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00006038}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006039
John McCall60d7b3a2010-08-24 06:29:42 +00006040ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00006041 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
6042 DeclarationName());
6043 return Rebuilder.TransformExpr(E);
6044}
6045
John McCall63b43852010-04-29 23:50:39 +00006046bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
6047 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00006048
6049 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6050 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
6051 DeclarationName());
6052 NestedNameSpecifier *Rebuilt =
6053 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00006054 if (!Rebuilt) return true;
6055
6056 SS.setScopeRep(Rebuilt);
6057 return false;
John McCall31f17ec2010-04-27 00:57:59 +00006058}
6059
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006060/// \brief Produces a formatted string that describes the binding of
6061/// template parameters to template arguments.
6062std::string
6063Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6064 const TemplateArgumentList &Args) {
Douglas Gregor910f8002010-11-07 23:05:16 +00006065 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006066}
6067
6068std::string
6069Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6070 const TemplateArgument *Args,
6071 unsigned NumArgs) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006072 llvm::SmallString<128> Str;
6073 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006074
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006075 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00006076 return std::string();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006077
6078 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006079 if (I >= NumArgs)
6080 break;
6081
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006082 if (I == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00006083 Out << "[with ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006084 else
Douglas Gregor87dd6972010-12-20 16:52:59 +00006085 Out << ", ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006086
6087 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006088 Out << Id->getName();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006089 } else {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006090 Out << '$' << I;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006091 }
6092
Douglas Gregor87dd6972010-12-20 16:52:59 +00006093 Out << " = ";
6094 Args[I].print(Context.PrintingPolicy, Out);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006095 }
Douglas Gregor87dd6972010-12-20 16:52:59 +00006096
6097 Out << ']';
6098 return Out.str();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006099}
Douglas Gregord0937222010-12-13 22:49:22 +00006100