blob: 4ac8a6c21c3d3a4f702a38eb9c1dcdf1ff3e90d9 [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
John McCall2d887082010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000014#include "clang/Sema/Scope.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000017#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000019#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000020#include "clang/AST/ExprCXX.h"
John McCall92b7f702010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000022#include "clang/AST/DeclTemplate.h"
John McCall4e2cbb22010-10-20 05:44:58 +000023#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor5f3aeb62010-10-13 00:27:52 +000024#include "clang/AST/TypeVisitor.h"
John McCall19510852010-08-20 18:27:03 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000027#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000029#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000030using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000031using namespace sema;
Douglas Gregor72c3f312008-12-05 18:15:24 +000032
John McCall78b81052010-11-10 02:40:36 +000033// Exported for use by Parser.
34SourceRange
35clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
36 unsigned N) {
37 if (!N) return SourceRange();
38 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
39}
40
Douglas Gregor2dd078a2009-09-02 22:59:36 +000041/// \brief Determine whether the declaration found is acceptable as the name
42/// of a template and, if so, return that template declaration. Otherwise,
43/// returns NULL.
John McCallad00b772010-06-16 08:42:20 +000044static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
45 NamedDecl *Orig) {
46 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000047
Douglas Gregor2dd078a2009-09-02 22:59:36 +000048 if (isa<TemplateDecl>(D))
John McCallad00b772010-06-16 08:42:20 +000049 return Orig;
Mike Stump1eb44332009-09-09 15:08:12 +000050
Douglas Gregor2dd078a2009-09-02 22:59:36 +000051 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
52 // C++ [temp.local]p1:
53 // Like normal (non-template) classes, class templates have an
54 // injected-class-name (Clause 9). The injected-class-name
55 // can be used with or without a template-argument-list. When
56 // it is used without a template-argument-list, it is
57 // equivalent to the injected-class-name followed by the
58 // template-parameters of the class template enclosed in
59 // <>. When it is used with a template-argument-list, it
60 // refers to the specified class template specialization,
61 // which could be the current specialization or another
62 // specialization.
63 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000064 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000065 if (Record->getDescribedClassTemplate())
66 return Record->getDescribedClassTemplate();
67
68 if (ClassTemplateSpecializationDecl *Spec
69 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
70 return Spec->getSpecializedTemplate();
71 }
Mike Stump1eb44332009-09-09 15:08:12 +000072
Douglas Gregor2dd078a2009-09-02 22:59:36 +000073 return 0;
74 }
Mike Stump1eb44332009-09-09 15:08:12 +000075
Douglas Gregor2dd078a2009-09-02 22:59:36 +000076 return 0;
77}
78
John McCallf7a1a742009-11-24 19:00:30 +000079static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor01e56ae2010-04-12 20:54:26 +000080 // The set of class templates we've already seen.
81 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCallf7a1a742009-11-24 19:00:30 +000082 LookupResult::Filter filter = R.makeFilter();
83 while (filter.hasNext()) {
84 NamedDecl *Orig = filter.next();
John McCallad00b772010-06-16 08:42:20 +000085 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCallf7a1a742009-11-24 19:00:30 +000086 if (!Repl)
87 filter.erase();
Douglas Gregor01e56ae2010-04-12 20:54:26 +000088 else if (Repl != Orig) {
89
90 // C++ [temp.local]p3:
91 // A lookup that finds an injected-class-name (10.2) can result in an
92 // ambiguity in certain cases (for example, if it is found in more than
93 // one base class). If all of the injected-class-names that are found
94 // refer to specializations of the same class template, and if the name
95 // is followed by a template-argument-list, the reference refers to the
96 // class template itself and not a specialization thereof, and is not
97 // ambiguous.
98 //
99 // FIXME: Will we eventually have to do the same for alias templates?
100 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
101 if (!ClassTemplates.insert(ClassTmpl)) {
102 filter.erase();
103 continue;
104 }
John McCall8ba66912010-08-13 07:02:08 +0000105
106 // FIXME: we promote access to public here as a workaround to
107 // the fact that LookupResult doesn't let us remember that we
108 // found this template through a particular injected class name,
109 // which means we end up doing nasty things to the invariants.
110 // Pretending that access is public is *much* safer.
111 filter.replace(Repl, AS_public);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000112 }
John McCallf7a1a742009-11-24 19:00:30 +0000113 }
114 filter.done();
115}
116
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000117TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000118 CXXScopeSpec &SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000119 bool hasTemplateKeyword,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000120 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +0000121 ParsedType ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000122 bool EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000123 TemplateTy &TemplateResult,
124 bool &MemberOfUnknownSpecialization) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000125 assert(getLangOptions().CPlusPlus && "No template names in C!");
126
Douglas Gregor014e88d2009-11-03 23:16:33 +0000127 DeclarationName TName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000128 MemberOfUnknownSpecialization = false;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000129
130 switch (Name.getKind()) {
131 case UnqualifiedId::IK_Identifier:
132 TName = DeclarationName(Name.Identifier);
133 break;
134
135 case UnqualifiedId::IK_OperatorFunctionId:
136 TName = Context.DeclarationNames.getCXXOperatorName(
137 Name.OperatorFunctionId.Operator);
138 break;
139
Sean Hunte6252d12009-11-28 08:58:14 +0000140 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000141 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
142 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000143
Douglas Gregor014e88d2009-11-03 23:16:33 +0000144 default:
145 return TNK_Non_template;
146 }
Mike Stump1eb44332009-09-09 15:08:12 +0000147
John McCallb3d87482010-08-24 05:47:05 +0000148 QualType ObjectType = ObjectTypePtr.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Douglas Gregorbfea2392009-12-31 08:11:17 +0000150 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
151 LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000152 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
153 MemberOfUnknownSpecialization);
John McCall67d22fb2010-08-28 20:17:00 +0000154 if (R.empty()) return TNK_Non_template;
155 if (R.isAmbiguous()) {
156 // Suppress diagnostics; we'll redo this lookup later.
John McCallb8592062010-08-13 02:23:42 +0000157 R.suppressDiagnostics();
John McCall67d22fb2010-08-28 20:17:00 +0000158
159 // FIXME: we might have ambiguous templates, in which case we
160 // should at least parse them properly!
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000161 return TNK_Non_template;
John McCallb8592062010-08-13 02:23:42 +0000162 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000163
John McCall0bd6feb2009-12-02 08:04:21 +0000164 TemplateName Template;
165 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000166
John McCall0bd6feb2009-12-02 08:04:21 +0000167 unsigned ResultCount = R.end() - R.begin();
168 if (ResultCount > 1) {
169 // We assume that we'll preserve the qualifier from a function
170 // template name in other ways.
171 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
172 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000173
174 // We'll do this lookup again later.
175 R.suppressDiagnostics();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000176 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000177 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
178
179 if (SS.isSet() && !SS.isInvalid()) {
180 NestedNameSpecifier *Qualifier
181 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c153532010-08-06 12:11:11 +0000182 Template = Context.getQualifiedTemplateName(Qualifier,
183 hasTemplateKeyword, TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000184 } else {
185 Template = TemplateName(TD);
186 }
187
John McCallb8592062010-08-13 02:23:42 +0000188 if (isa<FunctionTemplateDecl>(TD)) {
John McCall0bd6feb2009-12-02 08:04:21 +0000189 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000190
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
193 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000194 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
195 TemplateKind = TNK_Type_template;
196 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000197 }
Mike Stump1eb44332009-09-09 15:08:12 +0000198
John McCall0bd6feb2009-12-02 08:04:21 +0000199 TemplateResult = TemplateTy::make(Template);
200 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000201}
202
Douglas Gregor84d0a192010-01-12 21:28:44 +0000203bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
204 SourceLocation IILoc,
205 Scope *S,
206 const CXXScopeSpec *SS,
207 TemplateTy &SuggestedTemplate,
208 TemplateNameKind &SuggestedKind) {
209 // We can't recover unless there's a dependent scope specifier preceding the
210 // template name.
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000211 // FIXME: Typo correction?
Douglas Gregor84d0a192010-01-12 21:28:44 +0000212 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
213 computeDeclContext(*SS))
214 return false;
215
216 // The code is missing a 'template' keyword prior to the dependent template
217 // name.
218 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
219 Diag(IILoc, diag::err_template_kw_missing)
220 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000221 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor84d0a192010-01-12 21:28:44 +0000222 SuggestedTemplate
223 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
224 SuggestedKind = TNK_Dependent_template_name;
225 return true;
226}
227
John McCallf7a1a742009-11-24 19:00:30 +0000228void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000229 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000230 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000231 bool EnteringContext,
232 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000233 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000234 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-11-24 19:00:30 +0000235 DeclContext *LookupCtx = 0;
236 bool isDependent = false;
237 if (!ObjectType.isNull()) {
238 // This nested-name-specifier occurs in a member access expression, e.g.,
239 // x->B::f, and we are looking into the type of the object.
240 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
241 LookupCtx = computeDeclContext(ObjectType);
242 isDependent = ObjectType->isDependentType();
243 assert((isDependent || !ObjectType->isIncompleteType()) &&
244 "Caller should have completed object type");
245 } else if (SS.isSet()) {
246 // This nested-name-specifier occurs after another nested-name-specifier,
247 // so long into the context associated with the prior nested-name-specifier.
248 LookupCtx = computeDeclContext(SS, EnteringContext);
249 isDependent = isDependentScopeSpecifier(SS);
250
251 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000252 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000253 return;
254 }
255
256 bool ObjectTypeSearchedInScope = false;
257 if (LookupCtx) {
258 // Perform "qualified" name lookup into the declaration context we
259 // computed, which is either the type of the base of a member access
260 // expression or the declaration context associated with a prior
261 // nested-name-specifier.
262 LookupQualifiedName(Found, LookupCtx);
263
264 if (!ObjectType.isNull() && Found.empty()) {
265 // C++ [basic.lookup.classref]p1:
266 // In a class member access expression (5.2.5), if the . or -> token is
267 // immediately followed by an identifier followed by a <, the
268 // identifier must be looked up to determine whether the < is the
269 // beginning of a template argument list (14.2) or a less-than operator.
270 // The identifier is first looked up in the class of the object
271 // expression. If the identifier is not found, it is then looked up in
272 // the context of the entire postfix-expression and shall name a class
273 // or function template.
John McCallf7a1a742009-11-24 19:00:30 +0000274 if (S) LookupName(Found, S);
275 ObjectTypeSearchedInScope = true;
276 }
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000277 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000278 // We cannot look into a dependent object type or nested nme
279 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000280 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000281 return;
282 } else {
283 // Perform unqualified name lookup in the current scope.
284 LookupName(Found, S);
285 }
286
Douglas Gregor2e933882010-01-12 17:06:20 +0000287 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000288 // If we did not find any names, attempt to correct any typos.
289 DeclarationName Name = Found.getLookupName();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000290 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000291 false, CTC_CXXCasts)) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000292 FilterAcceptableTemplateNames(Context, Found);
John McCallad00b772010-06-16 08:42:20 +0000293 if (!Found.empty()) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000294 if (LookupCtx)
295 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
296 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000297 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000298 Found.getLookupName().getAsString());
299 else
300 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
301 << Name << Found.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000302 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000303 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000304 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
305 Diag(Template->getLocation(), diag::note_previous_decl)
306 << Template->getDeclName();
John McCallad00b772010-06-16 08:42:20 +0000307 }
Douglas Gregorbfea2392009-12-31 08:11:17 +0000308 } else {
309 Found.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000310 Found.setLookupName(Name);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000311 }
312 }
313
John McCallf7a1a742009-11-24 19:00:30 +0000314 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000315 if (Found.empty()) {
316 if (isDependent)
317 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000318 return;
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000319 }
John McCallf7a1a742009-11-24 19:00:30 +0000320
321 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
322 // C++ [basic.lookup.classref]p1:
323 // [...] If the lookup in the class of the object expression finds a
324 // template, the name is also looked up in the context of the entire
325 // postfix-expression and [...]
326 //
327 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
328 LookupOrdinaryName);
329 LookupName(FoundOuter, S);
330 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000331
John McCallf7a1a742009-11-24 19:00:30 +0000332 if (FoundOuter.empty()) {
333 // - if the name is not found, the name found in the class of the
334 // object expression is used, otherwise
335 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
336 // - if the name is found in the context of the entire
337 // postfix-expression and does not name a class template, the name
338 // found in the class of the object expression is used, otherwise
John McCallad00b772010-06-16 08:42:20 +0000339 } else if (!Found.isSuppressingDiagnostics()) {
John McCallf7a1a742009-11-24 19:00:30 +0000340 // - if the name found is a class template, it must refer to the same
341 // entity as the one found in the class of the object expression,
342 // otherwise the program is ill-formed.
343 if (!Found.isSingleResult() ||
344 Found.getFoundDecl()->getCanonicalDecl()
345 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
346 Diag(Found.getNameLoc(),
Jeffrey Yasskin21d07e42010-06-05 01:39:57 +0000347 diag::ext_nested_name_member_ref_lookup_ambiguous)
348 << Found.getLookupName()
349 << ObjectType;
John McCallf7a1a742009-11-24 19:00:30 +0000350 Diag(Found.getRepresentativeDecl()->getLocation(),
351 diag::note_ambig_member_ref_object_type)
352 << ObjectType;
353 Diag(FoundOuter.getFoundDecl()->getLocation(),
354 diag::note_ambig_member_ref_scope);
355
356 // Recover by taking the template that we found in the object
357 // expression's type.
358 }
359 }
360 }
361}
362
John McCall2f841ba2009-12-02 03:53:29 +0000363/// ActOnDependentIdExpression - Handle a dependent id-expression that
364/// was just parsed. This is only possible with an explicit scope
365/// specifier naming a dependent type.
John McCall60d7b3a2010-08-24 06:29:42 +0000366ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000367Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000368 const DeclarationNameInfo &NameInfo,
John McCall2f841ba2009-12-02 03:53:29 +0000369 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000370 const TemplateArgumentListInfo *TemplateArgs) {
371 NestedNameSpecifier *Qualifier
372 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallea1471e2010-05-20 01:18:31 +0000373
374 DeclContext *DC = getFunctionLevelDeclContext();
John McCallf7a1a742009-11-24 19:00:30 +0000375
John McCall2f841ba2009-12-02 03:53:29 +0000376 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000377 isa<CXXMethodDecl>(DC) &&
378 cast<CXXMethodDecl>(DC)->isInstance()) {
379 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2f841ba2009-12-02 03:53:29 +0000380
John McCallf7a1a742009-11-24 19:00:30 +0000381 // Since the 'this' expression is synthesized, we don't need to
382 // perform the double-lookup check.
383 NamedDecl *FirstQualifierInScope = 0;
384
John McCallaa81e162009-12-01 22:10:20 +0000385 return Owned(CXXDependentScopeMemberExpr::Create(Context,
386 /*This*/ 0, ThisType,
387 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000388 /*Op*/ SourceLocation(),
389 Qualifier, SS.getRange(),
390 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +0000391 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000392 TemplateArgs));
393 }
394
Abramo Bagnara25777432010-08-11 22:01:17 +0000395 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +0000396}
397
John McCall60d7b3a2010-08-24 06:29:42 +0000398ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000399Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000400 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000401 const TemplateArgumentListInfo *TemplateArgs) {
402 return Owned(DependentScopeDeclRefExpr::Create(Context,
403 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
404 SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +0000405 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000406 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000407}
408
Douglas Gregor72c3f312008-12-05 18:15:24 +0000409/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
410/// that the template parameter 'PrevDecl' is being shadowed by a new
411/// declaration at location Loc. Returns true to indicate that this is
412/// an error, and false otherwise.
413bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000414 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000415
416 // Microsoft Visual C++ permits template parameters to be shadowed.
417 if (getLangOptions().Microsoft)
418 return false;
419
420 // C++ [temp.local]p4:
421 // A template-parameter shall not be redeclared within its
422 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000423 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000424 << cast<NamedDecl>(PrevDecl)->getDeclName();
425 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
426 return true;
427}
428
Douglas Gregor2943aed2009-03-03 04:44:36 +0000429/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000430/// the parameter D to reference the templated declaration and return a pointer
431/// to the template declaration. Otherwise, do nothing to D and return null.
John McCalld226f652010-08-21 09:40:31 +0000432TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
433 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
434 D = Temp->getTemplatedDecl();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000435 return Temp;
436 }
437 return 0;
438}
439
Douglas Gregor788cd062009-11-11 01:00:40 +0000440static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
441 const ParsedTemplateArgument &Arg) {
442
443 switch (Arg.getKind()) {
444 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000445 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000446 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
447 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000448 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000449 return TemplateArgumentLoc(TemplateArgument(T), DI);
450 }
451
452 case ParsedTemplateArgument::NonType: {
453 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
454 return TemplateArgumentLoc(TemplateArgument(E), E);
455 }
456
457 case ParsedTemplateArgument::Template: {
John McCall2b5289b2010-08-23 07:28:44 +0000458 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor788cd062009-11-11 01:00:40 +0000459 return TemplateArgumentLoc(TemplateArgument(Template),
460 Arg.getScopeSpec().getRange(),
461 Arg.getLocation());
462 }
463 }
464
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000465 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000466 return TemplateArgumentLoc();
467}
468
469/// \brief Translates template arguments as provided by the parser
470/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000471void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
472 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000473 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000474 TemplateArgs.addArgument(translateTemplateArgument(*this,
475 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000476}
477
Douglas Gregor72c3f312008-12-05 18:15:24 +0000478/// ActOnTypeParameter - Called when a C++ template type parameter
479/// (e.g., "typename T") has been parsed. Typename specifies whether
480/// the keyword "typename" was used to declare the type parameter
481/// (otherwise, "class" was used), and KeyLoc is the location of the
482/// "class" or "typename" keyword. ParamName is the name of the
483/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregorefed5c82010-06-16 15:23:05 +0000484/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000485/// If the type parameter has a default argument, it will be added
486/// later via ActOnTypeParameterDefault.
John McCalld226f652010-08-21 09:40:31 +0000487Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
488 SourceLocation EllipsisLoc,
489 SourceLocation KeyLoc,
490 IdentifierInfo *ParamName,
491 SourceLocation ParamNameLoc,
492 unsigned Depth, unsigned Position,
493 SourceLocation EqualLoc,
John McCallb3d87482010-08-24 05:47:05 +0000494 ParsedType DefaultArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000495 assert(S->isTemplateParamScope() &&
496 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000497 bool Invalid = false;
498
499 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000500 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000501 LookupOrdinaryName,
502 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000503 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000504 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000505 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000506 }
507
Douglas Gregorddc29e12009-02-06 22:42:48 +0000508 SourceLocation Loc = ParamNameLoc;
509 if (!ParamName)
510 Loc = KeyLoc;
511
Douglas Gregor72c3f312008-12-05 18:15:24 +0000512 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000513 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
514 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000515 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000516 if (Invalid)
517 Param->setInvalidDecl();
518
519 if (ParamName) {
520 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000521 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000522 IdResolver.AddDecl(Param);
523 }
524
Douglas Gregor61c4d282011-01-05 15:48:55 +0000525 // C++0x [temp.param]p9:
526 // A default template-argument may be specified for any kind of
527 // template-parameter that is not a template parameter pack.
528 if (DefaultArg && Ellipsis) {
529 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
530 DefaultArg = ParsedType();
531 }
532
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000533 // Handle the default argument, if provided.
534 if (DefaultArg) {
535 TypeSourceInfo *DefaultTInfo;
536 GetTypeFromParser(DefaultArg, &DefaultTInfo);
537
538 assert(DefaultTInfo && "expected source information for type");
539
Douglas Gregor6f526752010-12-16 08:48:57 +0000540 // Check for unexpanded parameter packs.
541 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
542 UPPC_DefaultArgument))
543 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000544
545 // Check the template argument itself.
546 if (CheckTemplateArgument(Param, DefaultTInfo)) {
547 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000548 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000549 }
550
551 Param->setDefaultArgument(DefaultTInfo, false);
552 }
553
John McCalld226f652010-08-21 09:40:31 +0000554 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000555}
556
Douglas Gregor2943aed2009-03-03 04:44:36 +0000557/// \brief Check that the type of a non-type template parameter is
558/// well-formed.
559///
560/// \returns the (possibly-promoted) parameter type if valid;
561/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000562QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000563Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000564 // We don't allow variably-modified types as the type of non-type template
565 // parameters.
566 if (T->isVariablyModifiedType()) {
567 Diag(Loc, diag::err_variably_modified_nontype_template_param)
568 << T;
569 return QualType();
570 }
571
Douglas Gregor2943aed2009-03-03 04:44:36 +0000572 // C++ [temp.param]p4:
573 //
574 // A non-type template-parameter shall have one of the following
575 // (optionally cv-qualified) types:
576 //
577 // -- integral or enumeration type,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000578 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000579 // -- pointer to object or pointer to function,
Eli Friedman13578692010-08-05 02:49:48 +0000580 T->isPointerType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000581 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000582 T->isReferenceType() ||
583 // -- pointer to member.
584 T->isMemberPointerType() ||
585 // If T is a dependent type, we can't do the check now, so we
586 // assume that it is well-formed.
587 T->isDependentType())
588 return T;
589 // C++ [temp.param]p8:
590 //
591 // A non-type template-parameter of type "array of T" or
592 // "function returning T" is adjusted to be of type "pointer to
593 // T" or "pointer to function returning T", respectively.
594 else if (T->isArrayType())
595 // FIXME: Keep the type prior to promotion?
596 return Context.getArrayDecayedType(T);
597 else if (T->isFunctionType())
598 // FIXME: Keep the type prior to promotion?
599 return Context.getPointerType(T);
Douglas Gregor0fddb972010-05-22 16:17:30 +0000600
Douglas Gregor2943aed2009-03-03 04:44:36 +0000601 Diag(Loc, diag::err_template_nontype_parm_bad_type)
602 << T;
603
604 return QualType();
605}
606
John McCalld226f652010-08-21 09:40:31 +0000607Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
608 unsigned Depth,
609 unsigned Position,
610 SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000611 Expr *Default) {
John McCallbf1a0282010-06-04 23:28:52 +0000612 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
613 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000614
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000615 assert(S->isTemplateParamScope() &&
616 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000617 bool Invalid = false;
618
619 IdentifierInfo *ParamName = D.getIdentifier();
620 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000621 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000622 LookupOrdinaryName,
623 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000624 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000625 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000626 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000627 }
628
Douglas Gregor4d2abba2010-12-16 15:36:43 +0000629 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
630 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000631 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000632 Invalid = true;
633 }
Douglas Gregor781def02010-12-16 08:56:23 +0000634
Douglas Gregor10738d32010-12-23 23:51:58 +0000635 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000636 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000637 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
638 D.getIdentifierLoc(),
Douglas Gregor10738d32010-12-23 23:51:58 +0000639 Depth, Position, ParamName, T,
640 IsParameterPack, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000641 if (Invalid)
642 Param->setInvalidDecl();
643
644 if (D.getIdentifier()) {
645 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000646 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000647 IdResolver.AddDecl(Param);
648 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000649
Douglas Gregor61c4d282011-01-05 15:48:55 +0000650 // C++0x [temp.param]p9:
651 // A default template-argument may be specified for any kind of
652 // template-parameter that is not a template parameter pack.
653 if (Default && IsParameterPack) {
654 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
655 Default = 0;
656 }
657
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000658 // Check the well-formedness of the default template argument, if provided.
Douglas Gregor10738d32010-12-23 23:51:58 +0000659 if (Default) {
Douglas Gregor6f526752010-12-16 08:48:57 +0000660 // Check for unexpanded parameter packs.
661 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
662 return Param;
663
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000664 TemplateArgument Converted;
665 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
666 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000667 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000668 }
669
John McCall9ae2f072010-08-23 23:25:46 +0000670 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000671 }
672
John McCalld226f652010-08-21 09:40:31 +0000673 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000674}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000675
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000676/// ActOnTemplateTemplateParameter - Called when a C++ template template
677/// parameter (e.g. T in template <template <typename> class T> class array)
678/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000679Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
680 SourceLocation TmpLoc,
681 TemplateParamsTy *Params,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000682 SourceLocation EllipsisLoc,
John McCalld226f652010-08-21 09:40:31 +0000683 IdentifierInfo *Name,
684 SourceLocation NameLoc,
685 unsigned Depth,
686 unsigned Position,
687 SourceLocation EqualLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000688 ParsedTemplateArgument Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000689 assert(S->isTemplateParamScope() &&
690 "Template template parameter not in template parameter scope!");
691
692 // Construct the parameter object.
Douglas Gregor61c4d282011-01-05 15:48:55 +0000693 bool IsParameterPack = EllipsisLoc.isValid();
694 // FIXME: Pack-ness is dropped
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000695 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000696 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000697 NameLoc.isInvalid()? TmpLoc : NameLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000698 Depth, Position, IsParameterPack,
699 Name, Params);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000700
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000701 // If the template template parameter has a name, then link the identifier
702 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000703 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000704 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000705 IdResolver.AddDecl(Param);
706 }
707
Douglas Gregor6f526752010-12-16 08:48:57 +0000708 if (Params->size() == 0) {
709 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
710 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
711 Param->setInvalidDecl();
712 }
713
Douglas Gregor61c4d282011-01-05 15:48:55 +0000714 // C++0x [temp.param]p9:
715 // A default template-argument may be specified for any kind of
716 // template-parameter that is not a template parameter pack.
717 if (IsParameterPack && !Default.isInvalid()) {
718 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
719 Default = ParsedTemplateArgument();
720 }
721
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000722 if (!Default.isInvalid()) {
723 // Check only that we have a template template argument. We don't want to
724 // try to check well-formedness now, because our template template parameter
725 // might have dependent types in its template parameters, which we wouldn't
726 // be able to match now.
727 //
728 // If none of the template template parameter's template arguments mention
729 // other template parameters, we could actually perform more checking here.
730 // However, it isn't worth doing.
731 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
732 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
733 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
734 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000735 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000736 }
737
Douglas Gregor6f526752010-12-16 08:48:57 +0000738 // Check for unexpanded parameter packs.
739 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
740 DefaultArg.getArgument().getAsTemplate(),
741 UPPC_DefaultArgument))
742 return Param;
743
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000744 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000745 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000746
John McCalld226f652010-08-21 09:40:31 +0000747 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000748}
749
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000750/// ActOnTemplateParameterList - Builds a TemplateParameterList that
751/// contains the template parameters in Params/NumParams.
752Sema::TemplateParamsTy *
753Sema::ActOnTemplateParameterList(unsigned Depth,
754 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000755 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000756 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000757 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000758 SourceLocation RAngleLoc) {
759 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000760 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000761
Douglas Gregorddc29e12009-02-06 22:42:48 +0000762 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000763 (NamedDecl**)Params, NumParams,
764 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000765}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000766
John McCallb6217662010-03-15 10:12:16 +0000767static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
768 if (SS.isSet())
769 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
770 SS.getRange());
771}
772
John McCallf312b1e2010-08-26 23:41:50 +0000773DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000774Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000775 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000776 IdentifierInfo *Name, SourceLocation NameLoc,
777 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000778 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000779 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000780 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000781 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000782 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000783 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000784
785 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000786 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000787 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000788
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000789 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
790 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000791
792 // There is no such thing as an unnamed class template.
793 if (!Name) {
794 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000795 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000796 }
797
798 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000799 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000800 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000801 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000802 if (SS.isNotEmpty() && !SS.isInvalid()) {
803 SemanticContext = computeDeclContext(SS, true);
804 if (!SemanticContext) {
805 // FIXME: Produce a reasonable diagnostic here
806 return true;
807 }
Mike Stump1eb44332009-09-09 15:08:12 +0000808
John McCall77bb1aa2010-05-01 00:40:08 +0000809 if (RequireCompleteDeclContext(SS, SemanticContext))
810 return true;
811
John McCalla24dc2e2009-11-17 02:14:36 +0000812 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000813 } else {
814 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000815 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000816 }
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Douglas Gregor57265e32010-04-12 16:00:01 +0000818 if (Previous.isAmbiguous())
819 return true;
820
Douglas Gregorddc29e12009-02-06 22:42:48 +0000821 NamedDecl *PrevDecl = 0;
822 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000823 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000824
Douglas Gregorddc29e12009-02-06 22:42:48 +0000825 // If there is a previous declaration with the same name, check
826 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000827 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000828 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000829
830 // We may have found the injected-class-name of a class template,
831 // class template partial specialization, or class template specialization.
832 // In these cases, grab the template that is being defined or specialized.
833 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
834 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
835 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
836 PrevClassTemplate
837 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
838 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
839 PrevClassTemplate
840 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
841 ->getSpecializedTemplate();
842 }
843 }
844
John McCall65c49462009-12-18 11:25:59 +0000845 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000846 // C++ [namespace.memdef]p3:
847 // [...] When looking for a prior declaration of a class or a function
848 // declared as a friend, and when the name of the friend class or
849 // function is neither a qualified name nor a template-id, scopes outside
850 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000851 if (!SS.isSet()) {
852 DeclContext *OutermostContext = CurContext;
853 while (!OutermostContext->isFileContext())
854 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000855
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000856 if (PrevDecl &&
857 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
858 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
859 SemanticContext = PrevDecl->getDeclContext();
860 } else {
861 // Declarations in outer scopes don't matter. However, the outermost
862 // context we computed is the semantic context for our new
863 // declaration.
864 PrevDecl = PrevClassTemplate = 0;
865 SemanticContext = OutermostContext;
866 }
John McCalle129d442009-12-17 23:21:11 +0000867 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000868
John McCalle129d442009-12-17 23:21:11 +0000869 if (CurContext->isDependentContext()) {
870 // If this is a dependent context, we don't want to link the friend
871 // class template to the template in scope, because that would perform
872 // checking of the template parameter lists that can't be performed
873 // until the outer context is instantiated.
874 PrevDecl = PrevClassTemplate = 0;
875 }
876 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
877 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000878
Douglas Gregorddc29e12009-02-06 22:42:48 +0000879 if (PrevClassTemplate) {
880 // Ensure that the template parameter lists are compatible.
881 if (!TemplateParameterListsAreEqual(TemplateParams,
882 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000883 /*Complain=*/true,
884 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000885 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000886
887 // C++ [temp.class]p4:
888 // In a redeclaration, partial specialization, explicit
889 // specialization or explicit instantiation of a class template,
890 // the class-key shall agree in kind with the original class
891 // template declaration (7.1.5.3).
892 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000893 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000894 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000895 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000896 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000897 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000898 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000899 }
900
Douglas Gregorddc29e12009-02-06 22:42:48 +0000901 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000902 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000903 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000904 Diag(NameLoc, diag::err_redefinition) << Name;
905 Diag(Def->getLocation(), diag::note_previous_definition);
906 // FIXME: Would it make sense to try to "forget" the previous
907 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000908 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000909 }
910 }
911 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
912 // Maybe we will complain about the shadowed template parameter.
913 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
914 // Just pretend that we didn't see the previous declaration.
915 PrevDecl = 0;
916 } else if (PrevDecl) {
917 // C++ [temp]p5:
918 // A class template shall not have the same name as any other
919 // template, class, function, object, enumeration, enumerator,
920 // namespace, or type in the same scope (3.3), except as specified
921 // in (14.5.4).
922 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
923 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000924 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000925 }
926
Douglas Gregord684b002009-02-10 19:49:53 +0000927 // Check the template parameter list of this declaration, possibly
928 // merging in the template parameter list from the previous class
929 // template declaration.
930 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000931 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
932 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000933 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Douglas Gregor57265e32010-04-12 16:00:01 +0000935 if (SS.isSet()) {
936 // If the name of the template was qualified, we must be defining the
937 // template out-of-line.
938 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
939 !(TUK == TUK_Friend && CurContext->isDependentContext()))
940 Diag(NameLoc, diag::err_member_def_does_not_match)
941 << Name << SemanticContext << SS.getRange();
942 }
943
Mike Stump1eb44332009-09-09 15:08:12 +0000944 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000945 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000946 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000947 PrevClassTemplate->getTemplatedDecl() : 0,
948 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000949 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000950
951 ClassTemplateDecl *NewTemplate
952 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
953 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000954 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000955 NewClass->setDescribedClassTemplate(NewTemplate);
956
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000957 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +0000958 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +0000959 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000960 assert(T->isDependentType() && "Class template type is not dependent?");
961 (void)T;
962
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000963 // If we are providing an explicit specialization of a member that is a
964 // class template, make a note of that.
965 if (PrevClassTemplate &&
966 PrevClassTemplate->getInstantiatedFromMemberTemplate())
967 PrevClassTemplate->setMemberSpecialization();
968
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000969 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000970 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000971 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Douglas Gregorddc29e12009-02-06 22:42:48 +0000973 // Set the lexical context of these templates
974 NewClass->setLexicalDeclContext(CurContext);
975 NewTemplate->setLexicalDeclContext(CurContext);
976
John McCall0f434ec2009-07-31 02:45:11 +0000977 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000978 NewClass->startDefinition();
979
980 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000981 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000982
John McCall05b23ea2009-09-14 21:59:20 +0000983 if (TUK != TUK_Friend)
984 PushOnScopeChains(NewTemplate, S);
985 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000986 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000987 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000988 NewClass->setAccess(PrevClassTemplate->getAccess());
989 }
John McCall05b23ea2009-09-14 21:59:20 +0000990
Douglas Gregord85bea22009-09-26 06:47:28 +0000991 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
992 PrevClassTemplate != NULL);
993
John McCall05b23ea2009-09-14 21:59:20 +0000994 // Friend templates are visible in fairly strange ways.
995 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +0000996 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall05b23ea2009-09-14 21:59:20 +0000997 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
998 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
999 PushOnScopeChains(NewTemplate, EnclosingScope,
1000 /* AddToContext = */ false);
1001 }
Douglas Gregord85bea22009-09-26 06:47:28 +00001002
1003 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1004 NewClass->getLocation(),
1005 NewTemplate,
1006 /*FIXME:*/NewClass->getLocation());
1007 Friend->setAccess(AS_public);
1008 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +00001009 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00001010
Douglas Gregord684b002009-02-10 19:49:53 +00001011 if (Invalid) {
1012 NewTemplate->setInvalidDecl();
1013 NewClass->setInvalidDecl();
1014 }
John McCalld226f652010-08-21 09:40:31 +00001015 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +00001016}
1017
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001018/// \brief Diagnose the presence of a default template argument on a
1019/// template parameter, which is ill-formed in certain contexts.
1020///
1021/// \returns true if the default template argument should be dropped.
1022static bool DiagnoseDefaultTemplateArgument(Sema &S,
1023 Sema::TemplateParamListContext TPC,
1024 SourceLocation ParamLoc,
1025 SourceRange DefArgRange) {
1026 switch (TPC) {
1027 case Sema::TPC_ClassTemplate:
1028 return false;
1029
1030 case Sema::TPC_FunctionTemplate:
1031 // C++ [temp.param]p9:
1032 // A default template-argument shall not be specified in a
1033 // function template declaration or a function template
1034 // definition [...]
1035 // (This sentence is not in C++0x, per DR226).
1036 if (!S.getLangOptions().CPlusPlus0x)
1037 S.Diag(ParamLoc,
1038 diag::err_template_parameter_default_in_function_template)
1039 << DefArgRange;
1040 return false;
1041
1042 case Sema::TPC_ClassTemplateMember:
1043 // C++0x [temp.param]p9:
1044 // A default template-argument shall not be specified in the
1045 // template-parameter-lists of the definition of a member of a
1046 // class template that appears outside of the member's class.
1047 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1048 << DefArgRange;
1049 return true;
1050
1051 case Sema::TPC_FriendFunctionTemplate:
1052 // C++ [temp.param]p9:
1053 // A default template-argument shall not be specified in a
1054 // friend template declaration.
1055 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1056 << DefArgRange;
1057 return true;
1058
1059 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1060 // for friend function templates if there is only a single
1061 // declaration (and it is a definition). Strange!
1062 }
1063
1064 return false;
1065}
1066
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001067/// \brief Check for unexpanded parameter packs within the template parameters
1068/// of a template template parameter, recursively.
1069bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP){
1070 TemplateParameterList *Params = TTP->getTemplateParameters();
1071 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1072 NamedDecl *P = Params->getParam(I);
1073 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1074 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1075 NTTP->getTypeSourceInfo(),
1076 Sema::UPPC_NonTypeTemplateParameterType))
1077 return true;
1078
1079 continue;
1080 }
1081
1082 if (TemplateTemplateParmDecl *InnerTTP
1083 = dyn_cast<TemplateTemplateParmDecl>(P))
1084 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1085 return true;
1086 }
1087
1088 return false;
1089}
1090
Douglas Gregord684b002009-02-10 19:49:53 +00001091/// \brief Checks the validity of a template parameter list, possibly
1092/// considering the template parameter list from a previous
1093/// declaration.
1094///
1095/// If an "old" template parameter list is provided, it must be
1096/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1097/// template parameter list.
1098///
1099/// \param NewParams Template parameter list for a new template
1100/// declaration. This template parameter list will be updated with any
1101/// default arguments that are carried through from the previous
1102/// template parameter list.
1103///
1104/// \param OldParams If provided, template parameter list from a
1105/// previous declaration of the same template. Default template
1106/// arguments will be merged from the old template parameter list to
1107/// the new template parameter list.
1108///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001109/// \param TPC Describes the context in which we are checking the given
1110/// template parameter list.
1111///
Douglas Gregord684b002009-02-10 19:49:53 +00001112/// \returns true if an error occurred, false otherwise.
1113bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001114 TemplateParameterList *OldParams,
1115 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001116 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001117
Douglas Gregord684b002009-02-10 19:49:53 +00001118 // C++ [temp.param]p10:
1119 // The set of default template-arguments available for use with a
1120 // template declaration or definition is obtained by merging the
1121 // default arguments from the definition (if in scope) and all
1122 // declarations in scope in the same way default function
1123 // arguments are (8.3.6).
1124 bool SawDefaultArgument = false;
1125 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001126
Anders Carlsson49d25572009-06-12 23:20:15 +00001127 bool SawParameterPack = false;
1128 SourceLocation ParameterPackLoc;
1129
Mike Stump1a35fde2009-02-11 23:03:27 +00001130 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001131 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001132 if (OldParams)
1133 OldParam = OldParams->begin();
1134
1135 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1136 NewParamEnd = NewParams->end();
1137 NewParam != NewParamEnd; ++NewParam) {
1138 // Variables used to diagnose redundant default arguments
1139 bool RedundantDefaultArg = false;
1140 SourceLocation OldDefaultLoc;
1141 SourceLocation NewDefaultLoc;
1142
1143 // Variables used to diagnose missing default arguments
1144 bool MissingDefaultArg = false;
1145
Anders Carlsson49d25572009-06-12 23:20:15 +00001146 // C++0x [temp.param]p11:
Douglas Gregor1ed64762011-01-05 16:19:19 +00001147 // If a template parameter of a primary class template is a template
1148 // parameter pack, it shall be the last template parameter.
1149 if (SawParameterPack && TPC == TPC_ClassTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00001150 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001151 diag::err_template_param_pack_must_be_last_template_parameter);
1152 Invalid = true;
1153 }
1154
Douglas Gregord684b002009-02-10 19:49:53 +00001155 if (TemplateTypeParmDecl *NewTypeParm
1156 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001157 // Check the presence of a default argument here.
1158 if (NewTypeParm->hasDefaultArgument() &&
1159 DiagnoseDefaultTemplateArgument(*this, TPC,
1160 NewTypeParm->getLocation(),
1161 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001162 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001163 NewTypeParm->removeDefaultArgument();
1164
1165 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001166 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001167 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Anders Carlsson49d25572009-06-12 23:20:15 +00001169 if (NewTypeParm->isParameterPack()) {
1170 assert(!NewTypeParm->hasDefaultArgument() &&
1171 "Parameter packs can't have a default argument!");
1172 SawParameterPack = true;
1173 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001174 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001175 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001176 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1177 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1178 SawDefaultArgument = true;
1179 RedundantDefaultArg = true;
1180 PreviousDefaultArgLoc = NewDefaultLoc;
1181 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1182 // Merge the default argument from the old declaration to the
1183 // new declaration.
1184 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001185 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001186 true);
1187 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1188 } else if (NewTypeParm->hasDefaultArgument()) {
1189 SawDefaultArgument = true;
1190 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1191 } else if (SawDefaultArgument)
1192 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001193 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001194 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001195 // Check for unexpanded parameter packs.
1196 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1197 NewNonTypeParm->getTypeSourceInfo(),
1198 UPPC_NonTypeTemplateParameterType)) {
1199 Invalid = true;
1200 continue;
1201 }
1202
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001203 // Check the presence of a default argument here.
1204 if (NewNonTypeParm->hasDefaultArgument() &&
1205 DiagnoseDefaultTemplateArgument(*this, TPC,
1206 NewNonTypeParm->getLocation(),
1207 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001208 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001209 }
1210
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001211 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001212 NonTypeTemplateParmDecl *OldNonTypeParm
1213 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001214 if (NewNonTypeParm->isParameterPack()) {
1215 assert(!NewNonTypeParm->hasDefaultArgument() &&
1216 "Parameter packs can't have a default argument!");
1217 SawParameterPack = true;
1218 ParameterPackLoc = NewNonTypeParm->getLocation();
1219 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001220 NewNonTypeParm->hasDefaultArgument()) {
1221 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1222 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1223 SawDefaultArgument = true;
1224 RedundantDefaultArg = true;
1225 PreviousDefaultArgLoc = NewDefaultLoc;
1226 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1227 // Merge the default argument from the old declaration to the
1228 // new declaration.
1229 SawDefaultArgument = true;
1230 // FIXME: We need to create a new kind of "default argument"
Douglas Gregor61c4d282011-01-05 15:48:55 +00001231 // expression that points to a previous non-type template
Douglas Gregord684b002009-02-10 19:49:53 +00001232 // parameter.
1233 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001234 OldNonTypeParm->getDefaultArgument(),
1235 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001236 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1237 } else if (NewNonTypeParm->hasDefaultArgument()) {
1238 SawDefaultArgument = true;
1239 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1240 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001241 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001242 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001243 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001244 TemplateTemplateParmDecl *NewTemplateParm
1245 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001246
1247 // Check for unexpanded parameter packs, recursively.
1248 if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1249 Invalid = true;
1250 continue;
1251 }
1252
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001253 if (NewTemplateParm->hasDefaultArgument() &&
1254 DiagnoseDefaultTemplateArgument(*this, TPC,
1255 NewTemplateParm->getLocation(),
1256 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001257 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001258
1259 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001260 TemplateTemplateParmDecl *OldTemplateParm
1261 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001262 if (NewTemplateParm->isParameterPack()) {
1263 assert(!NewTemplateParm->hasDefaultArgument() &&
1264 "Parameter packs can't have a default argument!");
1265 SawParameterPack = true;
1266 ParameterPackLoc = NewTemplateParm->getLocation();
1267 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001268 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001269 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1270 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001271 SawDefaultArgument = true;
1272 RedundantDefaultArg = true;
1273 PreviousDefaultArgLoc = NewDefaultLoc;
1274 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1275 // Merge the default argument from the old declaration to the
1276 // new declaration.
1277 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001278 // FIXME: We need to create a new kind of "default argument" expression
1279 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001280 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001281 OldTemplateParm->getDefaultArgument(),
1282 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001283 PreviousDefaultArgLoc
1284 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001285 } else if (NewTemplateParm->hasDefaultArgument()) {
1286 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001287 PreviousDefaultArgLoc
1288 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001289 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001290 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001291 }
1292
1293 if (RedundantDefaultArg) {
1294 // C++ [temp.param]p12:
1295 // A template-parameter shall not be given default arguments
1296 // by two different declarations in the same scope.
1297 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1298 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1299 Invalid = true;
1300 } else if (MissingDefaultArg) {
1301 // C++ [temp.param]p11:
1302 // If a template-parameter has a default template-argument,
1303 // all subsequent template-parameters shall have a default
1304 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001305 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001306 diag::err_template_param_default_arg_missing);
1307 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1308 Invalid = true;
1309 }
1310
1311 // If we have an old template parameter list that we're merging
1312 // in, move on to the next parameter.
1313 if (OldParams)
1314 ++OldParam;
1315 }
1316
1317 return Invalid;
1318}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001319
John McCall4e2cbb22010-10-20 05:44:58 +00001320namespace {
1321
1322/// A class which looks for a use of a certain level of template
1323/// parameter.
1324struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1325 typedef RecursiveASTVisitor<DependencyChecker> super;
1326
1327 unsigned Depth;
1328 bool Match;
1329
1330 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1331 NamedDecl *ND = Params->getParam(0);
1332 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1333 Depth = PD->getDepth();
1334 } else if (NonTypeTemplateParmDecl *PD =
1335 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1336 Depth = PD->getDepth();
1337 } else {
1338 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1339 }
1340 }
1341
1342 bool Matches(unsigned ParmDepth) {
1343 if (ParmDepth >= Depth) {
1344 Match = true;
1345 return true;
1346 }
1347 return false;
1348 }
1349
1350 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1351 return !Matches(T->getDepth());
1352 }
1353
1354 bool TraverseTemplateName(TemplateName N) {
1355 if (TemplateTemplateParmDecl *PD =
1356 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1357 if (Matches(PD->getDepth())) return false;
1358 return super::TraverseTemplateName(N);
1359 }
1360
1361 bool VisitDeclRefExpr(DeclRefExpr *E) {
1362 if (NonTypeTemplateParmDecl *PD =
1363 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1364 if (PD->getDepth() == Depth) {
1365 Match = true;
1366 return false;
1367 }
1368 }
1369 return super::VisitDeclRefExpr(E);
1370 }
1371};
1372}
1373
1374/// Determines whether a template-id depends on the given parameter
1375/// list.
1376static bool
1377DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId,
1378 TemplateParameterList *Params) {
1379 DependencyChecker Checker(Params);
1380 Checker.TraverseType(QualType(TemplateId, 0));
1381 return Checker.Match;
1382}
1383
Mike Stump1eb44332009-09-09 15:08:12 +00001384/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001385/// specifier, returning the template parameter list that applies to the
1386/// name.
1387///
1388/// \param DeclStartLoc the start of the declaration that has a scope
1389/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001390///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001391/// \param SS the scope specifier that will be matched to the given template
1392/// parameter lists. This scope specifier precedes a qualified name that is
1393/// being declared.
1394///
1395/// \param ParamLists the template parameter lists, from the outermost to the
1396/// innermost template parameter lists.
1397///
1398/// \param NumParamLists the number of template parameter lists in ParamLists.
1399///
John McCall77e8b112010-04-13 20:37:33 +00001400/// \param IsFriend Whether to apply the slightly different rules for
1401/// matching template parameters to scope specifiers in friend
1402/// declarations.
1403///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001404/// \param IsExplicitSpecialization will be set true if the entity being
1405/// declared is an explicit specialization, false otherwise.
1406///
Mike Stump1eb44332009-09-09 15:08:12 +00001407/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001408/// name that is preceded by the scope specifier @p SS. This template
1409/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001410/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001411/// template specialization), or may be NULL (if we were's declaring isn't
1412/// itself a template).
1413TemplateParameterList *
1414Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1415 const CXXScopeSpec &SS,
1416 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001417 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001418 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001419 bool &IsExplicitSpecialization,
1420 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001421 IsExplicitSpecialization = false;
1422
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001423 // Find the template-ids that occur within the nested-name-specifier. These
1424 // template-ids will match up with the template parameter lists.
1425 llvm::SmallVector<const TemplateSpecializationType *, 4>
1426 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001427 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1428 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001429 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1430 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001431 const Type *T = NNS->getAsType();
1432 if (!T) break;
1433
1434 // C++0x [temp.expl.spec]p17:
1435 // A member or a member template may be nested within many
1436 // enclosing class templates. In an explicit specialization for
1437 // such a member, the member declaration shall be preceded by a
1438 // template<> for each enclosing class template that is
1439 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001440 //
1441 // Following the existing practice of GNU and EDG, we allow a typedef of a
1442 // template specialization type.
John McCall49f4e1c2010-12-10 11:01:00 +00001443 while (const TypedefType *TT = dyn_cast<TypedefType>(T))
1444 T = TT->getDecl()->getUnderlyingType().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001445
Mike Stump1eb44332009-09-09 15:08:12 +00001446 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001447 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001448 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1449 if (!Template)
1450 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Ted Kremenek6217b802009-07-29 21:53:49 +00001452 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001453 ClassTemplateSpecializationDecl *SpecDecl
1454 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1455 // If the nested name specifier refers to an explicit specialization,
1456 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001457 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1458 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001459 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001460 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001461 }
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001463 TemplateIdsInSpecifier.push_back(SpecType);
1464 }
1465 }
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001467 // Reverse the list of template-ids in the scope specifier, so that we can
1468 // more easily match up the template-ids and the template parameter lists.
1469 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001471 SourceLocation FirstTemplateLoc = DeclStartLoc;
1472 if (NumParamLists)
1473 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001475 // Match the template-ids found in the specifier to the template parameter
1476 // lists.
John McCall4e2cbb22010-10-20 05:44:58 +00001477 unsigned ParamIdx = 0, TemplateIdx = 0;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001478 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
John McCall4e2cbb22010-10-20 05:44:58 +00001479 TemplateIdx != NumTemplateIds; ++TemplateIdx) {
1480 const TemplateSpecializationType *TemplateId
1481 = TemplateIdsInSpecifier[TemplateIdx];
Douglas Gregorb88e8882009-07-30 17:40:51 +00001482 bool DependentTemplateId = TemplateId->isDependentType();
John McCall4e2cbb22010-10-20 05:44:58 +00001483
1484 // In friend declarations we can have template-ids which don't
1485 // depend on the corresponding template parameter lists. But
1486 // assume that empty parameter lists are supposed to match this
1487 // template-id.
1488 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) {
1489 if (!DependentTemplateId ||
1490 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx]))
1491 continue;
1492 }
1493
1494 if (ParamIdx >= NumParamLists) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001495 // We have a template-id without a corresponding template parameter
1496 // list.
John McCall77e8b112010-04-13 20:37:33 +00001497
1498 // ...which is fine if this is a friend declaration.
1499 if (IsFriend) {
1500 IsExplicitSpecialization = true;
1501 break;
1502 }
1503
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001504 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001505 // FIXME: the location information here isn't great.
1506 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001507 diag::err_template_spec_needs_template_parameters)
John McCall4e2cbb22010-10-20 05:44:58 +00001508 << QualType(TemplateId, 0)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001509 << SS.getRange();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001510 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001511 } else {
1512 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1513 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001514 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001515 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001516 }
1517 return 0;
1518 }
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001520 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001521 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001522 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001523
John McCall31f17ec2010-04-27 00:57:59 +00001524 // Are there cases in (e.g.) friends where this won't match?
1525 if (const InjectedClassNameType *Injected
1526 = TemplateId->getAs<InjectedClassNameType>()) {
1527 CXXRecordDecl *Record = Injected->getDecl();
1528 if (ClassTemplatePartialSpecializationDecl *Partial =
1529 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1530 ExpectedTemplateParams = Partial->getTemplateParameters();
1531 else
1532 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1533 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001534 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001535
John McCall31f17ec2010-04-27 00:57:59 +00001536 if (ExpectedTemplateParams)
John McCall4e2cbb22010-10-20 05:44:58 +00001537 TemplateParameterListsAreEqual(ParamLists[ParamIdx],
John McCall31f17ec2010-04-27 00:57:59 +00001538 ExpectedTemplateParams,
1539 true, TPL_TemplateMatch);
1540
John McCall4e2cbb22010-10-20 05:44:58 +00001541 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1542 TPC_ClassTemplateMember);
1543 } else if (ParamLists[ParamIdx]->size() > 0)
1544 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001545 diag::err_template_param_list_matches_nontemplate)
1546 << TemplateId
John McCall4e2cbb22010-10-20 05:44:58 +00001547 << ParamLists[ParamIdx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001548 else
1549 IsExplicitSpecialization = true;
John McCall4e2cbb22010-10-20 05:44:58 +00001550
1551 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001552 }
Mike Stump1eb44332009-09-09 15:08:12 +00001553
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001554 // If there were at least as many template-ids as there were template
1555 // parameter lists, then there are no template parameter lists remaining for
1556 // the declaration itself.
John McCall4e2cbb22010-10-20 05:44:58 +00001557 if (ParamIdx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001558 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001560 // If there were too many template parameter lists, complain about that now.
John McCall4e2cbb22010-10-20 05:44:58 +00001561 if (ParamIdx != NumParamLists - 1) {
1562 while (ParamIdx < NumParamLists - 1) {
1563 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0;
1564 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001565 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1566 : diag::err_template_spec_extra_headers)
John McCall4e2cbb22010-10-20 05:44:58 +00001567 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1568 ParamLists[ParamIdx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001569
1570 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1571 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1572 diag::note_explicit_template_spec_does_not_need_header)
1573 << ExplicitSpecializationsInSpecifier.back();
1574 ExplicitSpecializationsInSpecifier.pop_back();
1575 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001576
1577 // We have a template parameter list with no corresponding scope, which
1578 // means that the resulting template declaration can't be instantiated
1579 // properly (we'll end up with dependent nodes when we shouldn't).
1580 if (!isExplicitSpecHeader)
1581 Invalid = true;
1582
John McCall4e2cbb22010-10-20 05:44:58 +00001583 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001584 }
1585 }
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001587 // Return the last template parameter list, which corresponds to the
1588 // entity being declared.
1589 return ParamLists[NumParamLists - 1];
1590}
1591
Douglas Gregor7532dc62009-03-30 22:58:21 +00001592QualType Sema::CheckTemplateIdType(TemplateName Name,
1593 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001594 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001595 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001596 if (!Template) {
1597 // The template name does not resolve to a template, so we just
1598 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001599 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001600 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001601
Douglas Gregor40808ce2009-03-09 23:48:35 +00001602 // Check that the template argument list is well-formed for this
1603 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001604 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00001605 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001606 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001607 return QualType();
1608
Douglas Gregor910f8002010-11-07 23:05:16 +00001609 assert((Converted.size() == Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001610 "Converted template argument list is too short!");
1611
1612 QualType CanonType;
1613
Douglas Gregorcaddba02009-11-12 18:38:13 +00001614 if (Name.isDependent() ||
1615 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001616 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001617 // This class template specialization is a dependent
1618 // type. Therefore, its canonical type is another class template
1619 // specialization type that contains all of the converted
1620 // arguments in canonical form. This ensures that, e.g., A<T> and
1621 // A<T, T> have identical types when A is declared as:
1622 //
1623 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001624 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001625 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor910f8002010-11-07 23:05:16 +00001626 Converted.data(),
1627 Converted.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Douglas Gregor1275ae02009-07-28 23:00:59 +00001629 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001630 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001631 // In the future, we need to teach getTemplateSpecializationType to only
1632 // build the canonical type and return that to us.
1633 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001634
1635 // This might work out to be a current instantiation, in which
1636 // case the canonical type needs to be the InjectedClassNameType.
1637 //
1638 // TODO: in theory this could be a simple hashtable lookup; most
1639 // changes to CurContext don't change the set of current
1640 // instantiations.
1641 if (isa<ClassTemplateDecl>(Template)) {
1642 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1643 // If we get out to a namespace, we're done.
1644 if (Ctx->isFileContext()) break;
1645
1646 // If this isn't a record, keep looking.
1647 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1648 if (!Record) continue;
1649
1650 // Look for one of the two cases with InjectedClassNameTypes
1651 // and check whether it's the same template.
1652 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1653 !Record->getDescribedClassTemplate())
1654 continue;
1655
1656 // Fetch the injected class name type and check whether its
1657 // injected type is equal to the type we just built.
1658 QualType ICNT = Context.getTypeDeclType(Record);
1659 QualType Injected = cast<InjectedClassNameType>(ICNT)
1660 ->getInjectedSpecializationType();
1661
1662 if (CanonType != Injected->getCanonicalTypeInternal())
1663 continue;
1664
1665 // If so, the canonical type of this TST is the injected
1666 // class name type of the record we just found.
1667 assert(ICNT.isCanonical());
1668 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00001669 break;
1670 }
1671 }
Mike Stump1eb44332009-09-09 15:08:12 +00001672 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001673 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001674 // Find the class template specialization declaration that
1675 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001676 void *InsertPos = 0;
1677 ClassTemplateSpecializationDecl *Decl
Douglas Gregor910f8002010-11-07 23:05:16 +00001678 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
1679 InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001680 if (!Decl) {
1681 // This is the first time we have referenced this class template
1682 // specialization. Create the canonical declaration and add it to
1683 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001684 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001685 ClassTemplate->getTemplatedDecl()->getTagKind(),
1686 ClassTemplate->getDeclContext(),
1687 ClassTemplate->getLocation(),
Douglas Gregor910f8002010-11-07 23:05:16 +00001688 ClassTemplate,
1689 Converted.data(),
1690 Converted.size(), 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001691 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001692 Decl->setLexicalDeclContext(CurContext);
1693 }
1694
1695 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001696 assert(isa<RecordType>(CanonType) &&
1697 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001698 }
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Douglas Gregor40808ce2009-03-09 23:48:35 +00001700 // Build the fully-sugared type for this class template
1701 // specialization, which refers back to the class template
1702 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00001703 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001704}
1705
John McCallf312b1e2010-08-26 23:41:50 +00001706TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001707Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001708 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001709 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001710 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001711 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001712
Douglas Gregor40808ce2009-03-09 23:48:35 +00001713 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001714 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001715 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001716
John McCalld5532b62009-11-23 01:53:49 +00001717 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001718 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001719
1720 if (Result.isNull())
1721 return true;
1722
John McCalla93c9342009-12-07 02:54:59 +00001723 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001724 TemplateSpecializationTypeLoc TL
1725 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1726 TL.setTemplateNameLoc(TemplateLoc);
1727 TL.setLAngleLoc(LAngleLoc);
1728 TL.setRAngleLoc(RAngleLoc);
1729 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1730 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1731
John McCallb3d87482010-08-24 05:47:05 +00001732 return CreateParsedType(Result, DI);
John McCall6b2becf2009-09-08 17:47:29 +00001733}
John McCallf1bbbb42009-09-04 01:14:41 +00001734
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001735TypeResult Sema::ActOnTagTemplateIdType(CXXScopeSpec &SS,
1736 TypeResult TypeResult,
John McCallf312b1e2010-08-26 23:41:50 +00001737 TagUseKind TUK,
1738 TypeSpecifierType TagSpec,
1739 SourceLocation TagLoc) {
John McCall6b2becf2009-09-08 17:47:29 +00001740 if (TypeResult.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001741 return ::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001742
John McCalla93c9342009-12-07 02:54:59 +00001743 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001744 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001745
John McCall6b2becf2009-09-08 17:47:29 +00001746 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001747 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001748
John McCall6b2becf2009-09-08 17:47:29 +00001749 if (const RecordType *RT = Type->getAs<RecordType>()) {
1750 RecordDecl *D = RT->getDecl();
1751
1752 IdentifierInfo *Id = D->getIdentifier();
1753 assert(Id && "templated class must have an identifier");
1754
1755 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1756 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001757 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001758 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001759 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001760 }
1761 }
1762
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001763 ElaboratedTypeKeyword Keyword
1764 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1765 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001766
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001767 TypeSourceInfo *ElabDI = Context.CreateTypeSourceInfo(ElabType);
1768 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(ElabDI->getTypeLoc());
1769 TL.setKeywordLoc(TagLoc);
1770 TL.setQualifierRange(SS.getRange());
1771 TL.getNamedTypeLoc().initializeFullCopy(DI->getTypeLoc());
1772 return CreateParsedType(ElabType, ElabDI);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001773}
1774
John McCall60d7b3a2010-08-24 06:29:42 +00001775ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001776 LookupResult &R,
1777 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001778 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001779 // FIXME: Can we do any checking at this point? I guess we could check the
1780 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001781 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001782 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001783
1784 // These should be filtered out by our callers.
1785 assert(!R.empty() && "empty lookup results when building templateid");
1786 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1787
1788 NestedNameSpecifier *Qualifier = 0;
1789 SourceRange QualifierRange;
1790 if (SS.isSet()) {
1791 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1792 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001793 }
John McCallc373d482010-01-27 01:50:18 +00001794
1795 // We don't want lookup warnings at this point.
1796 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001797
John McCallf7a1a742009-11-24 19:00:30 +00001798 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001799 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001800 Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00001801 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001802 RequiresADL, TemplateArgs,
1803 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001804
1805 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001806}
1807
John McCallf7a1a742009-11-24 19:00:30 +00001808// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00001809ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001810Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001811 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +00001812 const TemplateArgumentListInfo &TemplateArgs) {
1813 DeclContext *DC;
1814 if (!(DC = computeDeclContext(SS, false)) ||
1815 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001816 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara25777432010-08-11 22:01:17 +00001817 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001819 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00001820 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001821 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1822 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001823
John McCallf7a1a742009-11-24 19:00:30 +00001824 if (R.isAmbiguous())
1825 return ExprError();
1826
1827 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001828 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1829 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001830 return ExprError();
1831 }
1832
1833 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001834 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1835 << (NestedNameSpecifier*) SS.getScopeRep()
1836 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001837 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1838 return ExprError();
1839 }
1840
1841 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001842}
1843
Douglas Gregorc45c2322009-03-31 00:43:58 +00001844/// \brief Form a dependent template name.
1845///
1846/// This action forms a dependent template name given the template
1847/// name and its (presumably dependent) scope specifier. For
1848/// example, given "MetaFun::template apply", the scope specifier \p
1849/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1850/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001851TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1852 SourceLocation TemplateKWLoc,
1853 CXXScopeSpec &SS,
1854 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00001855 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001856 bool EnteringContext,
1857 TemplateTy &Result) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00001858 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1859 !getLangOptions().CPlusPlus0x)
1860 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1861 << FixItHint::CreateRemoval(TemplateKWLoc);
1862
Douglas Gregor0707bc52010-01-19 16:01:07 +00001863 DeclContext *LookupCtx = 0;
1864 if (SS.isSet())
1865 LookupCtx = computeDeclContext(SS, EnteringContext);
1866 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00001867 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00001868 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001869 // C++0x [temp.names]p5:
1870 // If a name prefixed by the keyword template is not the name of
1871 // a template, the program is ill-formed. [Note: the keyword
1872 // template may not be applied to non-template members of class
1873 // templates. -end note ] [ Note: as is the case with the
1874 // typename prefix, the template prefix is allowed in cases
1875 // where it is not strictly necessary; i.e., when the
1876 // nested-name-specifier or the expression on the left of the ->
1877 // or . is not dependent on a template-parameter, or the use
1878 // does not appear in the scope of a template. -end note]
1879 //
1880 // Note: C++03 was more strict here, because it banned the use of
1881 // the "template" keyword prior to a template-name that was not a
1882 // dependent name. C++ DR468 relaxed this requirement (the
1883 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00001884 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001885 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001886 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1887 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001888 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001889 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1890 isa<CXXRecordDecl>(LookupCtx) &&
1891 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00001892 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001893 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001894 Diag(Name.getSourceRange().getBegin(),
1895 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001896 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001897 << Name.getSourceRange()
1898 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001899 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001900 } else {
1901 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001902 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001903 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001904 }
1905
Mike Stump1eb44332009-09-09 15:08:12 +00001906 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001907 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001908
1909 switch (Name.getKind()) {
1910 case UnqualifiedId::IK_Identifier:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001911 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1912 Name.Identifier));
1913 return TNK_Dependent_template_name;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001914
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001915 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001916 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001917 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00001918 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00001919
1920 case UnqualifiedId::IK_LiteralOperatorId:
1921 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1922
Douglas Gregor014e88d2009-11-03 23:16:33 +00001923 default:
1924 break;
1925 }
1926
1927 Diag(Name.getSourceRange().getBegin(),
1928 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001929 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001930 << Name.getSourceRange()
1931 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001932 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001933}
1934
Mike Stump1eb44332009-09-09 15:08:12 +00001935bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001936 const TemplateArgumentLoc &AL,
Douglas Gregor910f8002010-11-07 23:05:16 +00001937 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001938 const TemplateArgument &Arg = AL.getArgument();
1939
Anders Carlsson436b1562009-06-13 00:33:33 +00001940 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001941 switch(Arg.getKind()) {
1942 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001943 // C++ [temp.arg.type]p1:
1944 // A template-argument for a template-parameter which is a
1945 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001946 break;
1947 case TemplateArgument::Template: {
1948 // We have a template type parameter but the template argument
1949 // is a template without any arguments.
1950 SourceRange SR = AL.getSourceRange();
1951 TemplateName Name = Arg.getAsTemplate();
1952 Diag(SR.getBegin(), diag::err_template_missing_args)
1953 << Name << SR;
1954 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1955 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001956
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001957 return true;
1958 }
1959 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001960 // We have a template type parameter but the template argument
1961 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001962 SourceRange SR = AL.getSourceRange();
1963 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001964 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Anders Carlsson436b1562009-06-13 00:33:33 +00001966 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001967 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001968 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001969
John McCalla93c9342009-12-07 02:54:59 +00001970 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001971 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Anders Carlsson436b1562009-06-13 00:33:33 +00001973 // Add the converted template type argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001974 Converted.push_back(
John McCall833ca992009-10-29 08:12:44 +00001975 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001976 return false;
1977}
1978
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001979/// \brief Substitute template arguments into the default template argument for
1980/// the given template type parameter.
1981///
1982/// \param SemaRef the semantic analysis object for which we are performing
1983/// the substitution.
1984///
1985/// \param Template the template that we are synthesizing template arguments
1986/// for.
1987///
1988/// \param TemplateLoc the location of the template name that started the
1989/// template-id we are checking.
1990///
1991/// \param RAngleLoc the location of the right angle bracket ('>') that
1992/// terminates the template-id.
1993///
1994/// \param Param the template template parameter whose default we are
1995/// substituting into.
1996///
1997/// \param Converted the list of template arguments provided for template
1998/// parameters that precede \p Param in the template parameter list.
1999///
2000/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00002001static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002002SubstDefaultTemplateArgument(Sema &SemaRef,
2003 TemplateDecl *Template,
2004 SourceLocation TemplateLoc,
2005 SourceLocation RAngleLoc,
2006 TemplateTypeParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002007 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00002008 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002009
2010 // If the argument type is dependent, instantiate it now based
2011 // on the previously-computed template arguments.
2012 if (ArgType->getType()->isDependentType()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002013 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2014 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002015
2016 MultiLevelTemplateArgumentList AllTemplateArgs
2017 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2018
2019 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002020 Template, Converted.data(),
2021 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002022 SourceRange(TemplateLoc, RAngleLoc));
2023
2024 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2025 Param->getDefaultArgumentLoc(),
2026 Param->getDeclName());
2027 }
2028
2029 return ArgType;
2030}
2031
2032/// \brief Substitute template arguments into the default template argument for
2033/// the given non-type template parameter.
2034///
2035/// \param SemaRef the semantic analysis object for which we are performing
2036/// the substitution.
2037///
2038/// \param Template the template that we are synthesizing template arguments
2039/// for.
2040///
2041/// \param TemplateLoc the location of the template name that started the
2042/// template-id we are checking.
2043///
2044/// \param RAngleLoc the location of the right angle bracket ('>') that
2045/// terminates the template-id.
2046///
Douglas Gregor788cd062009-11-11 01:00:40 +00002047/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002048/// substituting into.
2049///
2050/// \param Converted the list of template arguments provided for template
2051/// parameters that precede \p Param in the template parameter list.
2052///
2053/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00002054static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002055SubstDefaultTemplateArgument(Sema &SemaRef,
2056 TemplateDecl *Template,
2057 SourceLocation TemplateLoc,
2058 SourceLocation RAngleLoc,
2059 NonTypeTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002060 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2061 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2062 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002063
2064 MultiLevelTemplateArgumentList AllTemplateArgs
2065 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2066
2067 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002068 Template, Converted.data(),
2069 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002070 SourceRange(TemplateLoc, RAngleLoc));
2071
2072 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2073}
2074
Douglas Gregor788cd062009-11-11 01:00:40 +00002075/// \brief Substitute template arguments into the default template argument for
2076/// the given template template parameter.
2077///
2078/// \param SemaRef the semantic analysis object for which we are performing
2079/// the substitution.
2080///
2081/// \param Template the template that we are synthesizing template arguments
2082/// for.
2083///
2084/// \param TemplateLoc the location of the template name that started the
2085/// template-id we are checking.
2086///
2087/// \param RAngleLoc the location of the right angle bracket ('>') that
2088/// terminates the template-id.
2089///
2090/// \param Param the template template parameter whose default we are
2091/// substituting into.
2092///
2093/// \param Converted the list of template arguments provided for template
2094/// parameters that precede \p Param in the template parameter list.
2095///
2096/// \returns the substituted template argument, or NULL if an error occurred.
2097static TemplateName
2098SubstDefaultTemplateArgument(Sema &SemaRef,
2099 TemplateDecl *Template,
2100 SourceLocation TemplateLoc,
2101 SourceLocation RAngleLoc,
2102 TemplateTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002103 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2104 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2105 Converted.data(), Converted.size());
Douglas Gregor788cd062009-11-11 01:00:40 +00002106
2107 MultiLevelTemplateArgumentList AllTemplateArgs
2108 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2109
2110 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002111 Template, Converted.data(),
2112 Converted.size(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002113 SourceRange(TemplateLoc, RAngleLoc));
2114
2115 return SemaRef.SubstTemplateName(
2116 Param->getDefaultArgument().getArgument().getAsTemplate(),
2117 Param->getDefaultArgument().getTemplateNameLoc(),
2118 AllTemplateArgs);
2119}
2120
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002121/// \brief If the given template parameter has a default template
2122/// argument, substitute into that default template argument and
2123/// return the corresponding template argument.
2124TemplateArgumentLoc
2125Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2126 SourceLocation TemplateLoc,
2127 SourceLocation RAngleLoc,
2128 Decl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002129 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2130 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002131 if (!TypeParm->hasDefaultArgument())
2132 return TemplateArgumentLoc();
2133
John McCalla93c9342009-12-07 02:54:59 +00002134 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002135 TemplateLoc,
2136 RAngleLoc,
2137 TypeParm,
2138 Converted);
2139 if (DI)
2140 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2141
2142 return TemplateArgumentLoc();
2143 }
2144
2145 if (NonTypeTemplateParmDecl *NonTypeParm
2146 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2147 if (!NonTypeParm->hasDefaultArgument())
2148 return TemplateArgumentLoc();
2149
John McCall60d7b3a2010-08-24 06:29:42 +00002150 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002151 TemplateLoc,
2152 RAngleLoc,
2153 NonTypeParm,
2154 Converted);
2155 if (Arg.isInvalid())
2156 return TemplateArgumentLoc();
2157
2158 Expr *ArgE = Arg.takeAs<Expr>();
2159 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2160 }
2161
2162 TemplateTemplateParmDecl *TempTempParm
2163 = cast<TemplateTemplateParmDecl>(Param);
2164 if (!TempTempParm->hasDefaultArgument())
2165 return TemplateArgumentLoc();
2166
2167 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2168 TemplateLoc,
2169 RAngleLoc,
2170 TempTempParm,
2171 Converted);
2172 if (TName.isNull())
2173 return TemplateArgumentLoc();
2174
2175 return TemplateArgumentLoc(TemplateArgument(TName),
2176 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2177 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2178}
2179
Douglas Gregore7526412009-11-11 19:31:23 +00002180/// \brief Check that the given template argument corresponds to the given
2181/// template parameter.
2182bool Sema::CheckTemplateArgument(NamedDecl *Param,
2183 const TemplateArgumentLoc &Arg,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002184 NamedDecl *Template,
Douglas Gregore7526412009-11-11 19:31:23 +00002185 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002186 SourceLocation RAngleLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002187 llvm::SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor02024a92010-03-28 02:42:43 +00002188 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002189 // Check template type parameters.
2190 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002191 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002192
Douglas Gregord9e15302009-11-11 19:41:09 +00002193 // Check non-type template parameters.
2194 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002195 // Do substitution on the type of the non-type template parameter
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002196 // with the template arguments we've seen thus far. But if the
2197 // template has a dependent context then we cannot substitute yet.
Douglas Gregore7526412009-11-11 19:31:23 +00002198 QualType NTTPType = NTTP->getType();
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002199 if (NTTPType->isDependentType() &&
2200 !isa<TemplateTemplateParmDecl>(Template) &&
2201 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002202 // Do substitution on the type of the non-type template parameter.
2203 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002204 NTTP, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002205 SourceRange(TemplateLoc, RAngleLoc));
2206
Douglas Gregor910f8002010-11-07 23:05:16 +00002207 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2208 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002209 NTTPType = SubstType(NTTPType,
2210 MultiLevelTemplateArgumentList(TemplateArgs),
2211 NTTP->getLocation(),
2212 NTTP->getDeclName());
2213 // If that worked, check the non-type template parameter type
2214 // for validity.
2215 if (!NTTPType.isNull())
2216 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2217 NTTP->getLocation());
2218 if (NTTPType.isNull())
2219 return true;
2220 }
2221
2222 switch (Arg.getArgument().getKind()) {
2223 case TemplateArgument::Null:
2224 assert(false && "Should never see a NULL template argument here");
2225 return true;
2226
2227 case TemplateArgument::Expression: {
2228 Expr *E = Arg.getArgument().getAsExpr();
2229 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002230 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002231 return true;
2232
Douglas Gregor910f8002010-11-07 23:05:16 +00002233 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002234 break;
2235 }
2236
2237 case TemplateArgument::Declaration:
2238 case TemplateArgument::Integral:
2239 // We've already checked this template argument, so just copy
2240 // it to the list of converted arguments.
Douglas Gregor910f8002010-11-07 23:05:16 +00002241 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002242 break;
2243
2244 case TemplateArgument::Template:
2245 // We were given a template template argument. It may not be ill-formed;
2246 // see below.
2247 if (DependentTemplateName *DTN
2248 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2249 // We have a template argument such as \c T::template X, which we
2250 // parsed as a template template argument. However, since we now
2251 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002252 // template name into an expression.
2253
2254 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2255 Arg.getTemplateNameLoc());
2256
John McCallf7a1a742009-11-24 19:00:30 +00002257 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2258 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002259 Arg.getTemplateQualifierRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002260 NameInfo);
Douglas Gregore7526412009-11-11 19:31:23 +00002261
2262 TemplateArgument Result;
2263 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2264 return true;
2265
Douglas Gregor910f8002010-11-07 23:05:16 +00002266 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002267 break;
2268 }
2269
2270 // We have a template argument that actually does refer to a class
2271 // template, template alias, or template template parameter, and
2272 // therefore cannot be a non-type template argument.
2273 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2274 << Arg.getSourceRange();
2275
2276 Diag(Param->getLocation(), diag::note_template_param_here);
2277 return true;
2278
2279 case TemplateArgument::Type: {
2280 // We have a non-type template parameter but the template
2281 // argument is a type.
2282
2283 // C++ [temp.arg]p2:
2284 // In a template-argument, an ambiguity between a type-id and
2285 // an expression is resolved to a type-id, regardless of the
2286 // form of the corresponding template-parameter.
2287 //
2288 // We warn specifically about this case, since it can be rather
2289 // confusing for users.
2290 QualType T = Arg.getArgument().getAsType();
2291 SourceRange SR = Arg.getSourceRange();
2292 if (T->isFunctionType())
2293 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2294 else
2295 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2296 Diag(Param->getLocation(), diag::note_template_param_here);
2297 return true;
2298 }
2299
2300 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002301 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002302 break;
2303 }
2304
2305 return false;
2306 }
2307
2308
2309 // Check template template parameters.
2310 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2311
2312 // Substitute into the template parameter list of the template
2313 // template parameter, since previously-supplied template arguments
2314 // may appear within the template template parameter.
2315 {
2316 // Set up a template instantiation context.
2317 LocalInstantiationScope Scope(*this);
2318 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002319 TempParm, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002320 SourceRange(TemplateLoc, RAngleLoc));
2321
Douglas Gregor910f8002010-11-07 23:05:16 +00002322 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2323 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002324 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2325 SubstDecl(TempParm, CurContext,
2326 MultiLevelTemplateArgumentList(TemplateArgs)));
2327 if (!TempParm)
2328 return true;
Douglas Gregore7526412009-11-11 19:31:23 +00002329 }
2330
2331 switch (Arg.getArgument().getKind()) {
2332 case TemplateArgument::Null:
2333 assert(false && "Should never see a NULL template argument here");
2334 return true;
2335
2336 case TemplateArgument::Template:
2337 if (CheckTemplateArgument(TempParm, Arg))
2338 return true;
2339
Douglas Gregor910f8002010-11-07 23:05:16 +00002340 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002341 break;
2342
2343 case TemplateArgument::Expression:
2344 case TemplateArgument::Type:
2345 // We have a template template parameter but the template
2346 // argument does not refer to a template.
2347 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2348 return true;
2349
2350 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002351 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002352 "Declaration argument with template template parameter");
2353 break;
2354 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002355 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002356 "Integral argument with template template parameter");
2357 break;
2358
2359 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002360 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002361 break;
2362 }
2363
2364 return false;
2365}
2366
Douglas Gregorc15cb382009-02-09 23:23:08 +00002367/// \brief Check that the given template argument list is well-formed
2368/// for specializing the given template.
2369bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2370 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002371 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002372 bool PartialTemplateArgs,
Douglas Gregor910f8002010-11-07 23:05:16 +00002373 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002374 TemplateParameterList *Params = Template->getTemplateParameters();
2375 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002376 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002377 bool Invalid = false;
2378
John McCalld5532b62009-11-23 01:53:49 +00002379 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2380
Mike Stump1eb44332009-09-09 15:08:12 +00002381 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002382 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002383
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002384 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002385 (NumArgs < Params->getMinRequiredArguments() &&
2386 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002387 // FIXME: point at either the first arg beyond what we can handle,
2388 // or the '>', depending on whether we have too many or too few
2389 // arguments.
2390 SourceRange Range;
2391 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002392 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002393 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2394 << (NumArgs > NumParams)
2395 << (isa<ClassTemplateDecl>(Template)? 0 :
2396 isa<FunctionTemplateDecl>(Template)? 1 :
2397 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2398 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002399 Diag(Template->getLocation(), diag::note_template_decl_here)
2400 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002401 Invalid = true;
2402 }
Mike Stump1eb44332009-09-09 15:08:12 +00002403
2404 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002405 // [...] The type and form of each template-argument specified in
2406 // a template-id shall match the type and form specified for the
2407 // corresponding parameter declared by the template in its
2408 // template-parameter-list.
Douglas Gregor14be16b2010-12-20 16:57:52 +00002409 llvm::SmallVector<TemplateArgument, 2> ArgumentPack;
2410 TemplateParameterList::iterator Param = Params->begin(),
2411 ParamEnd = Params->end();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002412 unsigned ArgIdx = 0;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002413 while (Param != ParamEnd) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002414 if (ArgIdx > NumArgs && PartialTemplateArgs)
2415 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002416
Douglas Gregorf35f8282009-11-11 21:54:23 +00002417 if (ArgIdx < NumArgs) {
2418 // Check the template argument we were given.
2419 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2420 TemplateLoc, RAngleLoc, Converted))
2421 return true;
2422
Douglas Gregor14be16b2010-12-20 16:57:52 +00002423 if ((*Param)->isTemplateParameterPack()) {
2424 // The template parameter was a template parameter pack, so take the
2425 // deduced argument and place it on the argument pack. Note that we
2426 // stay on the same template parameter so that we can deduce more
2427 // arguments.
2428 ArgumentPack.push_back(Converted.back());
2429 Converted.pop_back();
2430 } else {
2431 // Move to the next template parameter.
2432 ++Param;
2433 }
2434 ++ArgIdx;
Douglas Gregorf35f8282009-11-11 21:54:23 +00002435 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002436 }
Douglas Gregore7526412009-11-11 19:31:23 +00002437
Douglas Gregor14be16b2010-12-20 16:57:52 +00002438 // If we have a template parameter pack with no more corresponding
2439 // arguments, just break out now and we'll fill in the argument pack below.
2440 if ((*Param)->isTemplateParameterPack())
2441 break;
2442
Douglas Gregorf35f8282009-11-11 21:54:23 +00002443 // We have a default template argument that we will use.
2444 TemplateArgumentLoc Arg;
2445
2446 // Retrieve the default template argument from the template
2447 // parameter. For each kind of template parameter, we substitute the
2448 // template arguments provided thus far and any "outer" template arguments
2449 // (when the template parameter was part of a nested template) into
2450 // the default argument.
2451 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2452 if (!TTP->hasDefaultArgument()) {
2453 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2454 break;
2455 }
2456
John McCalla93c9342009-12-07 02:54:59 +00002457 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002458 Template,
2459 TemplateLoc,
2460 RAngleLoc,
2461 TTP,
2462 Converted);
2463 if (!ArgType)
2464 return true;
2465
2466 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2467 ArgType);
2468 } else if (NonTypeTemplateParmDecl *NTTP
2469 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2470 if (!NTTP->hasDefaultArgument()) {
2471 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2472 break;
2473 }
2474
John McCall60d7b3a2010-08-24 06:29:42 +00002475 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002476 TemplateLoc,
2477 RAngleLoc,
2478 NTTP,
2479 Converted);
2480 if (E.isInvalid())
2481 return true;
2482
2483 Expr *Ex = E.takeAs<Expr>();
2484 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2485 } else {
2486 TemplateTemplateParmDecl *TempParm
2487 = cast<TemplateTemplateParmDecl>(*Param);
2488
2489 if (!TempParm->hasDefaultArgument()) {
2490 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2491 break;
2492 }
2493
2494 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2495 TemplateLoc,
2496 RAngleLoc,
2497 TempParm,
2498 Converted);
2499 if (Name.isNull())
2500 return true;
2501
2502 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2503 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2504 TempParm->getDefaultArgument().getTemplateNameLoc());
2505 }
2506
2507 // Introduce an instantiation record that describes where we are using
2508 // the default template argument.
2509 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002510 Converted.data(), Converted.size(),
Douglas Gregorf35f8282009-11-11 21:54:23 +00002511 SourceRange(TemplateLoc, RAngleLoc));
2512
2513 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002514 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002515 RAngleLoc, Converted))
2516 return true;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002517
2518 // Move to the next template parameter and argument.
2519 ++Param;
2520 ++ArgIdx;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002521 }
Douglas Gregor14be16b2010-12-20 16:57:52 +00002522
2523 // Form argument packs for each of the parameter packs remaining.
2524 while (Param != ParamEnd) {
2525 if ((*Param)->isTemplateParameterPack()) {
2526 // The parameter pack takes the contents of the current argument pack,
2527 // which we built up earlier.
2528 if (ArgumentPack.empty()) {
2529 Converted.push_back(TemplateArgument(0, 0));
2530 } else {
2531 TemplateArgument *PackedArgs
2532 = new (Context) TemplateArgument [ArgumentPack.size()];
2533 std::copy(ArgumentPack.begin(), ArgumentPack.end(), PackedArgs);
2534 Converted.push_back(TemplateArgument(PackedArgs, ArgumentPack.size()));
2535 ArgumentPack.clear();
2536 }
2537 }
2538
2539 ++Param;
2540 }
2541
Douglas Gregorc15cb382009-02-09 23:23:08 +00002542 return Invalid;
2543}
2544
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002545namespace {
2546 class UnnamedLocalNoLinkageFinder
2547 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2548 {
2549 Sema &S;
2550 SourceRange SR;
2551
2552 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2553
2554 public:
2555 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2556
2557 bool Visit(QualType T) {
2558 return inherited::Visit(T.getTypePtr());
2559 }
2560
2561#define TYPE(Class, Parent) \
2562 bool Visit##Class##Type(const Class##Type *);
2563#define ABSTRACT_TYPE(Class, Parent) \
2564 bool Visit##Class##Type(const Class##Type *) { return false; }
2565#define NON_CANONICAL_TYPE(Class, Parent) \
2566 bool Visit##Class##Type(const Class##Type *) { return false; }
2567#include "clang/AST/TypeNodes.def"
2568
2569 bool VisitTagDecl(const TagDecl *Tag);
2570 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2571 };
2572}
2573
2574bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2575 return false;
2576}
2577
2578bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2579 return Visit(T->getElementType());
2580}
2581
2582bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2583 return Visit(T->getPointeeType());
2584}
2585
2586bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2587 const BlockPointerType* T) {
2588 return Visit(T->getPointeeType());
2589}
2590
2591bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2592 const LValueReferenceType* T) {
2593 return Visit(T->getPointeeType());
2594}
2595
2596bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2597 const RValueReferenceType* T) {
2598 return Visit(T->getPointeeType());
2599}
2600
2601bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2602 const MemberPointerType* T) {
2603 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2604}
2605
2606bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2607 const ConstantArrayType* T) {
2608 return Visit(T->getElementType());
2609}
2610
2611bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2612 const IncompleteArrayType* T) {
2613 return Visit(T->getElementType());
2614}
2615
2616bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2617 const VariableArrayType* T) {
2618 return Visit(T->getElementType());
2619}
2620
2621bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2622 const DependentSizedArrayType* T) {
2623 return Visit(T->getElementType());
2624}
2625
2626bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2627 const DependentSizedExtVectorType* T) {
2628 return Visit(T->getElementType());
2629}
2630
2631bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2632 return Visit(T->getElementType());
2633}
2634
2635bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2636 return Visit(T->getElementType());
2637}
2638
2639bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2640 const FunctionProtoType* T) {
2641 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2642 AEnd = T->arg_type_end();
2643 A != AEnd; ++A) {
2644 if (Visit(*A))
2645 return true;
2646 }
2647
2648 return Visit(T->getResultType());
2649}
2650
2651bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2652 const FunctionNoProtoType* T) {
2653 return Visit(T->getResultType());
2654}
2655
2656bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2657 const UnresolvedUsingType*) {
2658 return false;
2659}
2660
2661bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2662 return false;
2663}
2664
2665bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2666 return Visit(T->getUnderlyingType());
2667}
2668
2669bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2670 return false;
2671}
2672
2673bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2674 return VisitTagDecl(T->getDecl());
2675}
2676
2677bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2678 return VisitTagDecl(T->getDecl());
2679}
2680
2681bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2682 const TemplateTypeParmType*) {
2683 return false;
2684}
2685
2686bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2687 const TemplateSpecializationType*) {
2688 return false;
2689}
2690
2691bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2692 const InjectedClassNameType* T) {
2693 return VisitTagDecl(T->getDecl());
2694}
2695
2696bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2697 const DependentNameType* T) {
2698 return VisitNestedNameSpecifier(T->getQualifier());
2699}
2700
2701bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2702 const DependentTemplateSpecializationType* T) {
2703 return VisitNestedNameSpecifier(T->getQualifier());
2704}
2705
Douglas Gregor7536dd52010-12-20 02:24:11 +00002706bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
2707 const PackExpansionType* T) {
2708 return Visit(T->getPattern());
2709}
2710
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002711bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2712 return false;
2713}
2714
2715bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2716 const ObjCInterfaceType *) {
2717 return false;
2718}
2719
2720bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2721 const ObjCObjectPointerType *) {
2722 return false;
2723}
2724
2725bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2726 if (Tag->getDeclContext()->isFunctionOrMethod()) {
2727 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2728 << S.Context.getTypeDeclType(Tag) << SR;
2729 return true;
2730 }
2731
2732 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2733 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2734 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2735 return true;
2736 }
2737
2738 return false;
2739}
2740
2741bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2742 NestedNameSpecifier *NNS) {
2743 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2744 return true;
2745
2746 switch (NNS->getKind()) {
2747 case NestedNameSpecifier::Identifier:
2748 case NestedNameSpecifier::Namespace:
2749 case NestedNameSpecifier::Global:
2750 return false;
2751
2752 case NestedNameSpecifier::TypeSpec:
2753 case NestedNameSpecifier::TypeSpecWithTemplate:
2754 return Visit(QualType(NNS->getAsType(), 0));
2755 }
Fariborz Jahanian7b1ec6c2010-10-13 16:19:16 +00002756 return false;
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002757}
2758
2759
Douglas Gregorc15cb382009-02-09 23:23:08 +00002760/// \brief Check a template argument against its corresponding
2761/// template type parameter.
2762///
2763/// This routine implements the semantics of C++ [temp.arg.type]. It
2764/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002765bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002766 TypeSourceInfo *ArgInfo) {
2767 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002768 QualType Arg = ArgInfo->getType();
Douglas Gregor0fddb972010-05-22 16:17:30 +00002769 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth17fb8552010-09-03 21:12:34 +00002770
2771 if (Arg->isVariablyModifiedType()) {
2772 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002773 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00002774 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002775 }
2776
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002777 // C++03 [temp.arg.type]p2:
2778 // A local type, a type with no linkage, an unnamed type or a type
2779 // compounded from any of these types shall not be used as a
2780 // template-argument for a template type-parameter.
2781 //
2782 // C++0x allows these, and even in C++03 we allow them as an extension with
2783 // a warning.
Douglas Gregordb4d4bb2010-10-13 18:05:20 +00002784 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002785 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2786 (void)Finder.Visit(Context.getCanonicalType(Arg));
2787 }
2788
Douglas Gregorc15cb382009-02-09 23:23:08 +00002789 return false;
2790}
2791
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002792/// \brief Checks whether the given template argument is the address
2793/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002794static bool
2795CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2796 NonTypeTemplateParmDecl *Param,
2797 QualType ParamType,
2798 Expr *ArgIn,
2799 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002800 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002801 Expr *Arg = ArgIn;
2802 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002803
2804 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002805 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002806 Arg = Cast->getSubExpr();
2807
2808 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002809 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002810 // A template-argument for a non-type, non-template
2811 // template-parameter shall be one of: [...]
2812 //
2813 // -- the address of an object or function with external
2814 // linkage, including function templates and function
2815 // template-ids but excluding non-static class members,
2816 // expressed as & id-expression where the & is optional if
2817 // the name refers to a function or array, or if the
2818 // corresponding template-parameter is a reference; or
2819 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002820
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002821 // In C++98/03 mode, give an extension warning on any extra parentheses.
2822 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2823 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002824 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002825 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002826 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002827 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002828 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002829 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002830 }
2831
2832 Arg = Parens->getSubExpr();
2833 }
2834
Douglas Gregorb7a09262010-04-01 18:32:35 +00002835 bool AddressTaken = false;
2836 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002837 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002838 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002839 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002840 AddressTaken = true;
2841 AddrOpLoc = UnOp->getOperatorLoc();
2842 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002843 } else
2844 DRE = dyn_cast<DeclRefExpr>(Arg);
2845
Douglas Gregorb7a09262010-04-01 18:32:35 +00002846 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002847 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2848 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002849 S.Diag(Param->getLocation(), diag::note_template_param_here);
2850 return true;
2851 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002852
2853 // Stop checking the precise nature of the argument if it is value dependent,
2854 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002855 if (Arg->isValueDependent()) {
John McCall3fa5cae2010-10-26 07:05:15 +00002856 Converted = TemplateArgument(ArgIn);
Chandler Carruth038cc392010-01-31 10:01:20 +00002857 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002858 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002859
Douglas Gregorb7a09262010-04-01 18:32:35 +00002860 if (!isa<ValueDecl>(DRE->getDecl())) {
2861 S.Diag(Arg->getSourceRange().getBegin(),
2862 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002863 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002864 S.Diag(Param->getLocation(), diag::note_template_param_here);
2865 return true;
2866 }
2867
2868 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002869
2870 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002871 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2872 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002873 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002874 S.Diag(Param->getLocation(), diag::note_template_param_here);
2875 return true;
2876 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002877
2878 // Cannot refer to non-static member functions
2879 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002880 if (!Method->isStatic()) {
2881 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002882 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002883 S.Diag(Param->getLocation(), diag::note_template_param_here);
2884 return true;
2885 }
Mike Stump1eb44332009-09-09 15:08:12 +00002886
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002887 // Functions must have external linkage.
2888 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002889 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002890 S.Diag(Arg->getSourceRange().getBegin(),
2891 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002892 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002893 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002894 << true;
2895 return true;
2896 }
2897
2898 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002899 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002900
Douglas Gregorb7a09262010-04-01 18:32:35 +00002901 // If the template parameter has pointer type, the function decays.
2902 if (ParamType->isPointerType() && !AddressTaken)
2903 ArgType = S.Context.getPointerType(Func->getType());
2904 else if (AddressTaken && ParamType->isReferenceType()) {
2905 // If we originally had an address-of operator, but the
2906 // parameter has reference type, complain and (if things look
2907 // like they will work) drop the address-of operator.
2908 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2909 ParamType.getNonReferenceType())) {
2910 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2911 << ParamType;
2912 S.Diag(Param->getLocation(), diag::note_template_param_here);
2913 return true;
2914 }
2915
2916 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2917 << ParamType
2918 << FixItHint::CreateRemoval(AddrOpLoc);
2919 S.Diag(Param->getLocation(), diag::note_template_param_here);
2920
2921 ArgType = Func->getType();
2922 }
2923 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002924 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002925 S.Diag(Arg->getSourceRange().getBegin(),
2926 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002927 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002928 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002929 << true;
2930 return true;
2931 }
2932
Douglas Gregorb7a09262010-04-01 18:32:35 +00002933 // A value of reference type is not an object.
2934 if (Var->getType()->isReferenceType()) {
2935 S.Diag(Arg->getSourceRange().getBegin(),
2936 diag::err_template_arg_reference_var)
2937 << Var->getType() << Arg->getSourceRange();
2938 S.Diag(Param->getLocation(), diag::note_template_param_here);
2939 return true;
2940 }
2941
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002942 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002943 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002944
2945 // If the template parameter has pointer type, we must have taken
2946 // the address of this object.
2947 if (ParamType->isReferenceType()) {
2948 if (AddressTaken) {
2949 // If we originally had an address-of operator, but the
2950 // parameter has reference type, complain and (if things look
2951 // like they will work) drop the address-of operator.
2952 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2953 ParamType.getNonReferenceType())) {
2954 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2955 << ParamType;
2956 S.Diag(Param->getLocation(), diag::note_template_param_here);
2957 return true;
2958 }
2959
2960 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2961 << ParamType
2962 << FixItHint::CreateRemoval(AddrOpLoc);
2963 S.Diag(Param->getLocation(), diag::note_template_param_here);
2964
2965 ArgType = Var->getType();
2966 }
2967 } else if (!AddressTaken && ParamType->isPointerType()) {
2968 if (Var->getType()->isArrayType()) {
2969 // Array-to-pointer decay.
2970 ArgType = S.Context.getArrayDecayedType(Var->getType());
2971 } else {
2972 // If the template parameter has pointer type but the address of
2973 // this object was not taken, complain and (possibly) recover by
2974 // taking the address of the entity.
2975 ArgType = S.Context.getPointerType(Var->getType());
2976 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2977 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2978 << ParamType;
2979 S.Diag(Param->getLocation(), diag::note_template_param_here);
2980 return true;
2981 }
2982
2983 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2984 << ParamType
2985 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2986
2987 S.Diag(Param->getLocation(), diag::note_template_param_here);
2988 }
2989 }
2990 } else {
2991 // We found something else, but we don't know specifically what it is.
2992 S.Diag(Arg->getSourceRange().getBegin(),
2993 diag::err_template_arg_not_object_or_func)
2994 << Arg->getSourceRange();
2995 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2996 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002997 }
Mike Stump1eb44332009-09-09 15:08:12 +00002998
Douglas Gregorb7a09262010-04-01 18:32:35 +00002999 if (ParamType->isPointerType() &&
3000 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
3001 S.IsQualificationConversion(ArgType, ParamType)) {
3002 // For pointer-to-object types, qualification conversions are
3003 // permitted.
3004 } else {
3005 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
3006 if (!ParamRef->getPointeeType()->isFunctionType()) {
3007 // C++ [temp.arg.nontype]p5b3:
3008 // For a non-type template-parameter of type reference to
3009 // object, no conversions apply. The type referred to by the
3010 // reference may be more cv-qualified than the (otherwise
3011 // identical) type of the template- argument. The
3012 // template-parameter is bound directly to the
3013 // template-argument, which shall be an lvalue.
3014
3015 // FIXME: Other qualifiers?
3016 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
3017 unsigned ArgQuals = ArgType.getCVRQualifiers();
3018
3019 if ((ParamQuals | ArgQuals) != ParamQuals) {
3020 S.Diag(Arg->getSourceRange().getBegin(),
3021 diag::err_template_arg_ref_bind_ignores_quals)
3022 << ParamType << Arg->getType()
3023 << Arg->getSourceRange();
3024 S.Diag(Param->getLocation(), diag::note_template_param_here);
3025 return true;
3026 }
3027 }
3028 }
3029
3030 // At this point, the template argument refers to an object or
3031 // function with external linkage. We now need to check whether the
3032 // argument and parameter types are compatible.
3033 if (!S.Context.hasSameUnqualifiedType(ArgType,
3034 ParamType.getNonReferenceType())) {
3035 // We can't perform this conversion or binding.
3036 if (ParamType->isReferenceType())
3037 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
3038 << ParamType << Arg->getType() << Arg->getSourceRange();
3039 else
3040 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
3041 << Arg->getType() << ParamType << Arg->getSourceRange();
3042 S.Diag(Param->getLocation(), diag::note_template_param_here);
3043 return true;
3044 }
3045 }
3046
3047 // Create the template argument.
3048 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00003049 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00003050 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003051}
3052
3053/// \brief Checks whether the given template argument is a pointer to
3054/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003055bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
3056 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003057 bool Invalid = false;
3058
3059 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003060 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003061 Arg = Cast->getSubExpr();
3062
3063 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003064 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003065 // A template-argument for a non-type, non-template
3066 // template-parameter shall be one of: [...]
3067 //
3068 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003069 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003070
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003071 // In C++98/03 mode, give an extension warning on any extra parentheses.
3072 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3073 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003074 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003075 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00003076 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003077 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003078 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003079 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003080 }
3081
3082 Arg = Parens->getSubExpr();
3083 }
3084
Douglas Gregorcaddba02009-11-12 18:38:13 +00003085 // A pointer-to-member constant written &Class::member.
3086 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00003087 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00003088 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3089 if (DRE && !DRE->getQualifier())
3090 DRE = 0;
3091 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00003092 }
3093 // A constant of pointer-to-member type.
3094 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
3095 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
3096 if (VD->getType()->isMemberPointerType()) {
3097 if (isa<NonTypeTemplateParmDecl>(VD) ||
3098 (isa<VarDecl>(VD) &&
3099 Context.getCanonicalType(VD->getType()).isConstQualified())) {
3100 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003101 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003102 else
3103 Converted = TemplateArgument(VD->getCanonicalDecl());
3104 return Invalid;
3105 }
3106 }
3107 }
3108
3109 DRE = 0;
3110 }
3111
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003112 if (!DRE)
3113 return Diag(Arg->getSourceRange().getBegin(),
3114 diag::err_template_arg_not_pointer_to_member_form)
3115 << Arg->getSourceRange();
3116
3117 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3118 assert((isa<FieldDecl>(DRE->getDecl()) ||
3119 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3120 "Only non-static member pointers can make it here");
3121
3122 // Okay: this is the address of a non-static member, and therefore
3123 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003124 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003125 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003126 else
3127 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003128 return Invalid;
3129 }
3130
3131 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00003132 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003133 diag::err_template_arg_not_pointer_to_member_form)
3134 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003135 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003136 diag::note_template_arg_refers_here);
3137 return true;
3138}
3139
Douglas Gregorc15cb382009-02-09 23:23:08 +00003140/// \brief Check a template argument against its corresponding
3141/// non-type template parameter.
3142///
Douglas Gregor2943aed2009-03-03 04:44:36 +00003143/// This routine implements the semantics of C++ [temp.arg.nontype].
3144/// It returns true if an error occurred, and false otherwise. \p
3145/// InstantiatedParamType is the type of the non-type template
3146/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003147///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003148/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00003149bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00003150 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00003151 TemplateArgument &Converted,
3152 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00003153 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3154
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003155 // If either the parameter has a dependent type or the argument is
3156 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00003157 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3158 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003159 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003160 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00003161 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003162
3163 // C++ [temp.arg.nontype]p5:
3164 // The following conversions are performed on each expression used
3165 // as a non-type template-argument. If a non-type
3166 // template-argument cannot be converted to the type of the
3167 // corresponding template-parameter then the program is
3168 // ill-formed.
3169 //
3170 // -- for a non-type template-parameter of integral or
3171 // enumeration type, integral promotions (4.5) and integral
3172 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00003173 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00003174 QualType ArgType = Arg->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003175 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003176 // C++ [temp.arg.nontype]p1:
3177 // A template-argument for a non-type, non-template
3178 // template-parameter shall be one of:
3179 //
3180 // -- an integral constant-expression of integral or enumeration
3181 // type; or
3182 // -- the name of a non-type template-parameter; or
3183 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003184 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003185 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003186 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003187 diag::err_template_arg_not_integral_or_enumeral)
3188 << ArgType << Arg->getSourceRange();
3189 Diag(Param->getLocation(), diag::note_template_param_here);
3190 return true;
3191 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003192 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003193 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3194 << ArgType << Arg->getSourceRange();
3195 return true;
3196 }
3197
Douglas Gregor02024a92010-03-28 02:42:43 +00003198 // From here on out, all we care about are the unqualified forms
3199 // of the parameter and argument types.
3200 ParamType = ParamType.getUnqualifiedType();
3201 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003202
3203 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00003204 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003205 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00003206 } else if (CTAK == CTAK_Deduced) {
3207 // C++ [temp.deduct.type]p17:
3208 // If, in the declaration of a function template with a non-type
3209 // template-parameter, the non-type template- parameter is used
3210 // in an expression in the function parameter-list and, if the
3211 // corresponding template-argument is deduced, the
3212 // template-argument type shall match the type of the
3213 // template-parameter exactly, except that a template-argument
3214 // deduced from an array bound may be of any integral type.
3215 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3216 << ArgType << ParamType;
3217 Diag(Param->getLocation(), diag::note_template_param_here);
John McCalldaa8e4e2010-11-15 09:13:47 +00003218 return true;
3219 } else if (ParamType->isBooleanType()) {
3220 // This is an integral-to-boolean conversion.
3221 ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003222 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3223 !ParamType->isEnumeralType()) {
3224 // This is an integral promotion or conversion.
John McCall2de56d12010-08-25 11:45:40 +00003225 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003226 } else {
3227 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003228 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003229 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003230 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003231 Diag(Param->getLocation(), diag::note_template_param_here);
3232 return true;
3233 }
3234
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003235 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00003236 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003237 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003238
3239 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003240 llvm::APSInt OldValue = Value;
3241
3242 // Coerce the template argument's value to the value it will have
3243 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003244 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003245 if (Value.getBitWidth() != AllowedBits)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003246 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003247 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003248
3249 // Complain if an unsigned parameter received a negative value.
3250 if (IntegerType->isUnsignedIntegerType()
3251 && (OldValue.isSigned() && OldValue.isNegative())) {
3252 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3253 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3254 << Arg->getSourceRange();
3255 Diag(Param->getLocation(), diag::note_template_param_here);
3256 }
3257
3258 // Complain if we overflowed the template parameter's type.
3259 unsigned RequiredBits;
3260 if (IntegerType->isUnsignedIntegerType())
3261 RequiredBits = OldValue.getActiveBits();
3262 else if (OldValue.isUnsigned())
3263 RequiredBits = OldValue.getActiveBits() + 1;
3264 else
3265 RequiredBits = OldValue.getMinSignedBits();
3266 if (RequiredBits > AllowedBits) {
3267 Diag(Arg->getSourceRange().getBegin(),
3268 diag::warn_template_arg_too_large)
3269 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3270 << Arg->getSourceRange();
3271 Diag(Param->getLocation(), diag::note_template_param_here);
3272 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003273 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003274
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003275 // Add the value of this argument to the list of converted
3276 // arguments. We use the bitwidth and signedness of the template
3277 // parameter.
3278 if (Arg->isValueDependent()) {
3279 // The argument is value-dependent. Create a new
3280 // TemplateArgument with the converted expression.
3281 Converted = TemplateArgument(Arg);
3282 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003283 }
3284
John McCall833ca992009-10-29 08:12:44 +00003285 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00003286 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003287 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003288 return false;
3289 }
Douglas Gregora35284b2009-02-11 00:19:33 +00003290
John McCall6bb80172010-03-30 21:47:33 +00003291 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3292
Douglas Gregorb7a09262010-04-01 18:32:35 +00003293 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3294 // from a template argument of type std::nullptr_t to a non-type
3295 // template parameter of type pointer to object, pointer to
3296 // function, or pointer-to-member, respectively.
3297 if (ArgType->isNullPtrType() &&
3298 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3299 Converted = TemplateArgument((NamedDecl *)0);
3300 return false;
3301 }
3302
Douglas Gregorb86b0572009-02-11 01:18:59 +00003303 // Handle pointer-to-function, reference-to-function, and
3304 // pointer-to-member-function all in (roughly) the same way.
3305 if (// -- For a non-type template-parameter of type pointer to
3306 // function, only the function-to-pointer conversion (4.3) is
3307 // applied. If the template-argument represents a set of
3308 // overloaded functions (or a pointer to such), the matching
3309 // function is selected from the set (13.4).
3310 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003311 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003312 // -- For a non-type template-parameter of type reference to
3313 // function, no conversions apply. If the template-argument
3314 // represents a set of overloaded functions, the matching
3315 // function is selected from the set (13.4).
3316 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003317 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003318 // -- For a non-type template-parameter of type pointer to
3319 // member function, no conversions apply. If the
3320 // template-argument represents a set of overloaded member
3321 // functions, the matching member function is selected from
3322 // the set (13.4).
3323 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003324 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00003325 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003326
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003327 if (Arg->getType() == Context.OverloadTy) {
3328 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3329 true,
3330 FoundResult)) {
3331 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3332 return true;
3333
3334 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3335 ArgType = Arg->getType();
3336 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003337 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00003338 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003339
Douglas Gregorb7a09262010-04-01 18:32:35 +00003340 if (!ParamType->isMemberPointerType())
3341 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3342 ParamType,
3343 Arg, Converted);
3344
3345 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCall2de56d12010-08-25 11:45:40 +00003346 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb7a09262010-04-01 18:32:35 +00003347 } else if (!Context.hasSameUnqualifiedType(ArgType,
3348 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00003349 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003350 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00003351 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003352 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00003353 Diag(Param->getLocation(), diag::note_template_param_here);
3354 return true;
3355 }
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Douglas Gregorb7a09262010-04-01 18:32:35 +00003357 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00003358 }
3359
Chris Lattnerfe90de72009-02-20 21:37:53 +00003360 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003361 // -- for a non-type template-parameter of type pointer to
3362 // object, qualification conversions (4.4) and the
3363 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00003364 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00003365 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003366 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003367
Douglas Gregorb7a09262010-04-01 18:32:35 +00003368 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3369 ParamType,
3370 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003371 }
Mike Stump1eb44332009-09-09 15:08:12 +00003372
Ted Kremenek6217b802009-07-29 21:53:49 +00003373 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003374 // -- For a non-type template-parameter of type reference to
3375 // object, no conversions apply. The type referred to by the
3376 // reference may be more cv-qualified than the (otherwise
3377 // identical) type of the template-argument. The
3378 // template-parameter is bound directly to the
3379 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00003380 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003381 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003382
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003383 if (Arg->getType() == Context.OverloadTy) {
3384 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3385 ParamRefType->getPointeeType(),
3386 true,
3387 FoundResult)) {
3388 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3389 return true;
3390
3391 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3392 ArgType = Arg->getType();
3393 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00003394 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00003395 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003396
Douglas Gregorb7a09262010-04-01 18:32:35 +00003397 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3398 ParamType,
3399 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00003400 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00003401
3402 // -- For a non-type template-parameter of type pointer to data
3403 // member, qualification conversions (4.4) are applied.
3404 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3405
Douglas Gregor8e6563b2009-02-11 18:22:40 +00003406 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00003407 // Types match exactly: nothing more to do here.
3408 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCall2de56d12010-08-25 11:45:40 +00003409 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor658bbb52009-02-11 16:16:59 +00003410 } else {
3411 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003412 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00003413 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003414 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00003415 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00003416 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00003417 }
3418
Douglas Gregorcaddba02009-11-12 18:38:13 +00003419 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00003420}
3421
3422/// \brief Check a template argument against its corresponding
3423/// template template parameter.
3424///
3425/// This routine implements the semantics of C++ [temp.arg.template].
3426/// It returns true if an error occurred, and false otherwise.
3427bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003428 const TemplateArgumentLoc &Arg) {
3429 TemplateName Name = Arg.getArgument().getAsTemplate();
3430 TemplateDecl *Template = Name.getAsTemplateDecl();
3431 if (!Template) {
3432 // Any dependent template name is fine.
3433 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3434 return false;
3435 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003436
3437 // C++ [temp.arg.template]p1:
3438 // A template-argument for a template template-parameter shall be
3439 // the name of a class template, expressed as id-expression. Only
3440 // primary class templates are considered when matching the
3441 // template template argument with the corresponding parameter;
3442 // partial specializations are not considered even if their
3443 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003444 //
3445 // Note that we also allow template template parameters here, which
3446 // will happen when we are dealing with, e.g., class template
3447 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003448 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003449 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003450 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003451 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003452 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003453 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003454 << Template;
3455 }
3456
3457 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3458 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003459 true,
3460 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003461 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003462}
3463
Douglas Gregor02024a92010-03-28 02:42:43 +00003464/// \brief Given a non-type template argument that refers to a
3465/// declaration and the type of its corresponding non-type template
3466/// parameter, produce an expression that properly refers to that
3467/// declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00003468ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003469Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3470 QualType ParamType,
3471 SourceLocation Loc) {
3472 assert(Arg.getKind() == TemplateArgument::Declaration &&
3473 "Only declaration template arguments permitted here");
3474 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3475
3476 if (VD->getDeclContext()->isRecord() &&
3477 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3478 // If the value is a class member, we might have a pointer-to-member.
3479 // Determine whether the non-type template template parameter is of
3480 // pointer-to-member type. If so, we need to build an appropriate
3481 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3482 // would refer to the member itself.
3483 if (ParamType->isMemberPointerType()) {
3484 QualType ClassType
3485 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3486 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00003487 = NestedNameSpecifier::Create(Context, 0, false,
3488 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00003489 CXXScopeSpec SS;
3490 SS.setScopeRep(Qualifier);
John McCalldfa1edb2010-11-23 20:48:44 +00003491
3492 // The actual value-ness of this is unimportant, but for
3493 // internal consistency's sake, references to instance methods
3494 // are r-values.
3495 ExprValueKind VK = VK_LValue;
3496 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
3497 VK = VK_RValue;
3498
John McCall60d7b3a2010-08-24 06:29:42 +00003499 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCallf89e55a2010-11-18 06:31:45 +00003500 VD->getType().getNonReferenceType(),
John McCalldfa1edb2010-11-23 20:48:44 +00003501 VK,
John McCallf89e55a2010-11-18 06:31:45 +00003502 Loc,
3503 &SS);
Douglas Gregor02024a92010-03-28 02:42:43 +00003504 if (RefExpr.isInvalid())
3505 return ExprError();
3506
John McCall2de56d12010-08-25 11:45:40 +00003507 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorc0c83002010-04-30 21:46:38 +00003508
3509 // We might need to perform a trailing qualification conversion, since
3510 // the element type on the parameter could be more qualified than the
3511 // element type in the expression we constructed.
3512 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3513 ParamType.getUnqualifiedType())) {
3514 Expr *RefE = RefExpr.takeAs<Expr>();
John McCall2de56d12010-08-25 11:45:40 +00003515 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorc0c83002010-04-30 21:46:38 +00003516 RefExpr = Owned(RefE);
3517 }
3518
Douglas Gregor02024a92010-03-28 02:42:43 +00003519 assert(!RefExpr.isInvalid() &&
3520 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003521 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003522 return move(RefExpr);
3523 }
3524 }
3525
3526 QualType T = VD->getType().getNonReferenceType();
3527 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003528 // When the non-type template parameter is a pointer, take the
3529 // address of the declaration.
John McCallf89e55a2010-11-18 06:31:45 +00003530 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003531 if (RefExpr.isInvalid())
3532 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003533
3534 if (T->isFunctionType() || T->isArrayType()) {
3535 // Decay functions and arrays.
3536 Expr *RefE = (Expr *)RefExpr.get();
3537 DefaultFunctionArrayConversion(RefE);
3538 if (RefE != RefExpr.get()) {
3539 RefExpr.release();
3540 RefExpr = Owned(RefE);
3541 }
3542
3543 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003544 }
3545
Douglas Gregorb7a09262010-04-01 18:32:35 +00003546 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00003547 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00003548 }
3549
John McCallf89e55a2010-11-18 06:31:45 +00003550 ExprValueKind VK = VK_RValue;
3551
Douglas Gregor02024a92010-03-28 02:42:43 +00003552 // If the non-type template parameter has reference type, qualify the
3553 // resulting declaration reference with the extra qualifiers on the
3554 // type that the reference refers to.
John McCallf89e55a2010-11-18 06:31:45 +00003555 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
3556 VK = VK_LValue;
3557 T = Context.getQualifiedType(T,
3558 TargetRef->getPointeeType().getQualifiers());
3559 }
Douglas Gregor02024a92010-03-28 02:42:43 +00003560
John McCallf89e55a2010-11-18 06:31:45 +00003561 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003562}
3563
3564/// \brief Construct a new expression that refers to the given
3565/// integral template argument with the given source-location
3566/// information.
3567///
3568/// This routine takes care of the mapping from an integral template
3569/// argument (which may have any integral type) to the appropriate
3570/// literal value.
John McCall60d7b3a2010-08-24 06:29:42 +00003571ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003572Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3573 SourceLocation Loc) {
3574 assert(Arg.getKind() == TemplateArgument::Integral &&
3575 "Operation is only value for integral template arguments");
3576 QualType T = Arg.getIntegralType();
3577 if (T->isCharType() || T->isWideCharType())
3578 return Owned(new (Context) CharacterLiteral(
3579 Arg.getAsIntegral()->getZExtValue(),
3580 T->isWideCharType(),
3581 T,
3582 Loc));
3583 if (T->isBooleanType())
3584 return Owned(new (Context) CXXBoolLiteralExpr(
3585 Arg.getAsIntegral()->getBoolValue(),
3586 T,
3587 Loc));
3588
Peter Collingbournefb7b3632010-12-15 15:06:14 +00003589 QualType BT;
3590 if (const EnumType *ET = T->getAs<EnumType>())
3591 BT = ET->getDecl()->getPromotionType();
3592 else
3593 BT = T;
3594
3595 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
3596 ImpCastExprToType(E, T, CK_IntegralCast);
3597
3598 return Owned(E);
Douglas Gregor02024a92010-03-28 02:42:43 +00003599}
3600
3601
Douglas Gregorddc29e12009-02-06 22:42:48 +00003602/// \brief Determine whether the given template parameter lists are
3603/// equivalent.
3604///
Mike Stump1eb44332009-09-09 15:08:12 +00003605/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003606/// source code as part of a new template declaration.
3607///
3608/// \param Old The old template parameter list, typically found via
3609/// name lookup of the template declared with this template parameter
3610/// list.
3611///
3612/// \param Complain If true, this routine will produce a diagnostic if
3613/// the template parameter lists are not equivalent.
3614///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003615/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003616///
3617/// \param TemplateArgLoc If this source location is valid, then we
3618/// are actually checking the template parameter list of a template
3619/// argument (New) against the template parameter list of its
3620/// corresponding template template parameter (Old). We produce
3621/// slightly different diagnostics in this scenario.
3622///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003623/// \returns True if the template parameter lists are equal, false
3624/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003625bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003626Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3627 TemplateParameterList *Old,
3628 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003629 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003630 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003631 if (Old->size() != New->size()) {
3632 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003633 unsigned NextDiag = diag::err_template_param_list_different_arity;
3634 if (TemplateArgLoc.isValid()) {
3635 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3636 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003637 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003638 Diag(New->getTemplateLoc(), NextDiag)
3639 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003640 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003641 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003642 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003643 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003644 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3645 }
3646
3647 return false;
3648 }
3649
3650 for (TemplateParameterList::iterator OldParm = Old->begin(),
3651 OldParmEnd = Old->end(), NewParm = New->begin();
3652 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3653 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003654 if (Complain) {
3655 unsigned NextDiag = diag::err_template_param_different_kind;
3656 if (TemplateArgLoc.isValid()) {
3657 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3658 NextDiag = diag::note_template_param_different_kind;
3659 }
3660 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003661 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003662 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003663 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003664 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003665 return false;
3666 }
3667
Douglas Gregora417b872010-06-04 08:34:32 +00003668 if (TemplateTypeParmDecl *OldTTP
3669 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3670 // Template type parameters are equivalent if either both are template
3671 // type parameter packs or neither are (since we know we're at the same
3672 // index).
3673 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3674 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3675 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3676 // allow one to match a template parameter pack in the template
3677 // parameter list of a template template parameter to one or more
3678 // template parameters in the template parameter list of the
3679 // corresponding template template argument.
3680 if (Complain) {
3681 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3682 if (TemplateArgLoc.isValid()) {
3683 Diag(TemplateArgLoc,
3684 diag::err_template_arg_template_params_mismatch);
3685 NextDiag = diag::note_template_parameter_pack_non_pack;
3686 }
3687 Diag(NewTTP->getLocation(), NextDiag)
3688 << 0 << NewTTP->isParameterPack();
3689 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3690 << 0 << OldTTP->isParameterPack();
3691 }
3692 return false;
3693 }
Mike Stump1eb44332009-09-09 15:08:12 +00003694 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003695 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3696 // The types of non-type template parameters must agree.
3697 NonTypeTemplateParmDecl *NewNTTP
3698 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003699
Douglas Gregorf457c1a2011-01-05 16:01:49 +00003700 if (OldNTTP->isParameterPack() != NewNTTP->isParameterPack()) {
3701 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3702 // allow one to match a template parameter pack in the template
3703 // parameter list of a template template parameter to one or more
3704 // template parameters in the template parameter list of the
3705 // corresponding template template argument.
3706 if (Complain) {
3707 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3708 if (TemplateArgLoc.isValid()) {
3709 Diag(TemplateArgLoc,
3710 diag::err_template_arg_template_params_mismatch);
3711 NextDiag = diag::note_template_parameter_pack_non_pack;
3712 }
3713 Diag(NewNTTP->getLocation(), NextDiag)
3714 << 1 << NewNTTP->isParameterPack();
3715 Diag(OldNTTP->getLocation(), diag::note_template_parameter_pack_here)
3716 << 1 << OldNTTP->isParameterPack();
3717 }
3718 return false;
3719 }
3720
Douglas Gregorfb898e12009-11-12 16:20:59 +00003721 // If we are matching a template template argument to a template
3722 // template parameter and one of the non-type template parameter types
3723 // is dependent, then we must wait until template instantiation time
3724 // to actually compare the arguments.
3725 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3726 (OldNTTP->getType()->isDependentType() ||
3727 NewNTTP->getType()->isDependentType()))
3728 continue;
3729
Douglas Gregorddc29e12009-02-06 22:42:48 +00003730 if (Context.getCanonicalType(OldNTTP->getType()) !=
3731 Context.getCanonicalType(NewNTTP->getType())) {
3732 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003733 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3734 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003735 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003736 diag::err_template_arg_template_params_mismatch);
3737 NextDiag = diag::note_template_nontype_parm_different_type;
3738 }
3739 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003740 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003741 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003742 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003743 diag::note_template_nontype_parm_prev_declaration)
3744 << OldNTTP->getType();
3745 }
3746 return false;
3747 }
3748 } else {
3749 // The template parameter lists of template template
3750 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003751 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003752 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003753 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003754 = cast<TemplateTemplateParmDecl>(*OldParm);
3755 TemplateTemplateParmDecl *NewTTP
3756 = cast<TemplateTemplateParmDecl>(*NewParm);
Douglas Gregorf457c1a2011-01-05 16:01:49 +00003757
3758 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3759 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3760 // allow one to match a template parameter pack in the template
3761 // parameter list of a template template parameter to one or more
3762 // template parameters in the template parameter list of the
3763 // corresponding template template argument.
3764 if (Complain) {
3765 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3766 if (TemplateArgLoc.isValid()) {
3767 Diag(TemplateArgLoc,
3768 diag::err_template_arg_template_params_mismatch);
3769 NextDiag = diag::note_template_parameter_pack_non_pack;
3770 }
3771 Diag(NewTTP->getLocation(), NextDiag)
3772 << 2 << NewTTP->isParameterPack();
3773 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3774 << 2 << OldTTP->isParameterPack();
3775 }
3776 return false;
3777 }
3778
Douglas Gregorddc29e12009-02-06 22:42:48 +00003779 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3780 OldTTP->getTemplateParameters(),
3781 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003782 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003783 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003784 return false;
3785 }
3786 }
3787
3788 return true;
3789}
3790
3791/// \brief Check whether a template can be declared within this scope.
3792///
3793/// If the template declaration is valid in this scope, returns
3794/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003795bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003796Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003797 // Find the nearest enclosing declaration scope.
3798 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3799 (S->getFlags() & Scope::TemplateParamScope) != 0)
3800 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003801
Douglas Gregorddc29e12009-02-06 22:42:48 +00003802 // C++ [temp]p2:
3803 // A template-declaration can appear only as a namespace scope or
3804 // class scope declaration.
3805 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003806 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3807 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003808 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003809 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003810
Eli Friedman1503f772009-07-31 01:43:05 +00003811 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003812 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003813
3814 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3815 return false;
3816
Mike Stump1eb44332009-09-09 15:08:12 +00003817 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003818 diag::err_template_outside_namespace_or_class_scope)
3819 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003820}
Douglas Gregorcc636682009-02-17 23:15:12 +00003821
Douglas Gregord5cb8762009-10-07 00:13:32 +00003822/// \brief Determine what kind of template specialization the given declaration
3823/// is.
3824static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3825 if (!D)
3826 return TSK_Undeclared;
3827
Douglas Gregorf6b11852009-10-08 15:14:33 +00003828 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3829 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003830 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3831 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003832 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3833 return Var->getTemplateSpecializationKind();
3834
Douglas Gregord5cb8762009-10-07 00:13:32 +00003835 return TSK_Undeclared;
3836}
3837
Douglas Gregor9302da62009-10-14 23:50:59 +00003838/// \brief Check whether a specialization is well-formed in the current
3839/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003840///
Douglas Gregor9302da62009-10-14 23:50:59 +00003841/// This routine determines whether a template specialization can be declared
3842/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003843///
3844/// \param S the semantic analysis object for which this check is being
3845/// performed.
3846///
3847/// \param Specialized the entity being specialized or instantiated, which
3848/// may be a kind of template (class template, function template, etc.) or
3849/// a member of a class template (member function, static data member,
3850/// member class).
3851///
3852/// \param PrevDecl the previous declaration of this entity, if any.
3853///
3854/// \param Loc the location of the explicit specialization or instantiation of
3855/// this entity.
3856///
3857/// \param IsPartialSpecialization whether this is a partial specialization of
3858/// a class template.
3859///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003860/// \returns true if there was an error that we cannot recover from, false
3861/// otherwise.
3862static bool CheckTemplateSpecializationScope(Sema &S,
3863 NamedDecl *Specialized,
3864 NamedDecl *PrevDecl,
3865 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003866 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003867 // Keep these "kind" numbers in sync with the %select statements in the
3868 // various diagnostics emitted by this routine.
3869 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003870 bool isTemplateSpecialization = false;
3871 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003872 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003873 isTemplateSpecialization = true;
3874 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003875 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003876 isTemplateSpecialization = true;
3877 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003878 EntityKind = 3;
3879 else if (isa<VarDecl>(Specialized))
3880 EntityKind = 4;
3881 else if (isa<RecordDecl>(Specialized))
3882 EntityKind = 5;
3883 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003884 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3885 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003886 return true;
3887 }
3888
Douglas Gregor88b70942009-02-25 22:02:03 +00003889 // C++ [temp.expl.spec]p2:
3890 // An explicit specialization shall be declared in the namespace
3891 // of which the template is a member, or, for member templates, in
3892 // the namespace of which the enclosing class or enclosing class
3893 // template is a member. An explicit specialization of a member
3894 // function, member class or static data member of a class
3895 // template shall be declared in the namespace of which the class
3896 // template is a member. Such a declaration may also be a
3897 // definition. If the declaration is not a definition, the
3898 // specialization may be defined later in the name- space in which
3899 // the explicit specialization was declared, or in a namespace
3900 // that encloses the one in which the explicit specialization was
3901 // declared.
Sebastian Redl7a126a42010-08-31 00:36:30 +00003902 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003903 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003904 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003905 return true;
3906 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003907
Douglas Gregor0a407472009-10-07 17:30:37 +00003908 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3909 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003910 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003911 return true;
3912 }
3913
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003914 // C++ [temp.class.spec]p6:
3915 // A class template partial specialization may be declared or redeclared
3916 // in any namespace scope in which its definition may be defined (14.5.1
3917 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003918 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003919 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003920 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003921 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003922 if ((!PrevDecl ||
3923 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3924 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregor121dc9a2010-09-12 05:08:28 +00003925 // C++ [temp.exp.spec]p2:
3926 // An explicit specialization shall be declared in the namespace of which
3927 // the template is a member, or, for member templates, in the namespace
3928 // of which the enclosing class or enclosing class template is a member.
3929 // An explicit specialization of a member function, member class or
3930 // static data member of a class template shall be declared in the
3931 // namespace of which the class template is a member.
3932 //
3933 // C++0x [temp.expl.spec]p2:
3934 // An explicit specialization shall be declared in a namespace enclosing
3935 // the specialized template.
3936 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3937 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregora4d5de52010-09-12 05:24:55 +00003938 bool IsCPlusPlus0xExtension
3939 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003940 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003941 S.Diag(Loc, IsCPlusPlus0xExtension
3942 ? diag::ext_template_spec_decl_out_of_scope_global
3943 : diag::err_template_spec_decl_out_of_scope_global)
3944 << EntityKind << Specialized;
Douglas Gregor9302da62009-10-14 23:50:59 +00003945 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003946 S.Diag(Loc, IsCPlusPlus0xExtension
3947 ? diag::ext_template_spec_decl_out_of_scope
3948 : diag::err_template_spec_decl_out_of_scope)
3949 << EntityKind << Specialized
3950 << cast<NamedDecl>(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003951
3952 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3953 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003954 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003955 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003956
3957 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003958 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003959 // Note that HandleDeclarator() performs this check for explicit
3960 // specializations of function templates, static data members, and member
3961 // functions, so we skip the check here for those kinds of entities.
3962 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003963 // Should we refactor that check, so that it occurs later?
3964 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003965 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3966 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003967 if (isa<TranslationUnitDecl>(SpecializedContext))
3968 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3969 << EntityKind << Specialized;
3970 else if (isa<NamespaceDecl>(SpecializedContext))
3971 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3972 << EntityKind << Specialized
3973 << cast<NamedDecl>(SpecializedContext);
3974
Douglas Gregor9302da62009-10-14 23:50:59 +00003975 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003976 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003977
3978 // FIXME: check for specialization-after-instantiation errors and such.
3979
Douglas Gregor88b70942009-02-25 22:02:03 +00003980 return false;
3981}
Douglas Gregorbacb9492011-01-03 21:13:47 +00003982
3983/// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
3984/// that checks non-type template partial specialization arguments.
3985static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
3986 NonTypeTemplateParmDecl *Param,
3987 const TemplateArgument *Args,
3988 unsigned NumArgs) {
3989 for (unsigned I = 0; I != NumArgs; ++I) {
3990 if (Args[I].getKind() == TemplateArgument::Pack) {
3991 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
3992 Args[I].pack_begin(),
3993 Args[I].pack_size()))
3994 return true;
3995
Douglas Gregore94866f2009-06-12 21:21:02 +00003996 continue;
Douglas Gregorbacb9492011-01-03 21:13:47 +00003997 }
3998
3999 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004000 if (!ArgExpr) {
Douglas Gregore94866f2009-06-12 21:21:02 +00004001 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004002 }
Douglas Gregore94866f2009-06-12 21:21:02 +00004003
Douglas Gregor7a21fd42011-01-03 21:37:45 +00004004 // We can have a pack expansion of any of the bullets below.
Douglas Gregorbacb9492011-01-03 21:13:47 +00004005 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
4006 ArgExpr = Expansion->getPattern();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00004007
4008 // Strip off any implicit casts we added as part of type checking.
4009 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4010 ArgExpr = ICE->getSubExpr();
Douglas Gregorb9c66312010-12-23 17:13:55 +00004011
Douglas Gregore94866f2009-06-12 21:21:02 +00004012 // C++ [temp.class.spec]p8:
4013 // A non-type argument is non-specialized if it is the name of a
4014 // non-type parameter. All other non-type arguments are
4015 // specialized.
4016 //
4017 // Below, we check the two conditions that only apply to
4018 // specialized non-type arguments, so skip any non-specialized
4019 // arguments.
4020 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00004021 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregore94866f2009-06-12 21:21:02 +00004022 continue;
Douglas Gregorb9c66312010-12-23 17:13:55 +00004023
Douglas Gregore94866f2009-06-12 21:21:02 +00004024 // C++ [temp.class.spec]p9:
4025 // Within the argument list of a class template partial
4026 // specialization, the following restrictions apply:
4027 // -- A partially specialized non-type argument expression
4028 // shall not involve a template parameter of the partial
4029 // specialization except when the argument expression is a
4030 // simple identifier.
4031 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004032 S.Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00004033 diag::err_dependent_non_type_arg_in_partial_spec)
4034 << ArgExpr->getSourceRange();
4035 return true;
4036 }
Douglas Gregorbacb9492011-01-03 21:13:47 +00004037
Douglas Gregore94866f2009-06-12 21:21:02 +00004038 // -- The type of a template parameter corresponding to a
4039 // specialized non-type argument shall not be dependent on a
4040 // parameter of the specialization.
4041 if (Param->getType()->isDependentType()) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004042 S.Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00004043 diag::err_dependent_typed_non_type_arg_in_partial_spec)
4044 << Param->getType()
4045 << ArgExpr->getSourceRange();
Douglas Gregorbacb9492011-01-03 21:13:47 +00004046 S.Diag(Param->getLocation(), diag::note_template_param_here);
Douglas Gregore94866f2009-06-12 21:21:02 +00004047 return true;
4048 }
4049 }
Douglas Gregorbacb9492011-01-03 21:13:47 +00004050
4051 return false;
4052}
4053
4054/// \brief Check the non-type template arguments of a class template
4055/// partial specialization according to C++ [temp.class.spec]p9.
4056///
4057/// \param TemplateParams the template parameters of the primary class
4058/// template.
4059///
4060/// \param TemplateArg the template arguments of the class template
4061/// partial specialization.
4062///
4063/// \returns true if there was an error, false otherwise.
4064static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
4065 TemplateParameterList *TemplateParams,
4066 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs) {
4067 const TemplateArgument *ArgList = TemplateArgs.data();
4068
4069 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4070 NonTypeTemplateParmDecl *Param
4071 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
4072 if (!Param)
4073 continue;
4074
4075 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
4076 &ArgList[I], 1))
4077 return true;
4078 }
Douglas Gregore94866f2009-06-12 21:21:02 +00004079
4080 return false;
4081}
4082
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004083/// \brief Retrieve the previous declaration of the given declaration.
4084static NamedDecl *getPreviousDecl(NamedDecl *ND) {
4085 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4086 return VD->getPreviousDeclaration();
4087 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
4088 return FD->getPreviousDeclaration();
4089 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
4090 return TD->getPreviousDeclaration();
4091 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
4092 return TD->getPreviousDeclaration();
4093 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4094 return FTD->getPreviousDeclaration();
4095 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
4096 return CTD->getPreviousDeclaration();
4097 return 0;
4098}
4099
John McCalld226f652010-08-21 09:40:31 +00004100DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00004101Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
4102 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00004103 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004104 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004105 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00004106 SourceLocation TemplateNameLoc,
4107 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00004108 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00004109 SourceLocation RAngleLoc,
4110 AttributeList *Attr,
4111 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004112 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00004113
Douglas Gregorcc636682009-02-17 23:15:12 +00004114 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00004115 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004116 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00004117 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
4118
4119 if (!ClassTemplate) {
4120 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
4121 << (Name.getAsTemplateDecl() &&
4122 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
4123 return true;
4124 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004125
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004126 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004127 bool isPartialSpecialization = false;
4128
Douglas Gregor88b70942009-02-25 22:02:03 +00004129 // Check the validity of the template headers that introduce this
4130 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004131 // FIXME: We probably shouldn't complain about these headers for
4132 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004133 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00004134 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00004135 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
4136 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004137 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00004138 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004139 isExplicitSpecialization,
4140 Invalid);
4141 if (Invalid)
4142 return true;
4143
Abramo Bagnara9b934882010-06-12 08:15:14 +00004144 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
4145 if (TemplateParams)
4146 --NumMatchedTemplateParamLists;
4147
Douglas Gregor05396e22009-08-25 17:23:04 +00004148 if (TemplateParams && TemplateParams->size() > 0) {
4149 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00004150
Douglas Gregorb0ee93c2010-12-21 08:14:57 +00004151 if (TUK == TUK_Friend) {
4152 Diag(KWLoc, diag::err_partial_specialization_friend)
4153 << SourceRange(LAngleLoc, RAngleLoc);
4154 return true;
4155 }
4156
Douglas Gregor05396e22009-08-25 17:23:04 +00004157 // C++ [temp.class.spec]p10:
4158 // The template parameter list of a specialization shall not
4159 // contain default template argument values.
4160 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4161 Decl *Param = TemplateParams->getParam(I);
4162 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4163 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004164 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004165 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00004166 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004167 }
4168 } else if (NonTypeTemplateParmDecl *NTTP
4169 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4170 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004171 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004172 diag::err_default_arg_in_partial_spec)
4173 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004174 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004175 }
4176 } else {
4177 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00004178 if (TTP->hasDefaultArgument()) {
4179 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004180 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00004181 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004182 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004183 }
4184 }
4185 }
Douglas Gregora735b202009-10-13 14:39:41 +00004186 } else if (TemplateParams) {
4187 if (TUK == TUK_Friend)
4188 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00004189 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00004190 SourceRange(TemplateParams->getTemplateLoc(),
4191 TemplateParams->getRAngleLoc()))
4192 << SourceRange(LAngleLoc, RAngleLoc);
4193 else
4194 isExplicitSpecialization = true;
4195 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00004196 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00004197 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004198 isExplicitSpecialization = true;
4199 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004200
Douglas Gregorcc636682009-02-17 23:15:12 +00004201 // Check that the specialization uses the same tag kind as the
4202 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004203 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4204 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004205 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004206 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004207 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004208 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00004209 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004210 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00004211 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004212 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004213 diag::note_previous_use);
4214 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4215 }
4216
Douglas Gregor40808ce2009-03-09 23:48:35 +00004217 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004218 TemplateArgumentListInfo TemplateArgs;
4219 TemplateArgs.setLAngleLoc(LAngleLoc);
4220 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004221 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00004222
Douglas Gregor925910d2011-01-03 20:35:03 +00004223 // Check for unexpanded parameter packs in any of the template arguments.
4224 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4225 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4226 UPPC_PartialSpecialization))
4227 return true;
4228
Douglas Gregorcc636682009-02-17 23:15:12 +00004229 // Check that the template argument list is well-formed for this
4230 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00004231 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00004232 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4233 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004234 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004235
Douglas Gregor910f8002010-11-07 23:05:16 +00004236 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregorcc636682009-02-17 23:15:12 +00004237 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004238
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004239 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00004240 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004241 if (isPartialSpecialization) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004242 if (CheckClassTemplatePartialSpecializationArgs(*this,
Douglas Gregore94866f2009-06-12 21:21:02 +00004243 ClassTemplate->getTemplateParameters(),
Douglas Gregorb9c66312010-12-23 17:13:55 +00004244 Converted))
Douglas Gregore94866f2009-06-12 21:21:02 +00004245 return true;
4246
Douglas Gregorde090962010-02-09 00:37:32 +00004247 if (!Name.isDependent() &&
4248 !TemplateSpecializationType::anyDependentTemplateArguments(
4249 TemplateArgs.getArgumentArray(),
4250 TemplateArgs.size())) {
4251 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4252 << ClassTemplate->getDeclName();
4253 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00004254 }
4255 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004256
Douglas Gregorcc636682009-02-17 23:15:12 +00004257 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004258 ClassTemplateSpecializationDecl *PrevDecl = 0;
4259
4260 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004261 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004262 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004263 = ClassTemplate->findPartialSpecialization(Converted.data(),
4264 Converted.size(),
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004265 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004266 else
4267 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004268 = ClassTemplate->findSpecialization(Converted.data(),
4269 Converted.size(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00004270
4271 ClassTemplateSpecializationDecl *Specialization = 0;
4272
Douglas Gregor88b70942009-02-25 22:02:03 +00004273 // Check whether we can declare a class template specialization in
4274 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004275 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00004276 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00004277 TemplateNameLoc,
4278 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004279 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004280
Douglas Gregorb88e8882009-07-30 17:40:51 +00004281 // The canonical type
4282 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004283 if (PrevDecl &&
4284 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00004285 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004286 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004287 // arguments was referenced but not declared, or we're only
4288 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00004289 // declaration node as our own, updating its source location to
4290 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004291 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004292 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00004293 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00004294 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004295 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00004296 // Build the canonical type that describes the converted template
4297 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00004298 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4299 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb9c66312010-12-23 17:13:55 +00004300 Converted.data(),
4301 Converted.size());
4302
4303 if (Context.hasSameType(CanonType,
4304 ClassTemplate->getInjectedClassNameSpecialization())) {
4305 // C++ [temp.class.spec]p9b3:
4306 //
4307 // -- The argument list of the specialization shall not be identical
4308 // to the implicit argument list of the primary template.
4309 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4310 << (TUK == TUK_Definition)
4311 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4312 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
4313 ClassTemplate->getIdentifier(),
4314 TemplateNameLoc,
4315 Attr,
4316 TemplateParams,
4317 AS_none);
4318 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00004319
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004320 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004321 ClassTemplatePartialSpecializationDecl *PrevPartial
4322 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004323 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004324 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00004325 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00004326 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004327 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00004328 TemplateNameLoc,
4329 TemplateParams,
4330 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004331 Converted.data(),
4332 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00004333 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00004334 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004335 PrevPartial,
4336 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00004337 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004338 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004339 Partial->setTemplateParameterListsInfo(Context,
4340 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004341 (TemplateParameterList**) TemplateParameterLists.release());
4342 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004343
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004344 if (!PrevPartial)
4345 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004346 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00004347
Douglas Gregored9c0f92009-10-29 00:04:11 +00004348 // If we are providing an explicit specialization of a member class
4349 // template specialization, make a note of that.
4350 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4351 PrevPartial->setMemberSpecialization();
4352
Douglas Gregor031a5882009-06-13 00:26:55 +00004353 // Check that all of the template parameters of the class template
4354 // partial specialization are deducible from the template
4355 // arguments. If not, this class template partial specialization
4356 // will never be used.
4357 llvm::SmallVector<bool, 8> DeducibleParams;
4358 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00004359 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004360 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00004361 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00004362 unsigned NumNonDeducible = 0;
4363 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4364 if (!DeducibleParams[I])
4365 ++NumNonDeducible;
4366
4367 if (NumNonDeducible) {
4368 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4369 << (NumNonDeducible > 1)
4370 << SourceRange(TemplateNameLoc, RAngleLoc);
4371 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4372 if (!DeducibleParams[I]) {
4373 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4374 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00004375 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004376 diag::note_partial_spec_unused_parameter)
4377 << Param->getDeclName();
4378 else
Mike Stump1eb44332009-09-09 15:08:12 +00004379 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004380 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00004381 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00004382 }
4383 }
4384 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004385 } else {
4386 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004387 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004388 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004389 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00004390 ClassTemplate->getDeclContext(),
4391 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004392 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004393 Converted.data(),
4394 Converted.size(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004395 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004396 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004397 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004398 Specialization->setTemplateParameterListsInfo(Context,
4399 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004400 (TemplateParameterList**) TemplateParameterLists.release());
4401 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004402
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004403 if (!PrevDecl)
4404 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00004405
4406 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004407 }
4408
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004409 // C++ [temp.expl.spec]p6:
4410 // If a template, a member template or the member of a class template is
4411 // explicitly specialized then that specialization shall be declared
4412 // before the first use of that specialization that would cause an implicit
4413 // instantiation to take place, in every translation unit in which such a
4414 // use occurs; no diagnostic is required.
4415 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004416 bool Okay = false;
4417 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4418 // Is there any previous explicit specialization declaration?
4419 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4420 Okay = true;
4421 break;
4422 }
4423 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004424
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004425 if (!Okay) {
4426 SourceRange Range(TemplateNameLoc, RAngleLoc);
4427 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4428 << Context.getTypeDeclType(Specialization) << Range;
4429
4430 Diag(PrevDecl->getPointOfInstantiation(),
4431 diag::note_instantiation_required_here)
4432 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004433 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004434 return true;
4435 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004436 }
4437
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004438 // If this is not a friend, note that this is an explicit specialization.
4439 if (TUK != TUK_Friend)
4440 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004441
4442 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004443 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00004444 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004445 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004446 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004447 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00004448 Diag(Def->getLocation(), diag::note_previous_definition);
4449 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00004450 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004451 }
4452 }
4453
John McCall7f1b9872010-12-18 03:30:47 +00004454 if (Attr)
4455 ProcessDeclAttributeList(S, Specialization, Attr);
4456
Douglas Gregorfc705b82009-02-26 22:19:44 +00004457 // Build the fully-sugared type for this class template
4458 // specialization as the user wrote in the specialization
4459 // itself. This means that we'll pretty-print the type retrieved
4460 // from the specialization's declaration the way that the user
4461 // actually wrote the specialization, rather than formatting the
4462 // name based on the "canonical" representation used to store the
4463 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004464 TypeSourceInfo *WrittenTy
4465 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4466 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004467 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004468 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor7e9b57b2010-07-06 18:33:12 +00004469 if (TemplateParams)
4470 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004471 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00004472 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00004473
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004474 // C++ [temp.expl.spec]p9:
4475 // A template explicit specialization is in the scope of the
4476 // namespace in which the template was defined.
4477 //
4478 // We actually implement this paragraph where we set the semantic
4479 // context (in the creation of the ClassTemplateSpecializationDecl),
4480 // but we also maintain the lexical context where the actual
4481 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00004482 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004483
Douglas Gregorcc636682009-02-17 23:15:12 +00004484 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004485 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00004486 Specialization->startDefinition();
4487
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004488 if (TUK == TUK_Friend) {
4489 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4490 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00004491 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004492 /*FIXME:*/KWLoc);
4493 Friend->setAccess(AS_public);
4494 CurContext->addDecl(Friend);
4495 } else {
4496 // Add the specialization into its lexical context, so that it can
4497 // be seen when iterating through the list of declarations in that
4498 // context. However, specializations are not found by name lookup.
4499 CurContext->addDecl(Specialization);
4500 }
John McCalld226f652010-08-21 09:40:31 +00004501 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00004502}
Douglas Gregord57959a2009-03-27 23:10:48 +00004503
John McCalld226f652010-08-21 09:40:31 +00004504Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00004505 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004506 Declarator &D) {
Douglas Gregore542c862009-06-23 23:11:28 +00004507 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4508}
4509
John McCalld226f652010-08-21 09:40:31 +00004510Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004511 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004512 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00004513 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004514 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00004515
Douglas Gregor52591bf2009-06-24 00:54:41 +00004516 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004517 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00004518 }
Mike Stump1eb44332009-09-09 15:08:12 +00004519
Douglas Gregor52591bf2009-06-24 00:54:41 +00004520 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004521
John McCalld226f652010-08-21 09:40:31 +00004522 Decl *DP = HandleDeclarator(ParentScope, D,
4523 move(TemplateParameterLists),
4524 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004525 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00004526 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00004527 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00004528 FunctionTemplate->getTemplatedDecl());
4529 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4530 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4531 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00004532}
4533
John McCall75042392010-02-11 01:33:53 +00004534/// \brief Strips various properties off an implicit instantiation
4535/// that has just been explicitly specialized.
4536static void StripImplicitInstantiation(NamedDecl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00004537 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00004538
4539 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4540 FD->setInlineSpecified(false);
4541 }
4542}
4543
Douglas Gregor454885e2009-10-15 15:54:05 +00004544/// \brief Diagnose cases where we have an explicit template specialization
4545/// before/after an explicit template instantiation, producing diagnostics
4546/// for those cases where they are required and determining whether the
4547/// new specialization/instantiation will have any effect.
4548///
Douglas Gregor454885e2009-10-15 15:54:05 +00004549/// \param NewLoc the location of the new explicit specialization or
4550/// instantiation.
4551///
4552/// \param NewTSK the kind of the new explicit specialization or instantiation.
4553///
4554/// \param PrevDecl the previous declaration of the entity.
4555///
4556/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4557///
4558/// \param PrevPointOfInstantiation if valid, indicates where the previus
4559/// declaration was instantiated (either implicitly or explicitly).
4560///
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004561/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00004562/// specialization or instantiation has no effect and should be ignored.
4563///
4564/// \returns true if there was an error that should prevent the introduction of
4565/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004566bool
4567Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4568 TemplateSpecializationKind NewTSK,
4569 NamedDecl *PrevDecl,
4570 TemplateSpecializationKind PrevTSK,
4571 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004572 bool &HasNoEffect) {
4573 HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004574
4575 switch (NewTSK) {
4576 case TSK_Undeclared:
4577 case TSK_ImplicitInstantiation:
4578 assert(false && "Don't check implicit instantiations here");
4579 return false;
4580
4581 case TSK_ExplicitSpecialization:
4582 switch (PrevTSK) {
4583 case TSK_Undeclared:
4584 case TSK_ExplicitSpecialization:
4585 // Okay, we're just specializing something that is either already
4586 // explicitly specialized or has merely been mentioned without any
4587 // instantiation.
4588 return false;
4589
4590 case TSK_ImplicitInstantiation:
4591 if (PrevPointOfInstantiation.isInvalid()) {
4592 // The declaration itself has not actually been instantiated, so it is
4593 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004594 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004595 return false;
4596 }
4597 // Fall through
4598
4599 case TSK_ExplicitInstantiationDeclaration:
4600 case TSK_ExplicitInstantiationDefinition:
4601 assert((PrevTSK == TSK_ImplicitInstantiation ||
4602 PrevPointOfInstantiation.isValid()) &&
4603 "Explicit instantiation without point of instantiation?");
4604
4605 // C++ [temp.expl.spec]p6:
4606 // If a template, a member template or the member of a class template
4607 // is explicitly specialized then that specialization shall be declared
4608 // before the first use of that specialization that would cause an
4609 // implicit instantiation to take place, in every translation unit in
4610 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004611 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4612 // Is there any previous explicit specialization declaration?
4613 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4614 return false;
4615 }
4616
Douglas Gregor0d035142009-10-27 18:42:08 +00004617 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004618 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004619 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004620 << (PrevTSK != TSK_ImplicitInstantiation);
4621
4622 return true;
4623 }
4624 break;
4625
4626 case TSK_ExplicitInstantiationDeclaration:
4627 switch (PrevTSK) {
4628 case TSK_ExplicitInstantiationDeclaration:
4629 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004630 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004631 return false;
4632
4633 case TSK_Undeclared:
4634 case TSK_ImplicitInstantiation:
4635 // We're explicitly instantiating something that may have already been
4636 // implicitly instantiated; that's fine.
4637 return false;
4638
4639 case TSK_ExplicitSpecialization:
4640 // C++0x [temp.explicit]p4:
4641 // For a given set of template parameters, if an explicit instantiation
4642 // of a template appears after a declaration of an explicit
4643 // specialization for that template, the explicit instantiation has no
4644 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004645 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004646 return false;
4647
4648 case TSK_ExplicitInstantiationDefinition:
4649 // C++0x [temp.explicit]p10:
4650 // If an entity is the subject of both an explicit instantiation
4651 // declaration and an explicit instantiation definition in the same
4652 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004653 Diag(NewLoc,
4654 diag::err_explicit_instantiation_declaration_after_definition);
4655 Diag(PrevPointOfInstantiation,
4656 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004657 assert(PrevPointOfInstantiation.isValid() &&
4658 "Explicit instantiation without point of instantiation?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004659 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004660 return false;
4661 }
4662 break;
4663
4664 case TSK_ExplicitInstantiationDefinition:
4665 switch (PrevTSK) {
4666 case TSK_Undeclared:
4667 case TSK_ImplicitInstantiation:
4668 // We're explicitly instantiating something that may have already been
4669 // implicitly instantiated; that's fine.
4670 return false;
4671
4672 case TSK_ExplicitSpecialization:
4673 // C++ DR 259, C++0x [temp.explicit]p4:
4674 // For a given set of template parameters, if an explicit
4675 // instantiation of a template appears after a declaration of
4676 // an explicit specialization for that template, the explicit
4677 // instantiation has no effect.
4678 //
4679 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004680 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004681 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004682 if (!getLangOptions().CPlusPlus0x) {
4683 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004684 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004685 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004686 diag::note_previous_template_specialization);
4687 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004688 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004689 return false;
4690
4691 case TSK_ExplicitInstantiationDeclaration:
4692 // We're explicity instantiating a definition for something for which we
4693 // were previously asked to suppress instantiations. That's fine.
4694 return false;
4695
4696 case TSK_ExplicitInstantiationDefinition:
4697 // C++0x [temp.spec]p5:
4698 // For a given template and a given set of template-arguments,
4699 // - an explicit instantiation definition shall appear at most once
4700 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004701 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004702 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004703 Diag(PrevPointOfInstantiation,
4704 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004705 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004706 return false;
4707 }
4708 break;
4709 }
4710
4711 assert(false && "Missing specialization/instantiation case?");
4712
4713 return false;
4714}
4715
John McCallaf2094e2010-04-08 09:05:18 +00004716/// \brief Perform semantic analysis for the given dependent function
4717/// template specialization. The only possible way to get a dependent
4718/// function template specialization is with a friend declaration,
4719/// like so:
4720///
4721/// template <class T> void foo(T);
4722/// template <class T> class A {
4723/// friend void foo<>(T);
4724/// };
4725///
4726/// There really isn't any useful analysis we can do here, so we
4727/// just store the information.
4728bool
4729Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4730 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4731 LookupResult &Previous) {
4732 // Remove anything from Previous that isn't a function template in
4733 // the correct context.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004734 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallaf2094e2010-04-08 09:05:18 +00004735 LookupResult::Filter F = Previous.makeFilter();
4736 while (F.hasNext()) {
4737 NamedDecl *D = F.next()->getUnderlyingDecl();
4738 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl7a126a42010-08-31 00:36:30 +00004739 !FDLookupContext->InEnclosingNamespaceSetOf(
4740 D->getDeclContext()->getRedeclContext()))
John McCallaf2094e2010-04-08 09:05:18 +00004741 F.erase();
4742 }
4743 F.done();
4744
4745 // Should this be diagnosed here?
4746 if (Previous.empty()) return true;
4747
4748 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4749 ExplicitTemplateArgs);
4750 return false;
4751}
4752
Abramo Bagnarae03db982010-05-20 15:32:11 +00004753/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004754/// specialization.
4755///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004756/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004757/// explicit function template specialization. On successful completion,
4758/// the function declaration \p FD will become a function template
4759/// specialization.
4760///
4761/// \param FD the function declaration, which will be updated to become a
4762/// function template specialization.
4763///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004764/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4765/// if any. Note that this may be valid info even when 0 arguments are
4766/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4767/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004768///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004769/// \param PrevDecl the set of declarations that may be specialized by
4770/// this function specialization.
4771bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004772Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004773 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004774 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004775 // The set of function template specializations that could match this
4776 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004777 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004778
Sebastian Redl7a126a42010-08-31 00:36:30 +00004779 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall68263142009-11-18 22:49:29 +00004780 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4781 I != E; ++I) {
4782 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4783 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004784 // Only consider templates found within the same semantic lookup scope as
4785 // FD.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004786 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4787 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004788 continue;
4789
4790 // C++ [temp.expl.spec]p11:
4791 // A trailing template-argument can be left unspecified in the
4792 // template-id naming an explicit function template specialization
4793 // provided it can be deduced from the function argument type.
4794 // Perform template argument deduction to determine whether we may be
4795 // specializing this template.
4796 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004797 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004798 FunctionDecl *Specialization = 0;
4799 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004800 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004801 FD->getType(),
4802 Specialization,
4803 Info)) {
4804 // FIXME: Template argument deduction failed; record why it failed, so
4805 // that we can provide nifty diagnostics.
4806 (void)TDK;
4807 continue;
4808 }
4809
4810 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004811 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004812 }
4813 }
4814
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004815 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004816 UnresolvedSetIterator Result
4817 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4818 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004819 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004820 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004821 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004822 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004823 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004824 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004825 return true;
John McCallc373d482010-01-27 01:50:18 +00004826
4827 // Ignore access information; it doesn't figure into redeclaration checking.
4828 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004829 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004830
4831 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004832 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004833
4834 // If this is a friend declaration, then we're not really declaring
4835 // an explicit specialization.
4836 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004837
Douglas Gregord5cb8762009-10-07 00:13:32 +00004838 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004839 if (!isFriend &&
4840 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004841 Specialization->getPrimaryTemplate(),
4842 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004843 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004844 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004845
4846 // C++ [temp.expl.spec]p6:
4847 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004848 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004849 // before the first use of that specialization that would cause an implicit
4850 // instantiation to take place, in every translation unit in which such a
4851 // use occurs; no diagnostic is required.
4852 FunctionTemplateSpecializationInfo *SpecInfo
4853 = Specialization->getTemplateSpecializationInfo();
4854 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004855
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004856 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00004857 if (!isFriend &&
4858 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004859 TSK_ExplicitSpecialization,
4860 Specialization,
4861 SpecInfo->getTemplateSpecializationKind(),
4862 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004863 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004864 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004865
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004866 // Mark the prior declaration as an explicit specialization, so that later
4867 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004868 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00004869 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004870 MarkUnusedFileScopedDecl(Specialization);
4871 }
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004872
4873 // Turn the given function declaration into a function template
4874 // specialization, with the template arguments from the previous
4875 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004876 // Take copies of (semantic and syntactic) template argument lists.
4877 const TemplateArgumentList* TemplArgs = new (Context)
4878 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4879 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4880 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004881 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004882 TemplArgs, /*InsertPos=*/0,
4883 SpecInfo->getTemplateSpecializationKind(),
4884 TemplArgsAsWritten);
4885
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004886 // The "previous declaration" for this function template specialization is
4887 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004888 Previous.clear();
4889 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004890 return false;
4891}
4892
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004893/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004894/// specialization.
4895///
4896/// This routine performs all of the semantic analysis required for an
4897/// explicit member function specialization. On successful completion,
4898/// the function declaration \p FD will become a member function
4899/// specialization.
4900///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004901/// \param Member the member declaration, which will be updated to become a
4902/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004903///
John McCall68263142009-11-18 22:49:29 +00004904/// \param Previous the set of declarations, one of which may be specialized
4905/// by this function specialization; the set will be modified to contain the
4906/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004907bool
John McCall68263142009-11-18 22:49:29 +00004908Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004909 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004910
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004911 // Try to find the member we are instantiating.
4912 NamedDecl *Instantiation = 0;
4913 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004914 MemberSpecializationInfo *MSInfo = 0;
4915
John McCall68263142009-11-18 22:49:29 +00004916 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004917 // Nowhere to look anyway.
4918 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004919 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4920 I != E; ++I) {
4921 NamedDecl *D = (*I)->getUnderlyingDecl();
4922 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004923 if (Context.hasSameType(Function->getType(), Method->getType())) {
4924 Instantiation = Method;
4925 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004926 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004927 break;
4928 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004929 }
4930 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004931 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004932 VarDecl *PrevVar;
4933 if (Previous.isSingleResult() &&
4934 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004935 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004936 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004937 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004938 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004939 }
4940 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004941 CXXRecordDecl *PrevRecord;
4942 if (Previous.isSingleResult() &&
4943 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4944 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004945 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004946 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004947 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004948 }
4949
4950 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004951 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004952 // specializations are always out-of-line, the caller will complain about
4953 // this mismatch later.
4954 return false;
4955 }
John McCall77e8b112010-04-13 20:37:33 +00004956
4957 // If this is a friend, just bail out here before we start turning
4958 // things into explicit specializations.
4959 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4960 // Preserve instantiation information.
4961 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4962 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4963 cast<CXXMethodDecl>(InstantiatedFrom),
4964 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4965 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4966 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4967 cast<CXXRecordDecl>(InstantiatedFrom),
4968 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4969 }
4970
4971 Previous.clear();
4972 Previous.addDecl(Instantiation);
4973 return false;
4974 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004975
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004976 // Make sure that this is a specialization of a member.
4977 if (!InstantiatedFrom) {
4978 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4979 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004980 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4981 return true;
4982 }
4983
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004984 // C++ [temp.expl.spec]p6:
4985 // If a template, a member template or the member of a class template is
4986 // explicitly specialized then that spe- cialization shall be declared
4987 // before the first use of that specialization that would cause an implicit
4988 // instantiation to take place, in every translation unit in which such a
4989 // use occurs; no diagnostic is required.
4990 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004991
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004992 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00004993 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4994 TSK_ExplicitSpecialization,
4995 Instantiation,
4996 MSInfo->getTemplateSpecializationKind(),
4997 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004998 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004999 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005000
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005001 // Check the scope of this explicit specialization.
5002 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005003 InstantiatedFrom,
5004 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00005005 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005006 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00005007
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005008 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00005009 // the original declaration to note that it is an explicit specialization
5010 // (if it was previously an implicit instantiation). This latter step
5011 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005012 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005013 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
5014 if (InstantiationFunction->getTemplateSpecializationKind() ==
5015 TSK_ImplicitInstantiation) {
5016 InstantiationFunction->setTemplateSpecializationKind(
5017 TSK_ExplicitSpecialization);
5018 InstantiationFunction->setLocation(Member->getLocation());
5019 }
5020
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005021 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
5022 cast<CXXMethodDecl>(InstantiatedFrom),
5023 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005024 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005025 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005026 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
5027 if (InstantiationVar->getTemplateSpecializationKind() ==
5028 TSK_ImplicitInstantiation) {
5029 InstantiationVar->setTemplateSpecializationKind(
5030 TSK_ExplicitSpecialization);
5031 InstantiationVar->setLocation(Member->getLocation());
5032 }
5033
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005034 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
5035 cast<VarDecl>(InstantiatedFrom),
5036 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005037 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005038 } else {
5039 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00005040 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
5041 if (InstantiationClass->getTemplateSpecializationKind() ==
5042 TSK_ImplicitInstantiation) {
5043 InstantiationClass->setTemplateSpecializationKind(
5044 TSK_ExplicitSpecialization);
5045 InstantiationClass->setLocation(Member->getLocation());
5046 }
5047
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005048 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00005049 cast<CXXRecordDecl>(InstantiatedFrom),
5050 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005051 }
5052
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005053 // Save the caller the trouble of having to figure out which declaration
5054 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00005055 Previous.clear();
5056 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005057 return false;
5058}
5059
Douglas Gregor558c0322009-10-14 23:41:34 +00005060/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00005061///
5062/// \returns true if a serious error occurs, false otherwise.
5063static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00005064 SourceLocation InstLoc,
5065 bool WasQualifiedName) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005066 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
5067 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregor558c0322009-10-14 23:41:34 +00005068
Douglas Gregor669eed82010-07-13 00:10:04 +00005069 if (CurContext->isRecord()) {
5070 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
5071 << D;
5072 return true;
5073 }
5074
Douglas Gregor558c0322009-10-14 23:41:34 +00005075 // C++0x [temp.explicit]p2:
5076 // An explicit instantiation shall appear in an enclosing namespace of its
5077 // template.
5078 //
5079 // This is DR275, which we do not retroactively apply to C++98/03.
5080 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005081 !CurContext->Encloses(OrigContext)) {
5082 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00005083 S.Diag(InstLoc,
5084 S.getLangOptions().CPlusPlus0x?
5085 diag::err_explicit_instantiation_out_of_scope
5086 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00005087 << D << NS;
5088 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00005089 S.Diag(InstLoc,
5090 S.getLangOptions().CPlusPlus0x?
5091 diag::err_explicit_instantiation_must_be_global
5092 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00005093 << D;
5094 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00005095 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00005096 }
Sebastian Redl7a126a42010-08-31 00:36:30 +00005097
Douglas Gregor558c0322009-10-14 23:41:34 +00005098 // C++0x [temp.explicit]p2:
5099 // If the name declared in the explicit instantiation is an unqualified
5100 // name, the explicit instantiation shall appear in the namespace where
5101 // its template is declared or, if that namespace is inline (7.3.1), any
5102 // namespace from its enclosing namespace set.
5103 if (WasQualifiedName)
Douglas Gregor669eed82010-07-13 00:10:04 +00005104 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005105
5106 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor669eed82010-07-13 00:10:04 +00005107 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005108
Douglas Gregor2166beb2010-05-11 17:39:34 +00005109 S.Diag(InstLoc,
5110 S.getLangOptions().CPlusPlus0x?
5111 diag::err_explicit_instantiation_unqualified_wrong_namespace
5112 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl7a126a42010-08-31 00:36:30 +00005113 << D << OrigContext;
Douglas Gregor558c0322009-10-14 23:41:34 +00005114 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00005115 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00005116}
5117
5118/// \brief Determine whether the given scope specifier has a template-id in it.
5119static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
5120 if (!SS.isSet())
5121 return false;
5122
5123 // C++0x [temp.explicit]p2:
5124 // If the explicit instantiation is for a member function, a member class
5125 // or a static data member of a class template specialization, the name of
5126 // the class template specialization in the qualified-id for the member
5127 // name shall be a simple-template-id.
5128 //
5129 // C++98 has the same restriction, just worded differently.
5130 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
5131 NNS; NNS = NNS->getPrefix())
5132 if (Type *T = NNS->getAsType())
5133 if (isa<TemplateSpecializationType>(T))
5134 return true;
5135
5136 return false;
5137}
5138
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005139// Explicit instantiation of a class template specialization
John McCallf312b1e2010-08-26 23:41:50 +00005140DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005141Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005142 SourceLocation ExternLoc,
5143 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005144 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005145 SourceLocation KWLoc,
5146 const CXXScopeSpec &SS,
5147 TemplateTy TemplateD,
5148 SourceLocation TemplateNameLoc,
5149 SourceLocation LAngleLoc,
5150 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005151 SourceLocation RAngleLoc,
5152 AttributeList *Attr) {
5153 // Find the class template we're specializing
5154 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00005155 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005156 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
5157
5158 // Check that the specialization uses the same tag kind as the
5159 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005160 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5161 assert(Kind != TTK_Enum &&
5162 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005163 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00005164 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005165 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005166 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005167 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00005168 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005169 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00005170 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005171 diag::note_previous_use);
5172 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5173 }
5174
Douglas Gregor558c0322009-10-14 23:41:34 +00005175 // C++0x [temp.explicit]p2:
5176 // There are two forms of explicit instantiation: an explicit instantiation
5177 // definition and an explicit instantiation declaration. An explicit
5178 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00005179 TemplateSpecializationKind TSK
5180 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5181 : TSK_ExplicitInstantiationDeclaration;
5182
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005183 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00005184 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00005185 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005186
5187 // Check that the template argument list is well-formed for this
5188 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00005189 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00005190 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5191 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005192 return true;
5193
Douglas Gregor910f8002010-11-07 23:05:16 +00005194 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005195 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00005196
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005197 // Find the class template specialization declaration that
5198 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005199 void *InsertPos = 0;
5200 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00005201 = ClassTemplate->findSpecialization(Converted.data(),
5202 Converted.size(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005203
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005204 TemplateSpecializationKind PrevDecl_TSK
5205 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5206
Douglas Gregord5cb8762009-10-07 00:13:32 +00005207 // C++0x [temp.explicit]p2:
5208 // [...] An explicit instantiation shall appear in an enclosing
5209 // namespace of its template. [...]
5210 //
5211 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00005212 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5213 SS.isSet()))
5214 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00005215
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005216 ClassTemplateSpecializationDecl *Specialization = 0;
5217
Douglas Gregord78f5982009-11-25 06:01:46 +00005218 bool ReusedDecl = false;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005219 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005220 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00005221 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005222 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005223 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005224 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00005225 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005226
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005227 // Even though HasNoEffect == true means that this explicit instantiation
5228 // has no effect on semantics, we go on to put its syntax in the AST.
5229
5230 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5231 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00005232 // Since the only prior class template specialization with these
5233 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005234 // declaration node as our own, updating the source location
5235 // for the template name to reflect our new declaration.
5236 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00005237 Specialization = PrevDecl;
5238 Specialization->setLocation(TemplateNameLoc);
5239 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00005240 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00005241 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005242 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005243
Douglas Gregor52604ab2009-09-11 21:19:12 +00005244 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005245 // Create a new class template specialization declaration node for
5246 // this explicit specialization.
5247 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00005248 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005249 ClassTemplate->getDeclContext(),
5250 TemplateNameLoc,
5251 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005252 Converted.data(),
5253 Converted.size(),
5254 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00005255 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005256
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005257 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005258 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005259 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005260 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005261 }
5262
5263 // Build the fully-sugared type for this explicit instantiation as
5264 // the user wrote in the explicit instantiation itself. This means
5265 // that we'll pretty-print the type retrieved from the
5266 // specialization's declaration the way that the user actually wrote
5267 // the explicit instantiation, rather than formatting the name based
5268 // on the "canonical" representation used to store the template
5269 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00005270 TypeSourceInfo *WrittenTy
5271 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5272 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005273 Context.getTypeDeclType(Specialization));
5274 Specialization->setTypeAsWritten(WrittenTy);
5275 TemplateArgsIn.release();
5276
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005277 // Set source locations for keywords.
5278 Specialization->setExternLoc(ExternLoc);
5279 Specialization->setTemplateKeywordLoc(TemplateLoc);
5280
5281 // Add the explicit instantiation into its lexical context. However,
5282 // since explicit instantiations are never found by name lookup, we
5283 // just put it into the declaration context directly.
5284 Specialization->setLexicalDeclContext(CurContext);
5285 CurContext->addDecl(Specialization);
5286
5287 // Syntax is now OK, so return if it has no other effect on semantics.
5288 if (HasNoEffect) {
5289 // Set the template specialization kind.
5290 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005291 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00005292 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005293
5294 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005295 // A definition of a class template or class member template
5296 // shall be in scope at the point of the explicit instantiation of
5297 // the class template or class member template.
5298 //
5299 // This check comes when we actually try to perform the
5300 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005301 ClassTemplateSpecializationDecl *Def
5302 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005303 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005304 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005305 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005306 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005307 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005308 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5309 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005310
Douglas Gregor0d035142009-10-27 18:42:08 +00005311 // Instantiate the members of this class template specialization.
5312 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005313 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005314 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00005315 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5316
5317 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5318 // TSK_ExplicitInstantiationDefinition
5319 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5320 TSK == TSK_ExplicitInstantiationDefinition)
5321 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005322
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005323 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005324 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005325
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005326 // Set the template specialization kind.
5327 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005328 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005329}
5330
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005331// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00005332DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005333Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005334 SourceLocation ExternLoc,
5335 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005336 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005337 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005338 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005339 IdentifierInfo *Name,
5340 SourceLocation NameLoc,
5341 AttributeList *Attr) {
5342
Douglas Gregor402abb52009-05-28 23:31:59 +00005343 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00005344 bool IsDependent = false;
John McCallf312b1e2010-08-26 23:41:50 +00005345 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCalld226f652010-08-21 09:40:31 +00005346 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5347 MultiTemplateParamsArg(*this, 0, 0),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00005348 Owned, IsDependent, false, false,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005349 TypeResult());
John McCallc4e70192009-09-11 04:59:25 +00005350 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5351
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005352 if (!TagD)
5353 return true;
5354
John McCalld226f652010-08-21 09:40:31 +00005355 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005356 if (Tag->isEnum()) {
5357 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5358 << Context.getTypeDeclType(Tag);
5359 return true;
5360 }
5361
Douglas Gregord0c87372009-05-27 17:30:49 +00005362 if (Tag->isInvalidDecl())
5363 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00005364
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005365 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5366 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5367 if (!Pattern) {
5368 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5369 << Context.getTypeDeclType(Record);
5370 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5371 return true;
5372 }
5373
Douglas Gregor558c0322009-10-14 23:41:34 +00005374 // C++0x [temp.explicit]p2:
5375 // If the explicit instantiation is for a class or member class, the
5376 // elaborated-type-specifier in the declaration shall include a
5377 // simple-template-id.
5378 //
5379 // C++98 has the same restriction, just worded differently.
5380 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00005381 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005382 << Record << SS.getRange();
5383
5384 // C++0x [temp.explicit]p2:
5385 // There are two forms of explicit instantiation: an explicit instantiation
5386 // definition and an explicit instantiation declaration. An explicit
5387 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00005388 TemplateSpecializationKind TSK
5389 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5390 : TSK_ExplicitInstantiationDeclaration;
5391
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005392 // C++0x [temp.explicit]p2:
5393 // [...] An explicit instantiation shall appear in an enclosing
5394 // namespace of its template. [...]
5395 //
5396 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00005397 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00005398
5399 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00005400 CXXRecordDecl *PrevDecl
5401 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00005402 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00005403 PrevDecl = Record;
5404 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00005405 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005406 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00005407 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00005408 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00005409 PrevDecl,
5410 MSInfo->getTemplateSpecializationKind(),
5411 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005412 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005413 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005414 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00005415 return TagD;
5416 }
5417
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005418 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00005419 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005420 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005421 // C++ [temp.explicit]p3:
5422 // A definition of a member class of a class template shall be in scope
5423 // at the point of an explicit instantiation of the member class.
5424 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00005425 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005426 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00005427 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5428 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005429 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5430 << Pattern;
5431 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00005432 } else {
5433 if (InstantiateClass(NameLoc, Record, Def,
5434 getTemplateInstantiationArgs(Record),
5435 TSK))
5436 return true;
5437
Douglas Gregor952b0172010-02-11 01:04:33 +00005438 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00005439 if (!RecordDef)
5440 return true;
5441 }
5442 }
5443
5444 // Instantiate all of the members of the class.
5445 InstantiateClassMembers(NameLoc, RecordDef,
5446 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005447
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005448 if (TSK == TSK_ExplicitInstantiationDefinition)
5449 MarkVTableUsed(NameLoc, RecordDef, true);
5450
Mike Stump390b4cc2009-05-16 07:39:55 +00005451 // FIXME: We don't have any representation for explicit instantiations of
5452 // member classes. Such a representation is not needed for compilation, but it
5453 // should be available for clients that want to see all of the declarations in
5454 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005455 return TagD;
5456}
5457
John McCallf312b1e2010-08-26 23:41:50 +00005458DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5459 SourceLocation ExternLoc,
5460 SourceLocation TemplateLoc,
5461 Declarator &D) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005462 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00005463 // TODO: check if/when DNInfo should replace Name.
5464 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5465 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005466 if (!Name) {
5467 if (!D.isInvalidType())
5468 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5469 diag::err_explicit_instantiation_requires_name)
5470 << D.getDeclSpec().getSourceRange()
5471 << D.getSourceRange();
5472
5473 return true;
5474 }
5475
5476 // The scope passed in may not be a decl scope. Zip up the scope tree until
5477 // we find one that is.
5478 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5479 (S->getFlags() & Scope::TemplateParamScope) != 0)
5480 S = S->getParent();
5481
5482 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00005483 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5484 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005485 if (R.isNull())
5486 return true;
5487
5488 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5489 // Cannot explicitly instantiate a typedef.
5490 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5491 << Name;
5492 return true;
5493 }
5494
Douglas Gregor663b5a02009-10-14 20:14:33 +00005495 // C++0x [temp.explicit]p1:
5496 // [...] An explicit instantiation of a function template shall not use the
5497 // inline or constexpr specifiers.
5498 // Presumably, this also applies to member functions of class templates as
5499 // well.
5500 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5501 Diag(D.getDeclSpec().getInlineSpecLoc(),
5502 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00005503 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00005504
5505 // FIXME: check for constexpr specifier.
5506
Douglas Gregor558c0322009-10-14 23:41:34 +00005507 // C++0x [temp.explicit]p2:
5508 // There are two forms of explicit instantiation: an explicit instantiation
5509 // definition and an explicit instantiation declaration. An explicit
5510 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00005511 TemplateSpecializationKind TSK
5512 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5513 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00005514
Abramo Bagnara25777432010-08-11 22:01:17 +00005515 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005516 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005517
5518 if (!R->isFunctionType()) {
5519 // C++ [temp.explicit]p1:
5520 // A [...] static data member of a class template can be explicitly
5521 // instantiated from the member definition associated with its class
5522 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00005523 if (Previous.isAmbiguous())
5524 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005525
John McCall1bcee0a2009-12-02 08:25:40 +00005526 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005527 if (!Prev || !Prev->isStaticDataMember()) {
5528 // We expect to see a data data member here.
5529 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5530 << Name;
5531 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5532 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00005533 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005534 return true;
5535 }
5536
5537 if (!Prev->getInstantiatedFromStaticDataMember()) {
5538 // FIXME: Check for explicit specialization?
5539 Diag(D.getIdentifierLoc(),
5540 diag::err_explicit_instantiation_data_member_not_instantiated)
5541 << Prev;
5542 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5543 // FIXME: Can we provide a note showing where this was declared?
5544 return true;
5545 }
5546
Douglas Gregor558c0322009-10-14 23:41:34 +00005547 // C++0x [temp.explicit]p2:
5548 // If the explicit instantiation is for a member function, a member class
5549 // or a static data member of a class template specialization, the name of
5550 // the class template specialization in the qualified-id for the member
5551 // name shall be a simple-template-id.
5552 //
5553 // C++98 has the same restriction, just worded differently.
5554 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5555 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005556 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005557 << Prev << D.getCXXScopeSpec().getRange();
5558
5559 // Check the scope of this explicit instantiation.
5560 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5561
Douglas Gregor454885e2009-10-15 15:54:05 +00005562 // Verify that it is okay to explicitly instantiate here.
5563 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5564 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005565 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005566 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005567 MSInfo->getTemplateSpecializationKind(),
5568 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005569 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005570 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005571 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005572 return (Decl*) 0;
Douglas Gregor454885e2009-10-15 15:54:05 +00005573
Douglas Gregord5a423b2009-09-25 18:43:00 +00005574 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005575 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005576 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005577 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005578
5579 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00005580 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005581 }
5582
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005583 // If the declarator is a template-id, translate the parser's template
5584 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005585 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005586 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005587 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5588 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005589 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5590 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005591 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5592 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005593 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005594 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005595 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005596 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005597 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005598
Douglas Gregord5a423b2009-09-25 18:43:00 +00005599 // C++ [temp.explicit]p1:
5600 // A [...] function [...] can be explicitly instantiated from its template.
5601 // A member function [...] of a class template can be explicitly
5602 // instantiated from the member definition associated with its class
5603 // template.
John McCallc373d482010-01-27 01:50:18 +00005604 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005605 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5606 P != PEnd; ++P) {
5607 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005608 if (!HasExplicitTemplateArgs) {
5609 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5610 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5611 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005612
John McCallc373d482010-01-27 01:50:18 +00005613 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005614 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5615 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005616 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005617 }
5618 }
5619
5620 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5621 if (!FunTmpl)
5622 continue;
5623
John McCall5769d612010-02-08 23:07:23 +00005624 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005625 FunctionDecl *Specialization = 0;
5626 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005627 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005628 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005629 R, Specialization, Info)) {
5630 // FIXME: Keep track of almost-matches?
5631 (void)TDK;
5632 continue;
5633 }
5634
John McCallc373d482010-01-27 01:50:18 +00005635 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005636 }
5637
5638 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005639 UnresolvedSetIterator Result
5640 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005641 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005642 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5643 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5644 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005645
John McCallc373d482010-01-27 01:50:18 +00005646 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005647 return true;
John McCallc373d482010-01-27 01:50:18 +00005648
5649 // Ignore access control bits, we don't need them for redeclaration checking.
5650 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005651
Douglas Gregor0a897e32009-10-15 17:21:20 +00005652 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005653 Diag(D.getIdentifierLoc(),
5654 diag::err_explicit_instantiation_member_function_not_instantiated)
5655 << Specialization
5656 << (Specialization->getTemplateSpecializationKind() ==
5657 TSK_ExplicitSpecialization);
5658 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5659 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005660 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005661
Douglas Gregor0a897e32009-10-15 17:21:20 +00005662 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005663 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5664 PrevDecl = Specialization;
5665
Douglas Gregor0a897e32009-10-15 17:21:20 +00005666 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005667 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005668 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005669 PrevDecl,
5670 PrevDecl->getTemplateSpecializationKind(),
5671 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005672 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00005673 return true;
5674
5675 // FIXME: We may still want to build some representation of this
5676 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005677 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005678 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005679 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005680
5681 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005682
5683 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005684 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005685
Douglas Gregor558c0322009-10-14 23:41:34 +00005686 // C++0x [temp.explicit]p2:
5687 // If the explicit instantiation is for a member function, a member class
5688 // or a static data member of a class template specialization, the name of
5689 // the class template specialization in the qualified-id for the member
5690 // name shall be a simple-template-id.
5691 //
5692 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005693 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005694 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005695 D.getCXXScopeSpec().isSet() &&
5696 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5697 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005698 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005699 << Specialization << D.getCXXScopeSpec().getRange();
5700
5701 CheckExplicitInstantiationScope(*this,
5702 FunTmpl? (NamedDecl *)FunTmpl
5703 : Specialization->getInstantiatedFromMemberFunction(),
5704 D.getIdentifierLoc(),
5705 D.getCXXScopeSpec().isSet());
5706
Douglas Gregord5a423b2009-09-25 18:43:00 +00005707 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00005708 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005709}
5710
John McCallf312b1e2010-08-26 23:41:50 +00005711TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005712Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5713 const CXXScopeSpec &SS, IdentifierInfo *Name,
5714 SourceLocation TagLoc, SourceLocation NameLoc) {
5715 // This has to hold, because SS is expected to be defined.
5716 assert(Name && "Expected a name in a dependent tag");
5717
5718 NestedNameSpecifier *NNS
5719 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5720 if (!NNS)
5721 return true;
5722
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005723 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005724
Douglas Gregor48c89f42010-04-24 16:38:41 +00005725 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5726 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005727 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005728 return true;
5729 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005730
5731 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallb3d87482010-08-24 05:47:05 +00005732 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCallc4e70192009-09-11 04:59:25 +00005733}
5734
John McCallf312b1e2010-08-26 23:41:50 +00005735TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005736Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5737 const CXXScopeSpec &SS, const IdentifierInfo &II,
5738 SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005739 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005740 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5741 if (!NNS)
5742 return true;
5743
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005744 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5745 !getLangOptions().CPlusPlus0x)
5746 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5747 << FixItHint::CreateRemoval(TypenameLoc);
5748
Douglas Gregor107de902010-04-24 15:35:55 +00005749 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005750 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005751 if (T.isNull())
5752 return true;
John McCall63b43852010-04-29 23:50:39 +00005753
5754 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5755 if (isa<DependentNameType>(T)) {
5756 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005757 TL.setKeywordLoc(TypenameLoc);
5758 TL.setQualifierRange(SS.getRange());
5759 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005760 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005761 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005762 TL.setKeywordLoc(TypenameLoc);
5763 TL.setQualifierRange(SS.getRange());
5764 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005765 }
5766
John McCallb3d87482010-08-24 05:47:05 +00005767 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00005768}
5769
John McCallf312b1e2010-08-26 23:41:50 +00005770TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005771Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5772 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallb3d87482010-08-24 05:47:05 +00005773 ParsedType Ty) {
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
John McCall4e449832010-05-28 23:32:21 +00005779 TypeSourceInfo *InnerTSI = 0;
5780 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCall4e449832010-05-28 23:32:21 +00005781
5782 assert(isa<TemplateSpecializationType>(T) &&
5783 "Expected a template specialization type");
Douglas Gregor17343172009-04-01 00:28:59 +00005784
Douglas Gregor6946baf2009-09-02 13:05:45 +00005785 if (computeDeclContext(SS, false)) {
5786 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005787 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005788 // track of the nested-name-specifier.
John McCall4e449832010-05-28 23:32:21 +00005789
5790 // Push the inner type, preserving its source locations if possible.
5791 TypeLocBuilder Builder;
5792 if (InnerTSI)
5793 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5794 else
5795 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5796
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005797 /* Note: NNS already embedded in template specialization type T. */
5798 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCall4e449832010-05-28 23:32:21 +00005799 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5800 TL.setKeywordLoc(TypenameLoc);
5801 TL.setQualifierRange(SS.getRange());
5802
5803 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallb3d87482010-08-24 05:47:05 +00005804 return CreateParsedType(T, TSI);
Douglas Gregor6946baf2009-09-02 13:05:45 +00005805 }
Mike Stump1eb44332009-09-09 15:08:12 +00005806
John McCall33500952010-06-11 00:33:02 +00005807 // TODO: it's really silly that we make a template specialization
5808 // type earlier only to drop it again here.
5809 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5810 DependentTemplateName *DTN =
5811 TST->getTemplateName().getAsDependentTemplateName();
5812 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005813 assert(DTN->getQualifier()
5814 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5815 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5816 DTN->getQualifier(),
John McCall33500952010-06-11 00:33:02 +00005817 DTN->getIdentifier(),
5818 TST->getNumArgs(),
5819 TST->getArgs());
John McCall63b43852010-04-29 23:50:39 +00005820 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCall33500952010-06-11 00:33:02 +00005821 DependentTemplateSpecializationTypeLoc TL =
5822 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5823 if (InnerTSI) {
5824 TemplateSpecializationTypeLoc TSTL =
5825 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5826 TL.setLAngleLoc(TSTL.getLAngleLoc());
5827 TL.setRAngleLoc(TSTL.getRAngleLoc());
5828 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5829 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5830 } else {
5831 TL.initializeLocal(SourceLocation());
5832 }
John McCall4e449832010-05-28 23:32:21 +00005833 TL.setKeywordLoc(TypenameLoc);
5834 TL.setQualifierRange(SS.getRange());
John McCallb3d87482010-08-24 05:47:05 +00005835 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00005836}
5837
Douglas Gregord57959a2009-03-27 23:10:48 +00005838/// \brief Build the type that describes a C++ typename specifier,
5839/// e.g., "typename T::type".
5840QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005841Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5842 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005843 SourceLocation KeywordLoc, SourceRange NNSRange,
5844 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005845 CXXScopeSpec SS;
5846 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005847 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005848
John McCall77bb1aa2010-05-01 00:40:08 +00005849 DeclContext *Ctx = computeDeclContext(SS);
5850 if (!Ctx) {
5851 // If the nested-name-specifier is dependent and couldn't be
5852 // resolved to a type, build a typename type.
5853 assert(NNS->isDependent());
5854 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005855 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005856
John McCall77bb1aa2010-05-01 00:40:08 +00005857 // If the nested-name-specifier refers to the current instantiation,
5858 // the "typename" keyword itself is superfluous. In C++03, the
5859 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5860 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00005861 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005862
John McCall77bb1aa2010-05-01 00:40:08 +00005863 if (RequireCompleteDeclContext(SS, Ctx))
5864 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005865
5866 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005867 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005868 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005869 unsigned DiagID = 0;
5870 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005871 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005872 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005873 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005874 break;
Douglas Gregord9545042010-12-09 00:06:27 +00005875
5876 case LookupResult::FoundUnresolvedValue: {
5877 // We found a using declaration that is a value. Most likely, the using
5878 // declaration itself is meant to have the 'typename' keyword.
5879 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5880 IILoc);
5881 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
5882 << Name << Ctx << FullRange;
5883 if (UnresolvedUsingValueDecl *Using
5884 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
5885 SourceLocation Loc = Using->getTargetNestedNameRange().getBegin();
5886 Diag(Loc, diag::note_using_value_decl_missing_typename)
5887 << FixItHint::CreateInsertion(Loc, "typename ");
5888 }
5889 }
5890 // Fall through to create a dependent typename type, from which we can recover
5891 // better.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005892
5893 case LookupResult::NotFoundInCurrentInstantiation:
5894 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005895 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005896
5897 case LookupResult::Found:
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005898 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005899 // We found a type. Build an ElaboratedType, since the
5900 // typename-specifier was just sugar.
5901 return Context.getElaboratedType(ETK_Typename, NNS,
5902 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005903 }
5904
5905 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005906 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005907 break;
5908
Douglas Gregord9545042010-12-09 00:06:27 +00005909
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005910 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005911 return QualType();
5912
Douglas Gregord57959a2009-03-27 23:10:48 +00005913 case LookupResult::FoundOverloaded:
5914 DiagID = diag::err_typename_nested_not_type;
5915 Referenced = *Result.begin();
5916 break;
5917
John McCall6e247262009-10-10 05:48:19 +00005918 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005919 return QualType();
5920 }
5921
5922 // If we get here, it's because name lookup did not find a
5923 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005924 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5925 IILoc);
5926 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005927 if (Referenced)
5928 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5929 << Name;
5930 return QualType();
5931}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005932
5933namespace {
5934 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005935 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005936 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005937 SourceLocation Loc;
5938 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005939
Douglas Gregor4a959d82009-08-06 16:20:37 +00005940 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005941 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5942
Mike Stump1eb44332009-09-09 15:08:12 +00005943 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005944 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005945 DeclarationName Entity)
5946 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005947 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005948
5949 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005950 /// transformed.
5951 ///
5952 /// For the purposes of type reconstruction, a type has already been
5953 /// transformed if it is NULL or if it is not dependent.
5954 bool AlreadyTransformed(QualType T) {
5955 return T.isNull() || !T->isDependentType();
5956 }
Mike Stump1eb44332009-09-09 15:08:12 +00005957
5958 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005959 /// rebuilt.
5960 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005961
Douglas Gregor4a959d82009-08-06 16:20:37 +00005962 /// \brief Returns the name of the entity whose type is being rebuilt.
5963 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005964
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005965 /// \brief Sets the "base" location and entity when that
5966 /// information is known based on another transformation.
5967 void setBase(SourceLocation Loc, DeclarationName Entity) {
5968 this->Loc = Loc;
5969 this->Entity = Entity;
5970 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00005971 };
5972}
5973
Douglas Gregor4a959d82009-08-06 16:20:37 +00005974/// \brief Rebuilds a type within the context of the current instantiation.
5975///
Mike Stump1eb44332009-09-09 15:08:12 +00005976/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005977/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005978/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005979/// partial specialization thereof). This routine will rebuild that type now
5980/// that we have entered the declarator's scope, which may produce different
5981/// canonical types, e.g.,
5982///
5983/// \code
5984/// template<typename T>
5985/// struct X {
5986/// typedef T* pointer;
5987/// pointer data();
5988/// };
5989///
5990/// template<typename T>
5991/// typename X<T>::pointer X<T>::data() { ... }
5992/// \endcode
5993///
Douglas Gregor4714c122010-03-31 17:34:00 +00005994/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005995/// since we do not know that we can look into X<T> when we parsed the type.
5996/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005997/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00005998/// as the canonical type of T*, allowing the return types of the out-of-line
5999/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00006000TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6001 SourceLocation Loc,
6002 DeclarationName Name) {
6003 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00006004 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00006005
Douglas Gregor4a959d82009-08-06 16:20:37 +00006006 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
6007 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00006008}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006009
John McCall60d7b3a2010-08-24 06:29:42 +00006010ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00006011 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
6012 DeclarationName());
6013 return Rebuilder.TransformExpr(E);
6014}
6015
John McCall63b43852010-04-29 23:50:39 +00006016bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
6017 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00006018
6019 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6020 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
6021 DeclarationName());
6022 NestedNameSpecifier *Rebuilt =
6023 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00006024 if (!Rebuilt) return true;
6025
6026 SS.setScopeRep(Rebuilt);
6027 return false;
John McCall31f17ec2010-04-27 00:57:59 +00006028}
6029
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006030/// \brief Produces a formatted string that describes the binding of
6031/// template parameters to template arguments.
6032std::string
6033Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6034 const TemplateArgumentList &Args) {
Douglas Gregor910f8002010-11-07 23:05:16 +00006035 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006036}
6037
6038std::string
6039Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6040 const TemplateArgument *Args,
6041 unsigned NumArgs) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006042 llvm::SmallString<128> Str;
6043 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006044
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006045 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00006046 return std::string();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006047
6048 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006049 if (I >= NumArgs)
6050 break;
6051
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006052 if (I == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00006053 Out << "[with ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006054 else
Douglas Gregor87dd6972010-12-20 16:52:59 +00006055 Out << ", ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006056
6057 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006058 Out << Id->getName();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006059 } else {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006060 Out << '$' << I;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006061 }
6062
Douglas Gregor87dd6972010-12-20 16:52:59 +00006063 Out << " = ";
6064 Args[I].print(Context.PrintingPolicy, Out);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006065 }
Douglas Gregor87dd6972010-12-20 16:52:59 +00006066
6067 Out << ']';
6068 return Out.str();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006069}
Douglas Gregord0937222010-12-13 22:49:22 +00006070