blob: ad08a11f200da94504be9ff393058f121c7842cf [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
John McCall2d887082010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000014#include "clang/Sema/Scope.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000017#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000019#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000020#include "clang/AST/ExprCXX.h"
John McCall92b7f702010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000022#include "clang/AST/DeclTemplate.h"
John McCall4e2cbb22010-10-20 05:44:58 +000023#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor5f3aeb62010-10-13 00:27:52 +000024#include "clang/AST/TypeVisitor.h"
John McCall19510852010-08-20 18:27:03 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000027#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000029#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000030using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000031using namespace sema;
Douglas Gregor72c3f312008-12-05 18:15:24 +000032
John McCall78b81052010-11-10 02:40:36 +000033// Exported for use by Parser.
34SourceRange
35clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
36 unsigned N) {
37 if (!N) return SourceRange();
38 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
39}
40
Douglas Gregor2dd078a2009-09-02 22:59:36 +000041/// \brief Determine whether the declaration found is acceptable as the name
42/// of a template and, if so, return that template declaration. Otherwise,
43/// returns NULL.
John McCallad00b772010-06-16 08:42:20 +000044static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
45 NamedDecl *Orig) {
46 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000047
Douglas Gregor2dd078a2009-09-02 22:59:36 +000048 if (isa<TemplateDecl>(D))
John McCallad00b772010-06-16 08:42:20 +000049 return Orig;
Mike Stump1eb44332009-09-09 15:08:12 +000050
Douglas Gregor2dd078a2009-09-02 22:59:36 +000051 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
52 // C++ [temp.local]p1:
53 // Like normal (non-template) classes, class templates have an
54 // injected-class-name (Clause 9). The injected-class-name
55 // can be used with or without a template-argument-list. When
56 // it is used without a template-argument-list, it is
57 // equivalent to the injected-class-name followed by the
58 // template-parameters of the class template enclosed in
59 // <>. When it is used with a template-argument-list, it
60 // refers to the specified class template specialization,
61 // which could be the current specialization or another
62 // specialization.
63 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000064 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000065 if (Record->getDescribedClassTemplate())
66 return Record->getDescribedClassTemplate();
67
68 if (ClassTemplateSpecializationDecl *Spec
69 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
70 return Spec->getSpecializedTemplate();
71 }
Mike Stump1eb44332009-09-09 15:08:12 +000072
Douglas Gregor2dd078a2009-09-02 22:59:36 +000073 return 0;
74 }
Mike Stump1eb44332009-09-09 15:08:12 +000075
Douglas Gregor2dd078a2009-09-02 22:59:36 +000076 return 0;
77}
78
John McCallf7a1a742009-11-24 19:00:30 +000079static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor01e56ae2010-04-12 20:54:26 +000080 // The set of class templates we've already seen.
81 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCallf7a1a742009-11-24 19:00:30 +000082 LookupResult::Filter filter = R.makeFilter();
83 while (filter.hasNext()) {
84 NamedDecl *Orig = filter.next();
John McCallad00b772010-06-16 08:42:20 +000085 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCallf7a1a742009-11-24 19:00:30 +000086 if (!Repl)
87 filter.erase();
Douglas Gregor01e56ae2010-04-12 20:54:26 +000088 else if (Repl != Orig) {
89
90 // C++ [temp.local]p3:
91 // A lookup that finds an injected-class-name (10.2) can result in an
92 // ambiguity in certain cases (for example, if it is found in more than
93 // one base class). If all of the injected-class-names that are found
94 // refer to specializations of the same class template, and if the name
95 // is followed by a template-argument-list, the reference refers to the
96 // class template itself and not a specialization thereof, and is not
97 // ambiguous.
98 //
99 // FIXME: Will we eventually have to do the same for alias templates?
100 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
101 if (!ClassTemplates.insert(ClassTmpl)) {
102 filter.erase();
103 continue;
104 }
John McCall8ba66912010-08-13 07:02:08 +0000105
106 // FIXME: we promote access to public here as a workaround to
107 // the fact that LookupResult doesn't let us remember that we
108 // found this template through a particular injected class name,
109 // which means we end up doing nasty things to the invariants.
110 // Pretending that access is public is *much* safer.
111 filter.replace(Repl, AS_public);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000112 }
John McCallf7a1a742009-11-24 19:00:30 +0000113 }
114 filter.done();
115}
116
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000117TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000118 CXXScopeSpec &SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000119 bool hasTemplateKeyword,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000120 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +0000121 ParsedType ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000122 bool EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000123 TemplateTy &TemplateResult,
124 bool &MemberOfUnknownSpecialization) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000125 assert(getLangOptions().CPlusPlus && "No template names in C!");
126
Douglas Gregor014e88d2009-11-03 23:16:33 +0000127 DeclarationName TName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000128 MemberOfUnknownSpecialization = false;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000129
130 switch (Name.getKind()) {
131 case UnqualifiedId::IK_Identifier:
132 TName = DeclarationName(Name.Identifier);
133 break;
134
135 case UnqualifiedId::IK_OperatorFunctionId:
136 TName = Context.DeclarationNames.getCXXOperatorName(
137 Name.OperatorFunctionId.Operator);
138 break;
139
Sean Hunte6252d12009-11-28 08:58:14 +0000140 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000141 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
142 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000143
Douglas Gregor014e88d2009-11-03 23:16:33 +0000144 default:
145 return TNK_Non_template;
146 }
Mike Stump1eb44332009-09-09 15:08:12 +0000147
John McCallb3d87482010-08-24 05:47:05 +0000148 QualType ObjectType = ObjectTypePtr.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Douglas Gregorbfea2392009-12-31 08:11:17 +0000150 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
151 LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000152 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
153 MemberOfUnknownSpecialization);
John McCall67d22fb2010-08-28 20:17:00 +0000154 if (R.empty()) return TNK_Non_template;
155 if (R.isAmbiguous()) {
156 // Suppress diagnostics; we'll redo this lookup later.
John McCallb8592062010-08-13 02:23:42 +0000157 R.suppressDiagnostics();
John McCall67d22fb2010-08-28 20:17:00 +0000158
159 // FIXME: we might have ambiguous templates, in which case we
160 // should at least parse them properly!
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000161 return TNK_Non_template;
John McCallb8592062010-08-13 02:23:42 +0000162 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000163
John McCall0bd6feb2009-12-02 08:04:21 +0000164 TemplateName Template;
165 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000166
John McCall0bd6feb2009-12-02 08:04:21 +0000167 unsigned ResultCount = R.end() - R.begin();
168 if (ResultCount > 1) {
169 // We assume that we'll preserve the qualifier from a function
170 // template name in other ways.
171 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
172 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000173
174 // We'll do this lookup again later.
175 R.suppressDiagnostics();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000176 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000177 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
178
179 if (SS.isSet() && !SS.isInvalid()) {
180 NestedNameSpecifier *Qualifier
181 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c153532010-08-06 12:11:11 +0000182 Template = Context.getQualifiedTemplateName(Qualifier,
183 hasTemplateKeyword, TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000184 } else {
185 Template = TemplateName(TD);
186 }
187
John McCallb8592062010-08-13 02:23:42 +0000188 if (isa<FunctionTemplateDecl>(TD)) {
John McCall0bd6feb2009-12-02 08:04:21 +0000189 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000190
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
193 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000194 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
195 TemplateKind = TNK_Type_template;
196 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000197 }
Mike Stump1eb44332009-09-09 15:08:12 +0000198
John McCall0bd6feb2009-12-02 08:04:21 +0000199 TemplateResult = TemplateTy::make(Template);
200 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000201}
202
Douglas Gregor84d0a192010-01-12 21:28:44 +0000203bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
204 SourceLocation IILoc,
205 Scope *S,
206 const CXXScopeSpec *SS,
207 TemplateTy &SuggestedTemplate,
208 TemplateNameKind &SuggestedKind) {
209 // We can't recover unless there's a dependent scope specifier preceding the
210 // template name.
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000211 // FIXME: Typo correction?
Douglas Gregor84d0a192010-01-12 21:28:44 +0000212 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
213 computeDeclContext(*SS))
214 return false;
215
216 // The code is missing a 'template' keyword prior to the dependent template
217 // name.
218 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
219 Diag(IILoc, diag::err_template_kw_missing)
220 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000221 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor84d0a192010-01-12 21:28:44 +0000222 SuggestedTemplate
223 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
224 SuggestedKind = TNK_Dependent_template_name;
225 return true;
226}
227
John McCallf7a1a742009-11-24 19:00:30 +0000228void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000229 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000230 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000231 bool EnteringContext,
232 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000233 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000234 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-11-24 19:00:30 +0000235 DeclContext *LookupCtx = 0;
236 bool isDependent = false;
237 if (!ObjectType.isNull()) {
238 // This nested-name-specifier occurs in a member access expression, e.g.,
239 // x->B::f, and we are looking into the type of the object.
240 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
241 LookupCtx = computeDeclContext(ObjectType);
242 isDependent = ObjectType->isDependentType();
243 assert((isDependent || !ObjectType->isIncompleteType()) &&
244 "Caller should have completed object type");
245 } else if (SS.isSet()) {
246 // This nested-name-specifier occurs after another nested-name-specifier,
247 // so long into the context associated with the prior nested-name-specifier.
248 LookupCtx = computeDeclContext(SS, EnteringContext);
249 isDependent = isDependentScopeSpecifier(SS);
250
251 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000252 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000253 return;
254 }
255
256 bool ObjectTypeSearchedInScope = false;
257 if (LookupCtx) {
258 // Perform "qualified" name lookup into the declaration context we
259 // computed, which is either the type of the base of a member access
260 // expression or the declaration context associated with a prior
261 // nested-name-specifier.
262 LookupQualifiedName(Found, LookupCtx);
263
264 if (!ObjectType.isNull() && Found.empty()) {
265 // C++ [basic.lookup.classref]p1:
266 // In a class member access expression (5.2.5), if the . or -> token is
267 // immediately followed by an identifier followed by a <, the
268 // identifier must be looked up to determine whether the < is the
269 // beginning of a template argument list (14.2) or a less-than operator.
270 // The identifier is first looked up in the class of the object
271 // expression. If the identifier is not found, it is then looked up in
272 // the context of the entire postfix-expression and shall name a class
273 // or function template.
John McCallf7a1a742009-11-24 19:00:30 +0000274 if (S) LookupName(Found, S);
275 ObjectTypeSearchedInScope = true;
276 }
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000277 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000278 // We cannot look into a dependent object type or nested nme
279 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000280 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000281 return;
282 } else {
283 // Perform unqualified name lookup in the current scope.
284 LookupName(Found, S);
285 }
286
Douglas Gregor2e933882010-01-12 17:06:20 +0000287 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000288 // If we did not find any names, attempt to correct any typos.
289 DeclarationName Name = Found.getLookupName();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000290 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000291 false, CTC_CXXCasts)) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000292 FilterAcceptableTemplateNames(Context, Found);
John McCallad00b772010-06-16 08:42:20 +0000293 if (!Found.empty()) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000294 if (LookupCtx)
295 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
296 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000297 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000298 Found.getLookupName().getAsString());
299 else
300 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
301 << Name << Found.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000302 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000303 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000304 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
305 Diag(Template->getLocation(), diag::note_previous_decl)
306 << Template->getDeclName();
John McCallad00b772010-06-16 08:42:20 +0000307 }
Douglas Gregorbfea2392009-12-31 08:11:17 +0000308 } else {
309 Found.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000310 Found.setLookupName(Name);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000311 }
312 }
313
John McCallf7a1a742009-11-24 19:00:30 +0000314 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000315 if (Found.empty()) {
316 if (isDependent)
317 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000318 return;
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000319 }
John McCallf7a1a742009-11-24 19:00:30 +0000320
321 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
322 // C++ [basic.lookup.classref]p1:
323 // [...] If the lookup in the class of the object expression finds a
324 // template, the name is also looked up in the context of the entire
325 // postfix-expression and [...]
326 //
327 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
328 LookupOrdinaryName);
329 LookupName(FoundOuter, S);
330 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000331
John McCallf7a1a742009-11-24 19:00:30 +0000332 if (FoundOuter.empty()) {
333 // - if the name is not found, the name found in the class of the
334 // object expression is used, otherwise
335 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
336 // - if the name is found in the context of the entire
337 // postfix-expression and does not name a class template, the name
338 // found in the class of the object expression is used, otherwise
John McCallad00b772010-06-16 08:42:20 +0000339 } else if (!Found.isSuppressingDiagnostics()) {
John McCallf7a1a742009-11-24 19:00:30 +0000340 // - if the name found is a class template, it must refer to the same
341 // entity as the one found in the class of the object expression,
342 // otherwise the program is ill-formed.
343 if (!Found.isSingleResult() ||
344 Found.getFoundDecl()->getCanonicalDecl()
345 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
346 Diag(Found.getNameLoc(),
Jeffrey Yasskin21d07e42010-06-05 01:39:57 +0000347 diag::ext_nested_name_member_ref_lookup_ambiguous)
348 << Found.getLookupName()
349 << ObjectType;
John McCallf7a1a742009-11-24 19:00:30 +0000350 Diag(Found.getRepresentativeDecl()->getLocation(),
351 diag::note_ambig_member_ref_object_type)
352 << ObjectType;
353 Diag(FoundOuter.getFoundDecl()->getLocation(),
354 diag::note_ambig_member_ref_scope);
355
356 // Recover by taking the template that we found in the object
357 // expression's type.
358 }
359 }
360 }
361}
362
John McCall2f841ba2009-12-02 03:53:29 +0000363/// ActOnDependentIdExpression - Handle a dependent id-expression that
364/// was just parsed. This is only possible with an explicit scope
365/// specifier naming a dependent type.
John McCall60d7b3a2010-08-24 06:29:42 +0000366ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000367Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000368 const DeclarationNameInfo &NameInfo,
John McCall2f841ba2009-12-02 03:53:29 +0000369 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000370 const TemplateArgumentListInfo *TemplateArgs) {
371 NestedNameSpecifier *Qualifier
372 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallea1471e2010-05-20 01:18:31 +0000373
374 DeclContext *DC = getFunctionLevelDeclContext();
John McCallf7a1a742009-11-24 19:00:30 +0000375
John McCall2f841ba2009-12-02 03:53:29 +0000376 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000377 isa<CXXMethodDecl>(DC) &&
378 cast<CXXMethodDecl>(DC)->isInstance()) {
379 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2f841ba2009-12-02 03:53:29 +0000380
John McCallf7a1a742009-11-24 19:00:30 +0000381 // Since the 'this' expression is synthesized, we don't need to
382 // perform the double-lookup check.
383 NamedDecl *FirstQualifierInScope = 0;
384
John McCallaa81e162009-12-01 22:10:20 +0000385 return Owned(CXXDependentScopeMemberExpr::Create(Context,
386 /*This*/ 0, ThisType,
387 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000388 /*Op*/ SourceLocation(),
389 Qualifier, SS.getRange(),
390 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +0000391 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000392 TemplateArgs));
393 }
394
Abramo Bagnara25777432010-08-11 22:01:17 +0000395 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +0000396}
397
John McCall60d7b3a2010-08-24 06:29:42 +0000398ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000399Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000400 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000401 const TemplateArgumentListInfo *TemplateArgs) {
402 return Owned(DependentScopeDeclRefExpr::Create(Context,
403 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
404 SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +0000405 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000406 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000407}
408
Douglas Gregor72c3f312008-12-05 18:15:24 +0000409/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
410/// that the template parameter 'PrevDecl' is being shadowed by a new
411/// declaration at location Loc. Returns true to indicate that this is
412/// an error, and false otherwise.
413bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000414 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000415
416 // Microsoft Visual C++ permits template parameters to be shadowed.
417 if (getLangOptions().Microsoft)
418 return false;
419
420 // C++ [temp.local]p4:
421 // A template-parameter shall not be redeclared within its
422 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000423 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000424 << cast<NamedDecl>(PrevDecl)->getDeclName();
425 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
426 return true;
427}
428
Douglas Gregor2943aed2009-03-03 04:44:36 +0000429/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000430/// the parameter D to reference the templated declaration and return a pointer
431/// to the template declaration. Otherwise, do nothing to D and return null.
John McCalld226f652010-08-21 09:40:31 +0000432TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
433 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
434 D = Temp->getTemplatedDecl();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000435 return Temp;
436 }
437 return 0;
438}
439
Douglas Gregorba68eca2011-01-05 17:40:24 +0000440ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
441 SourceLocation EllipsisLoc) const {
442 assert(Kind == Template &&
443 "Only template template arguments can be pack expansions here");
444 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
445 "Template template argument pack expansion without packs");
446 ParsedTemplateArgument Result(*this);
447 Result.EllipsisLoc = EllipsisLoc;
448 return Result;
449}
450
Douglas Gregor788cd062009-11-11 01:00:40 +0000451static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
452 const ParsedTemplateArgument &Arg) {
453
454 switch (Arg.getKind()) {
455 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000456 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000457 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
458 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000459 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000460 return TemplateArgumentLoc(TemplateArgument(T), DI);
461 }
462
463 case ParsedTemplateArgument::NonType: {
464 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
465 return TemplateArgumentLoc(TemplateArgument(E), E);
466 }
467
468 case ParsedTemplateArgument::Template: {
John McCall2b5289b2010-08-23 07:28:44 +0000469 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor2be29f42011-01-14 23:41:42 +0000470 TemplateArgument TArg;
471 if (Arg.getEllipsisLoc().isValid())
472 TArg = TemplateArgument(Template, llvm::Optional<unsigned int>());
473 else
474 TArg = Template;
475 return TemplateArgumentLoc(TArg,
Douglas Gregor788cd062009-11-11 01:00:40 +0000476 Arg.getScopeSpec().getRange(),
Douglas Gregorba68eca2011-01-05 17:40:24 +0000477 Arg.getLocation(),
478 Arg.getEllipsisLoc());
Douglas Gregor788cd062009-11-11 01:00:40 +0000479 }
480 }
481
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000482 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000483 return TemplateArgumentLoc();
484}
485
486/// \brief Translates template arguments as provided by the parser
487/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000488void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
489 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000490 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000491 TemplateArgs.addArgument(translateTemplateArgument(*this,
492 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000493}
494
Douglas Gregor72c3f312008-12-05 18:15:24 +0000495/// ActOnTypeParameter - Called when a C++ template type parameter
496/// (e.g., "typename T") has been parsed. Typename specifies whether
497/// the keyword "typename" was used to declare the type parameter
498/// (otherwise, "class" was used), and KeyLoc is the location of the
499/// "class" or "typename" keyword. ParamName is the name of the
500/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregorefed5c82010-06-16 15:23:05 +0000501/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000502/// If the type parameter has a default argument, it will be added
503/// later via ActOnTypeParameterDefault.
John McCalld226f652010-08-21 09:40:31 +0000504Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
505 SourceLocation EllipsisLoc,
506 SourceLocation KeyLoc,
507 IdentifierInfo *ParamName,
508 SourceLocation ParamNameLoc,
509 unsigned Depth, unsigned Position,
510 SourceLocation EqualLoc,
John McCallb3d87482010-08-24 05:47:05 +0000511 ParsedType DefaultArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000512 assert(S->isTemplateParamScope() &&
513 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000514 bool Invalid = false;
515
516 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000517 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000518 LookupOrdinaryName,
519 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000520 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000521 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000522 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000523 }
524
Douglas Gregorddc29e12009-02-06 22:42:48 +0000525 SourceLocation Loc = ParamNameLoc;
526 if (!ParamName)
527 Loc = KeyLoc;
528
Douglas Gregor72c3f312008-12-05 18:15:24 +0000529 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000530 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
531 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000532 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000533 if (Invalid)
534 Param->setInvalidDecl();
535
536 if (ParamName) {
537 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000538 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000539 IdResolver.AddDecl(Param);
540 }
541
Douglas Gregor61c4d282011-01-05 15:48:55 +0000542 // C++0x [temp.param]p9:
543 // A default template-argument may be specified for any kind of
544 // template-parameter that is not a template parameter pack.
545 if (DefaultArg && Ellipsis) {
546 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
547 DefaultArg = ParsedType();
548 }
549
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000550 // Handle the default argument, if provided.
551 if (DefaultArg) {
552 TypeSourceInfo *DefaultTInfo;
553 GetTypeFromParser(DefaultArg, &DefaultTInfo);
554
555 assert(DefaultTInfo && "expected source information for type");
556
Douglas Gregor6f526752010-12-16 08:48:57 +0000557 // Check for unexpanded parameter packs.
558 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
559 UPPC_DefaultArgument))
560 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000561
562 // Check the template argument itself.
563 if (CheckTemplateArgument(Param, DefaultTInfo)) {
564 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000565 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000566 }
567
568 Param->setDefaultArgument(DefaultTInfo, false);
569 }
570
John McCalld226f652010-08-21 09:40:31 +0000571 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000572}
573
Douglas Gregor2943aed2009-03-03 04:44:36 +0000574/// \brief Check that the type of a non-type template parameter is
575/// well-formed.
576///
577/// \returns the (possibly-promoted) parameter type if valid;
578/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000579QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000580Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000581 // We don't allow variably-modified types as the type of non-type template
582 // parameters.
583 if (T->isVariablyModifiedType()) {
584 Diag(Loc, diag::err_variably_modified_nontype_template_param)
585 << T;
586 return QualType();
587 }
588
Douglas Gregor2943aed2009-03-03 04:44:36 +0000589 // C++ [temp.param]p4:
590 //
591 // A non-type template-parameter shall have one of the following
592 // (optionally cv-qualified) types:
593 //
594 // -- integral or enumeration type,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000595 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000596 // -- pointer to object or pointer to function,
Eli Friedman13578692010-08-05 02:49:48 +0000597 T->isPointerType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000598 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000599 T->isReferenceType() ||
600 // -- pointer to member.
601 T->isMemberPointerType() ||
602 // If T is a dependent type, we can't do the check now, so we
603 // assume that it is well-formed.
604 T->isDependentType())
605 return T;
606 // C++ [temp.param]p8:
607 //
608 // A non-type template-parameter of type "array of T" or
609 // "function returning T" is adjusted to be of type "pointer to
610 // T" or "pointer to function returning T", respectively.
611 else if (T->isArrayType())
612 // FIXME: Keep the type prior to promotion?
613 return Context.getArrayDecayedType(T);
614 else if (T->isFunctionType())
615 // FIXME: Keep the type prior to promotion?
616 return Context.getPointerType(T);
Douglas Gregor0fddb972010-05-22 16:17:30 +0000617
Douglas Gregor2943aed2009-03-03 04:44:36 +0000618 Diag(Loc, diag::err_template_nontype_parm_bad_type)
619 << T;
620
621 return QualType();
622}
623
John McCalld226f652010-08-21 09:40:31 +0000624Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
625 unsigned Depth,
626 unsigned Position,
627 SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000628 Expr *Default) {
John McCallbf1a0282010-06-04 23:28:52 +0000629 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
630 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000631
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000632 assert(S->isTemplateParamScope() &&
633 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000634 bool Invalid = false;
635
636 IdentifierInfo *ParamName = D.getIdentifier();
637 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000638 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000639 LookupOrdinaryName,
640 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000641 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000642 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000643 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000644 }
645
Douglas Gregor4d2abba2010-12-16 15:36:43 +0000646 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
647 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000648 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000649 Invalid = true;
650 }
Douglas Gregor781def02010-12-16 08:56:23 +0000651
Douglas Gregor10738d32010-12-23 23:51:58 +0000652 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000653 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000654 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
655 D.getIdentifierLoc(),
Douglas Gregor10738d32010-12-23 23:51:58 +0000656 Depth, Position, ParamName, T,
657 IsParameterPack, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000658 if (Invalid)
659 Param->setInvalidDecl();
660
661 if (D.getIdentifier()) {
662 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000663 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000664 IdResolver.AddDecl(Param);
665 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000666
Douglas Gregor61c4d282011-01-05 15:48:55 +0000667 // C++0x [temp.param]p9:
668 // A default template-argument may be specified for any kind of
669 // template-parameter that is not a template parameter pack.
670 if (Default && IsParameterPack) {
671 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
672 Default = 0;
673 }
674
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000675 // Check the well-formedness of the default template argument, if provided.
Douglas Gregor10738d32010-12-23 23:51:58 +0000676 if (Default) {
Douglas Gregor6f526752010-12-16 08:48:57 +0000677 // Check for unexpanded parameter packs.
678 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
679 return Param;
680
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000681 TemplateArgument Converted;
682 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
683 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000684 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000685 }
686
John McCall9ae2f072010-08-23 23:25:46 +0000687 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000688 }
689
John McCalld226f652010-08-21 09:40:31 +0000690 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000691}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000692
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000693/// ActOnTemplateTemplateParameter - Called when a C++ template template
694/// parameter (e.g. T in template <template <typename> class T> class array)
695/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000696Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
697 SourceLocation TmpLoc,
698 TemplateParamsTy *Params,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000699 SourceLocation EllipsisLoc,
John McCalld226f652010-08-21 09:40:31 +0000700 IdentifierInfo *Name,
701 SourceLocation NameLoc,
702 unsigned Depth,
703 unsigned Position,
704 SourceLocation EqualLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000705 ParsedTemplateArgument Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000706 assert(S->isTemplateParamScope() &&
707 "Template template parameter not in template parameter scope!");
708
709 // Construct the parameter object.
Douglas Gregor61c4d282011-01-05 15:48:55 +0000710 bool IsParameterPack = EllipsisLoc.isValid();
711 // FIXME: Pack-ness is dropped
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000712 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000713 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000714 NameLoc.isInvalid()? TmpLoc : NameLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000715 Depth, Position, IsParameterPack,
716 Name, Params);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000717
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000718 // If the template template parameter has a name, then link the identifier
719 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000720 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000721 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000722 IdResolver.AddDecl(Param);
723 }
724
Douglas Gregor6f526752010-12-16 08:48:57 +0000725 if (Params->size() == 0) {
726 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
727 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
728 Param->setInvalidDecl();
729 }
730
Douglas Gregor61c4d282011-01-05 15:48:55 +0000731 // C++0x [temp.param]p9:
732 // A default template-argument may be specified for any kind of
733 // template-parameter that is not a template parameter pack.
734 if (IsParameterPack && !Default.isInvalid()) {
735 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
736 Default = ParsedTemplateArgument();
737 }
738
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000739 if (!Default.isInvalid()) {
740 // Check only that we have a template template argument. We don't want to
741 // try to check well-formedness now, because our template template parameter
742 // might have dependent types in its template parameters, which we wouldn't
743 // be able to match now.
744 //
745 // If none of the template template parameter's template arguments mention
746 // other template parameters, we could actually perform more checking here.
747 // However, it isn't worth doing.
748 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
749 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
750 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
751 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000752 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000753 }
754
Douglas Gregor6f526752010-12-16 08:48:57 +0000755 // Check for unexpanded parameter packs.
756 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
757 DefaultArg.getArgument().getAsTemplate(),
758 UPPC_DefaultArgument))
759 return Param;
760
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000761 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000762 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000763
John McCalld226f652010-08-21 09:40:31 +0000764 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000765}
766
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000767/// ActOnTemplateParameterList - Builds a TemplateParameterList that
768/// contains the template parameters in Params/NumParams.
769Sema::TemplateParamsTy *
770Sema::ActOnTemplateParameterList(unsigned Depth,
771 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000772 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000773 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000774 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000775 SourceLocation RAngleLoc) {
776 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000777 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000778
Douglas Gregorddc29e12009-02-06 22:42:48 +0000779 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000780 (NamedDecl**)Params, NumParams,
781 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000782}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000783
John McCallb6217662010-03-15 10:12:16 +0000784static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
785 if (SS.isSet())
786 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
787 SS.getRange());
788}
789
John McCallf312b1e2010-08-26 23:41:50 +0000790DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000791Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000792 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000793 IdentifierInfo *Name, SourceLocation NameLoc,
794 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000795 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000796 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000797 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000798 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000799 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000800 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000801
802 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000803 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000804 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000805
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000806 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
807 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000808
809 // There is no such thing as an unnamed class template.
810 if (!Name) {
811 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000812 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000813 }
814
815 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000816 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000817 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000818 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000819 if (SS.isNotEmpty() && !SS.isInvalid()) {
820 SemanticContext = computeDeclContext(SS, true);
821 if (!SemanticContext) {
822 // FIXME: Produce a reasonable diagnostic here
823 return true;
824 }
Mike Stump1eb44332009-09-09 15:08:12 +0000825
John McCall77bb1aa2010-05-01 00:40:08 +0000826 if (RequireCompleteDeclContext(SS, SemanticContext))
827 return true;
828
John McCalla24dc2e2009-11-17 02:14:36 +0000829 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000830 } else {
831 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000832 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000833 }
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Douglas Gregor57265e32010-04-12 16:00:01 +0000835 if (Previous.isAmbiguous())
836 return true;
837
Douglas Gregorddc29e12009-02-06 22:42:48 +0000838 NamedDecl *PrevDecl = 0;
839 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000840 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000841
Douglas Gregorddc29e12009-02-06 22:42:48 +0000842 // If there is a previous declaration with the same name, check
843 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000844 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000845 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000846
847 // We may have found the injected-class-name of a class template,
848 // class template partial specialization, or class template specialization.
849 // In these cases, grab the template that is being defined or specialized.
850 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
851 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
852 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
853 PrevClassTemplate
854 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
855 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
856 PrevClassTemplate
857 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
858 ->getSpecializedTemplate();
859 }
860 }
861
John McCall65c49462009-12-18 11:25:59 +0000862 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000863 // C++ [namespace.memdef]p3:
864 // [...] When looking for a prior declaration of a class or a function
865 // declared as a friend, and when the name of the friend class or
866 // function is neither a qualified name nor a template-id, scopes outside
867 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000868 if (!SS.isSet()) {
869 DeclContext *OutermostContext = CurContext;
870 while (!OutermostContext->isFileContext())
871 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000872
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000873 if (PrevDecl &&
874 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
875 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
876 SemanticContext = PrevDecl->getDeclContext();
877 } else {
878 // Declarations in outer scopes don't matter. However, the outermost
879 // context we computed is the semantic context for our new
880 // declaration.
881 PrevDecl = PrevClassTemplate = 0;
882 SemanticContext = OutermostContext;
883 }
John McCalle129d442009-12-17 23:21:11 +0000884 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000885
John McCalle129d442009-12-17 23:21:11 +0000886 if (CurContext->isDependentContext()) {
887 // If this is a dependent context, we don't want to link the friend
888 // class template to the template in scope, because that would perform
889 // checking of the template parameter lists that can't be performed
890 // until the outer context is instantiated.
891 PrevDecl = PrevClassTemplate = 0;
892 }
893 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
894 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000895
Douglas Gregorddc29e12009-02-06 22:42:48 +0000896 if (PrevClassTemplate) {
897 // Ensure that the template parameter lists are compatible.
898 if (!TemplateParameterListsAreEqual(TemplateParams,
899 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000900 /*Complain=*/true,
901 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000902 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000903
904 // C++ [temp.class]p4:
905 // In a redeclaration, partial specialization, explicit
906 // specialization or explicit instantiation of a class template,
907 // the class-key shall agree in kind with the original class
908 // template declaration (7.1.5.3).
909 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000910 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000911 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000912 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000913 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000914 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000915 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000916 }
917
Douglas Gregorddc29e12009-02-06 22:42:48 +0000918 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000919 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000920 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000921 Diag(NameLoc, diag::err_redefinition) << Name;
922 Diag(Def->getLocation(), diag::note_previous_definition);
923 // FIXME: Would it make sense to try to "forget" the previous
924 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000925 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000926 }
927 }
928 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
929 // Maybe we will complain about the shadowed template parameter.
930 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
931 // Just pretend that we didn't see the previous declaration.
932 PrevDecl = 0;
933 } else if (PrevDecl) {
934 // C++ [temp]p5:
935 // A class template shall not have the same name as any other
936 // template, class, function, object, enumeration, enumerator,
937 // namespace, or type in the same scope (3.3), except as specified
938 // in (14.5.4).
939 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
940 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000941 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000942 }
943
Douglas Gregord684b002009-02-10 19:49:53 +0000944 // Check the template parameter list of this declaration, possibly
945 // merging in the template parameter list from the previous class
946 // template declaration.
947 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000948 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
949 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000950 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Douglas Gregor57265e32010-04-12 16:00:01 +0000952 if (SS.isSet()) {
953 // If the name of the template was qualified, we must be defining the
954 // template out-of-line.
955 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
956 !(TUK == TUK_Friend && CurContext->isDependentContext()))
957 Diag(NameLoc, diag::err_member_def_does_not_match)
958 << Name << SemanticContext << SS.getRange();
959 }
960
Mike Stump1eb44332009-09-09 15:08:12 +0000961 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000962 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000963 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000964 PrevClassTemplate->getTemplatedDecl() : 0,
965 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000966 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000967
968 ClassTemplateDecl *NewTemplate
969 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
970 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000971 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000972 NewClass->setDescribedClassTemplate(NewTemplate);
973
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000974 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +0000975 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +0000976 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000977 assert(T->isDependentType() && "Class template type is not dependent?");
978 (void)T;
979
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000980 // If we are providing an explicit specialization of a member that is a
981 // class template, make a note of that.
982 if (PrevClassTemplate &&
983 PrevClassTemplate->getInstantiatedFromMemberTemplate())
984 PrevClassTemplate->setMemberSpecialization();
985
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000986 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000987 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000988 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Douglas Gregorddc29e12009-02-06 22:42:48 +0000990 // Set the lexical context of these templates
991 NewClass->setLexicalDeclContext(CurContext);
992 NewTemplate->setLexicalDeclContext(CurContext);
993
John McCall0f434ec2009-07-31 02:45:11 +0000994 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000995 NewClass->startDefinition();
996
997 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000998 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000999
John McCall05b23ea2009-09-14 21:59:20 +00001000 if (TUK != TUK_Friend)
1001 PushOnScopeChains(NewTemplate, S);
1002 else {
Douglas Gregord85bea22009-09-26 06:47:28 +00001003 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +00001004 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +00001005 NewClass->setAccess(PrevClassTemplate->getAccess());
1006 }
John McCall05b23ea2009-09-14 21:59:20 +00001007
Douglas Gregord85bea22009-09-26 06:47:28 +00001008 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
1009 PrevClassTemplate != NULL);
1010
John McCall05b23ea2009-09-14 21:59:20 +00001011 // Friend templates are visible in fairly strange ways.
1012 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001013 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall05b23ea2009-09-14 21:59:20 +00001014 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
1015 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1016 PushOnScopeChains(NewTemplate, EnclosingScope,
1017 /* AddToContext = */ false);
1018 }
Douglas Gregord85bea22009-09-26 06:47:28 +00001019
1020 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1021 NewClass->getLocation(),
1022 NewTemplate,
1023 /*FIXME:*/NewClass->getLocation());
1024 Friend->setAccess(AS_public);
1025 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +00001026 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00001027
Douglas Gregord684b002009-02-10 19:49:53 +00001028 if (Invalid) {
1029 NewTemplate->setInvalidDecl();
1030 NewClass->setInvalidDecl();
1031 }
John McCalld226f652010-08-21 09:40:31 +00001032 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +00001033}
1034
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001035/// \brief Diagnose the presence of a default template argument on a
1036/// template parameter, which is ill-formed in certain contexts.
1037///
1038/// \returns true if the default template argument should be dropped.
1039static bool DiagnoseDefaultTemplateArgument(Sema &S,
1040 Sema::TemplateParamListContext TPC,
1041 SourceLocation ParamLoc,
1042 SourceRange DefArgRange) {
1043 switch (TPC) {
1044 case Sema::TPC_ClassTemplate:
1045 return false;
1046
1047 case Sema::TPC_FunctionTemplate:
1048 // C++ [temp.param]p9:
1049 // A default template-argument shall not be specified in a
1050 // function template declaration or a function template
1051 // definition [...]
1052 // (This sentence is not in C++0x, per DR226).
1053 if (!S.getLangOptions().CPlusPlus0x)
1054 S.Diag(ParamLoc,
1055 diag::err_template_parameter_default_in_function_template)
1056 << DefArgRange;
1057 return false;
1058
1059 case Sema::TPC_ClassTemplateMember:
1060 // C++0x [temp.param]p9:
1061 // A default template-argument shall not be specified in the
1062 // template-parameter-lists of the definition of a member of a
1063 // class template that appears outside of the member's class.
1064 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1065 << DefArgRange;
1066 return true;
1067
1068 case Sema::TPC_FriendFunctionTemplate:
1069 // C++ [temp.param]p9:
1070 // A default template-argument shall not be specified in a
1071 // friend template declaration.
1072 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1073 << DefArgRange;
1074 return true;
1075
1076 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1077 // for friend function templates if there is only a single
1078 // declaration (and it is a definition). Strange!
1079 }
1080
1081 return false;
1082}
1083
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001084/// \brief Check for unexpanded parameter packs within the template parameters
1085/// of a template template parameter, recursively.
1086bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP){
1087 TemplateParameterList *Params = TTP->getTemplateParameters();
1088 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1089 NamedDecl *P = Params->getParam(I);
1090 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1091 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1092 NTTP->getTypeSourceInfo(),
1093 Sema::UPPC_NonTypeTemplateParameterType))
1094 return true;
1095
1096 continue;
1097 }
1098
1099 if (TemplateTemplateParmDecl *InnerTTP
1100 = dyn_cast<TemplateTemplateParmDecl>(P))
1101 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1102 return true;
1103 }
1104
1105 return false;
1106}
1107
Douglas Gregord684b002009-02-10 19:49:53 +00001108/// \brief Checks the validity of a template parameter list, possibly
1109/// considering the template parameter list from a previous
1110/// declaration.
1111///
1112/// If an "old" template parameter list is provided, it must be
1113/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1114/// template parameter list.
1115///
1116/// \param NewParams Template parameter list for a new template
1117/// declaration. This template parameter list will be updated with any
1118/// default arguments that are carried through from the previous
1119/// template parameter list.
1120///
1121/// \param OldParams If provided, template parameter list from a
1122/// previous declaration of the same template. Default template
1123/// arguments will be merged from the old template parameter list to
1124/// the new template parameter list.
1125///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001126/// \param TPC Describes the context in which we are checking the given
1127/// template parameter list.
1128///
Douglas Gregord684b002009-02-10 19:49:53 +00001129/// \returns true if an error occurred, false otherwise.
1130bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001131 TemplateParameterList *OldParams,
1132 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001133 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001134
Douglas Gregord684b002009-02-10 19:49:53 +00001135 // C++ [temp.param]p10:
1136 // The set of default template-arguments available for use with a
1137 // template declaration or definition is obtained by merging the
1138 // default arguments from the definition (if in scope) and all
1139 // declarations in scope in the same way default function
1140 // arguments are (8.3.6).
1141 bool SawDefaultArgument = false;
1142 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001143
Anders Carlsson49d25572009-06-12 23:20:15 +00001144 bool SawParameterPack = false;
1145 SourceLocation ParameterPackLoc;
1146
Mike Stump1a35fde2009-02-11 23:03:27 +00001147 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001148 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001149 if (OldParams)
1150 OldParam = OldParams->begin();
1151
1152 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1153 NewParamEnd = NewParams->end();
1154 NewParam != NewParamEnd; ++NewParam) {
1155 // Variables used to diagnose redundant default arguments
1156 bool RedundantDefaultArg = false;
1157 SourceLocation OldDefaultLoc;
1158 SourceLocation NewDefaultLoc;
1159
1160 // Variables used to diagnose missing default arguments
1161 bool MissingDefaultArg = false;
1162
Anders Carlsson49d25572009-06-12 23:20:15 +00001163 // C++0x [temp.param]p11:
Douglas Gregor1ed64762011-01-05 16:19:19 +00001164 // If a template parameter of a primary class template is a template
1165 // parameter pack, it shall be the last template parameter.
1166 if (SawParameterPack && TPC == TPC_ClassTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00001167 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001168 diag::err_template_param_pack_must_be_last_template_parameter);
1169 Invalid = true;
1170 }
1171
Douglas Gregord684b002009-02-10 19:49:53 +00001172 if (TemplateTypeParmDecl *NewTypeParm
1173 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001174 // Check the presence of a default argument here.
1175 if (NewTypeParm->hasDefaultArgument() &&
1176 DiagnoseDefaultTemplateArgument(*this, TPC,
1177 NewTypeParm->getLocation(),
1178 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001179 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001180 NewTypeParm->removeDefaultArgument();
1181
1182 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001183 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001184 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Anders Carlsson49d25572009-06-12 23:20:15 +00001186 if (NewTypeParm->isParameterPack()) {
1187 assert(!NewTypeParm->hasDefaultArgument() &&
1188 "Parameter packs can't have a default argument!");
1189 SawParameterPack = true;
1190 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001191 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001192 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001193 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1194 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1195 SawDefaultArgument = true;
1196 RedundantDefaultArg = true;
1197 PreviousDefaultArgLoc = NewDefaultLoc;
1198 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1199 // Merge the default argument from the old declaration to the
1200 // new declaration.
1201 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001202 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001203 true);
1204 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1205 } else if (NewTypeParm->hasDefaultArgument()) {
1206 SawDefaultArgument = true;
1207 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1208 } else if (SawDefaultArgument)
1209 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001210 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001211 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001212 // Check for unexpanded parameter packs.
1213 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1214 NewNonTypeParm->getTypeSourceInfo(),
1215 UPPC_NonTypeTemplateParameterType)) {
1216 Invalid = true;
1217 continue;
1218 }
1219
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001220 // Check the presence of a default argument here.
1221 if (NewNonTypeParm->hasDefaultArgument() &&
1222 DiagnoseDefaultTemplateArgument(*this, TPC,
1223 NewNonTypeParm->getLocation(),
1224 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001225 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001226 }
1227
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001228 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001229 NonTypeTemplateParmDecl *OldNonTypeParm
1230 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001231 if (NewNonTypeParm->isParameterPack()) {
1232 assert(!NewNonTypeParm->hasDefaultArgument() &&
1233 "Parameter packs can't have a default argument!");
1234 SawParameterPack = true;
1235 ParameterPackLoc = NewNonTypeParm->getLocation();
1236 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001237 NewNonTypeParm->hasDefaultArgument()) {
1238 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1239 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1240 SawDefaultArgument = true;
1241 RedundantDefaultArg = true;
1242 PreviousDefaultArgLoc = NewDefaultLoc;
1243 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1244 // Merge the default argument from the old declaration to the
1245 // new declaration.
1246 SawDefaultArgument = true;
1247 // FIXME: We need to create a new kind of "default argument"
Douglas Gregor61c4d282011-01-05 15:48:55 +00001248 // expression that points to a previous non-type template
Douglas Gregord684b002009-02-10 19:49:53 +00001249 // parameter.
1250 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001251 OldNonTypeParm->getDefaultArgument(),
1252 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001253 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1254 } else if (NewNonTypeParm->hasDefaultArgument()) {
1255 SawDefaultArgument = true;
1256 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1257 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001258 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001259 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001260 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001261 TemplateTemplateParmDecl *NewTemplateParm
1262 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001263
1264 // Check for unexpanded parameter packs, recursively.
1265 if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1266 Invalid = true;
1267 continue;
1268 }
1269
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001270 if (NewTemplateParm->hasDefaultArgument() &&
1271 DiagnoseDefaultTemplateArgument(*this, TPC,
1272 NewTemplateParm->getLocation(),
1273 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001274 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001275
1276 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001277 TemplateTemplateParmDecl *OldTemplateParm
1278 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Douglas Gregor1ed64762011-01-05 16:19:19 +00001279 if (NewTemplateParm->isParameterPack()) {
1280 assert(!NewTemplateParm->hasDefaultArgument() &&
1281 "Parameter packs can't have a default argument!");
1282 SawParameterPack = true;
1283 ParameterPackLoc = NewTemplateParm->getLocation();
1284 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001285 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001286 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1287 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001288 SawDefaultArgument = true;
1289 RedundantDefaultArg = true;
1290 PreviousDefaultArgLoc = NewDefaultLoc;
1291 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1292 // Merge the default argument from the old declaration to the
1293 // new declaration.
1294 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001295 // FIXME: We need to create a new kind of "default argument" expression
1296 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001297 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001298 OldTemplateParm->getDefaultArgument(),
1299 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001300 PreviousDefaultArgLoc
1301 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001302 } else if (NewTemplateParm->hasDefaultArgument()) {
1303 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001304 PreviousDefaultArgLoc
1305 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001306 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001307 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001308 }
1309
1310 if (RedundantDefaultArg) {
1311 // C++ [temp.param]p12:
1312 // A template-parameter shall not be given default arguments
1313 // by two different declarations in the same scope.
1314 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1315 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1316 Invalid = true;
1317 } else if (MissingDefaultArg) {
1318 // C++ [temp.param]p11:
Douglas Gregorb49e4152011-01-05 16:21:17 +00001319 // If a template-parameter of a class template has a default
1320 // template-argument, each subsequent template- parameter shall either
1321 // have a default template-argument supplied or be a template parameter
1322 // pack.
Mike Stump1eb44332009-09-09 15:08:12 +00001323 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001324 diag::err_template_param_default_arg_missing);
1325 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1326 Invalid = true;
1327 }
1328
1329 // If we have an old template parameter list that we're merging
1330 // in, move on to the next parameter.
1331 if (OldParams)
1332 ++OldParam;
1333 }
1334
1335 return Invalid;
1336}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001337
John McCall4e2cbb22010-10-20 05:44:58 +00001338namespace {
1339
1340/// A class which looks for a use of a certain level of template
1341/// parameter.
1342struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1343 typedef RecursiveASTVisitor<DependencyChecker> super;
1344
1345 unsigned Depth;
1346 bool Match;
1347
1348 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1349 NamedDecl *ND = Params->getParam(0);
1350 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1351 Depth = PD->getDepth();
1352 } else if (NonTypeTemplateParmDecl *PD =
1353 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1354 Depth = PD->getDepth();
1355 } else {
1356 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1357 }
1358 }
1359
1360 bool Matches(unsigned ParmDepth) {
1361 if (ParmDepth >= Depth) {
1362 Match = true;
1363 return true;
1364 }
1365 return false;
1366 }
1367
1368 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1369 return !Matches(T->getDepth());
1370 }
1371
1372 bool TraverseTemplateName(TemplateName N) {
1373 if (TemplateTemplateParmDecl *PD =
1374 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1375 if (Matches(PD->getDepth())) return false;
1376 return super::TraverseTemplateName(N);
1377 }
1378
1379 bool VisitDeclRefExpr(DeclRefExpr *E) {
1380 if (NonTypeTemplateParmDecl *PD =
1381 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1382 if (PD->getDepth() == Depth) {
1383 Match = true;
1384 return false;
1385 }
1386 }
1387 return super::VisitDeclRefExpr(E);
1388 }
1389};
1390}
1391
1392/// Determines whether a template-id depends on the given parameter
1393/// list.
1394static bool
1395DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId,
1396 TemplateParameterList *Params) {
1397 DependencyChecker Checker(Params);
1398 Checker.TraverseType(QualType(TemplateId, 0));
1399 return Checker.Match;
1400}
1401
Mike Stump1eb44332009-09-09 15:08:12 +00001402/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001403/// specifier, returning the template parameter list that applies to the
1404/// name.
1405///
1406/// \param DeclStartLoc the start of the declaration that has a scope
1407/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001408///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001409/// \param SS the scope specifier that will be matched to the given template
1410/// parameter lists. This scope specifier precedes a qualified name that is
1411/// being declared.
1412///
1413/// \param ParamLists the template parameter lists, from the outermost to the
1414/// innermost template parameter lists.
1415///
1416/// \param NumParamLists the number of template parameter lists in ParamLists.
1417///
John McCall77e8b112010-04-13 20:37:33 +00001418/// \param IsFriend Whether to apply the slightly different rules for
1419/// matching template parameters to scope specifiers in friend
1420/// declarations.
1421///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001422/// \param IsExplicitSpecialization will be set true if the entity being
1423/// declared is an explicit specialization, false otherwise.
1424///
Mike Stump1eb44332009-09-09 15:08:12 +00001425/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001426/// name that is preceded by the scope specifier @p SS. This template
1427/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001428/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001429/// template specialization), or may be NULL (if we were's declaring isn't
1430/// itself a template).
1431TemplateParameterList *
1432Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1433 const CXXScopeSpec &SS,
1434 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001435 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001436 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001437 bool &IsExplicitSpecialization,
1438 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001439 IsExplicitSpecialization = false;
1440
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001441 // Find the template-ids that occur within the nested-name-specifier. These
1442 // template-ids will match up with the template parameter lists.
1443 llvm::SmallVector<const TemplateSpecializationType *, 4>
1444 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001445 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1446 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001447 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1448 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001449 const Type *T = NNS->getAsType();
1450 if (!T) break;
1451
1452 // C++0x [temp.expl.spec]p17:
1453 // A member or a member template may be nested within many
1454 // enclosing class templates. In an explicit specialization for
1455 // such a member, the member declaration shall be preceded by a
1456 // template<> for each enclosing class template that is
1457 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001458 //
1459 // Following the existing practice of GNU and EDG, we allow a typedef of a
1460 // template specialization type.
John McCall49f4e1c2010-12-10 11:01:00 +00001461 while (const TypedefType *TT = dyn_cast<TypedefType>(T))
1462 T = TT->getDecl()->getUnderlyingType().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001463
Mike Stump1eb44332009-09-09 15:08:12 +00001464 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001465 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001466 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1467 if (!Template)
1468 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Ted Kremenek6217b802009-07-29 21:53:49 +00001470 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001471 ClassTemplateSpecializationDecl *SpecDecl
1472 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1473 // If the nested name specifier refers to an explicit specialization,
1474 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001475 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1476 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001477 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001478 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001479 }
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001481 TemplateIdsInSpecifier.push_back(SpecType);
1482 }
1483 }
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001485 // Reverse the list of template-ids in the scope specifier, so that we can
1486 // more easily match up the template-ids and the template parameter lists.
1487 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001489 SourceLocation FirstTemplateLoc = DeclStartLoc;
1490 if (NumParamLists)
1491 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001493 // Match the template-ids found in the specifier to the template parameter
1494 // lists.
John McCall4e2cbb22010-10-20 05:44:58 +00001495 unsigned ParamIdx = 0, TemplateIdx = 0;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001496 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
John McCall4e2cbb22010-10-20 05:44:58 +00001497 TemplateIdx != NumTemplateIds; ++TemplateIdx) {
1498 const TemplateSpecializationType *TemplateId
1499 = TemplateIdsInSpecifier[TemplateIdx];
Douglas Gregorb88e8882009-07-30 17:40:51 +00001500 bool DependentTemplateId = TemplateId->isDependentType();
John McCall4e2cbb22010-10-20 05:44:58 +00001501
1502 // In friend declarations we can have template-ids which don't
1503 // depend on the corresponding template parameter lists. But
1504 // assume that empty parameter lists are supposed to match this
1505 // template-id.
1506 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) {
1507 if (!DependentTemplateId ||
1508 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx]))
1509 continue;
1510 }
1511
1512 if (ParamIdx >= NumParamLists) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001513 // We have a template-id without a corresponding template parameter
1514 // list.
John McCall77e8b112010-04-13 20:37:33 +00001515
1516 // ...which is fine if this is a friend declaration.
1517 if (IsFriend) {
1518 IsExplicitSpecialization = true;
1519 break;
1520 }
1521
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001522 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001523 // FIXME: the location information here isn't great.
1524 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001525 diag::err_template_spec_needs_template_parameters)
John McCall4e2cbb22010-10-20 05:44:58 +00001526 << QualType(TemplateId, 0)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001527 << SS.getRange();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001528 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001529 } else {
1530 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1531 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001532 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001533 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001534 }
1535 return 0;
1536 }
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001538 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001539 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001540 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001541
John McCall31f17ec2010-04-27 00:57:59 +00001542 // Are there cases in (e.g.) friends where this won't match?
1543 if (const InjectedClassNameType *Injected
1544 = TemplateId->getAs<InjectedClassNameType>()) {
1545 CXXRecordDecl *Record = Injected->getDecl();
1546 if (ClassTemplatePartialSpecializationDecl *Partial =
1547 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1548 ExpectedTemplateParams = Partial->getTemplateParameters();
1549 else
1550 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1551 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001552 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001553
John McCall31f17ec2010-04-27 00:57:59 +00001554 if (ExpectedTemplateParams)
John McCall4e2cbb22010-10-20 05:44:58 +00001555 TemplateParameterListsAreEqual(ParamLists[ParamIdx],
John McCall31f17ec2010-04-27 00:57:59 +00001556 ExpectedTemplateParams,
1557 true, TPL_TemplateMatch);
1558
John McCall4e2cbb22010-10-20 05:44:58 +00001559 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1560 TPC_ClassTemplateMember);
1561 } else if (ParamLists[ParamIdx]->size() > 0)
1562 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001563 diag::err_template_param_list_matches_nontemplate)
1564 << TemplateId
John McCall4e2cbb22010-10-20 05:44:58 +00001565 << ParamLists[ParamIdx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001566 else
1567 IsExplicitSpecialization = true;
John McCall4e2cbb22010-10-20 05:44:58 +00001568
1569 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001570 }
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001572 // If there were at least as many template-ids as there were template
1573 // parameter lists, then there are no template parameter lists remaining for
1574 // the declaration itself.
John McCall4e2cbb22010-10-20 05:44:58 +00001575 if (ParamIdx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001576 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001578 // If there were too many template parameter lists, complain about that now.
John McCall4e2cbb22010-10-20 05:44:58 +00001579 if (ParamIdx != NumParamLists - 1) {
1580 while (ParamIdx < NumParamLists - 1) {
1581 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0;
1582 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001583 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1584 : diag::err_template_spec_extra_headers)
John McCall4e2cbb22010-10-20 05:44:58 +00001585 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1586 ParamLists[ParamIdx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001587
1588 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1589 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1590 diag::note_explicit_template_spec_does_not_need_header)
1591 << ExplicitSpecializationsInSpecifier.back();
1592 ExplicitSpecializationsInSpecifier.pop_back();
1593 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001594
1595 // We have a template parameter list with no corresponding scope, which
1596 // means that the resulting template declaration can't be instantiated
1597 // properly (we'll end up with dependent nodes when we shouldn't).
1598 if (!isExplicitSpecHeader)
1599 Invalid = true;
1600
John McCall4e2cbb22010-10-20 05:44:58 +00001601 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001602 }
1603 }
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001605 // Return the last template parameter list, which corresponds to the
1606 // entity being declared.
1607 return ParamLists[NumParamLists - 1];
1608}
1609
Douglas Gregor7532dc62009-03-30 22:58:21 +00001610QualType Sema::CheckTemplateIdType(TemplateName Name,
1611 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001612 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001613 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001614 if (!Template) {
1615 // The template name does not resolve to a template, so we just
1616 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001617 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001618 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001619
Douglas Gregor40808ce2009-03-09 23:48:35 +00001620 // Check that the template argument list is well-formed for this
1621 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001622 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00001623 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001624 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001625 return QualType();
1626
Douglas Gregor910f8002010-11-07 23:05:16 +00001627 assert((Converted.size() == Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001628 "Converted template argument list is too short!");
1629
1630 QualType CanonType;
1631
Douglas Gregorcaddba02009-11-12 18:38:13 +00001632 if (Name.isDependent() ||
1633 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001634 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001635 // This class template specialization is a dependent
1636 // type. Therefore, its canonical type is another class template
1637 // specialization type that contains all of the converted
1638 // arguments in canonical form. This ensures that, e.g., A<T> and
1639 // A<T, T> have identical types when A is declared as:
1640 //
1641 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001642 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001643 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor910f8002010-11-07 23:05:16 +00001644 Converted.data(),
1645 Converted.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Douglas Gregor1275ae02009-07-28 23:00:59 +00001647 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001648 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001649 // In the future, we need to teach getTemplateSpecializationType to only
1650 // build the canonical type and return that to us.
1651 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001652
1653 // This might work out to be a current instantiation, in which
1654 // case the canonical type needs to be the InjectedClassNameType.
1655 //
1656 // TODO: in theory this could be a simple hashtable lookup; most
1657 // changes to CurContext don't change the set of current
1658 // instantiations.
1659 if (isa<ClassTemplateDecl>(Template)) {
1660 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1661 // If we get out to a namespace, we're done.
1662 if (Ctx->isFileContext()) break;
1663
1664 // If this isn't a record, keep looking.
1665 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1666 if (!Record) continue;
1667
1668 // Look for one of the two cases with InjectedClassNameTypes
1669 // and check whether it's the same template.
1670 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1671 !Record->getDescribedClassTemplate())
1672 continue;
1673
1674 // Fetch the injected class name type and check whether its
1675 // injected type is equal to the type we just built.
1676 QualType ICNT = Context.getTypeDeclType(Record);
1677 QualType Injected = cast<InjectedClassNameType>(ICNT)
1678 ->getInjectedSpecializationType();
1679
1680 if (CanonType != Injected->getCanonicalTypeInternal())
1681 continue;
1682
1683 // If so, the canonical type of this TST is the injected
1684 // class name type of the record we just found.
1685 assert(ICNT.isCanonical());
1686 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00001687 break;
1688 }
1689 }
Mike Stump1eb44332009-09-09 15:08:12 +00001690 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001691 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001692 // Find the class template specialization declaration that
1693 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001694 void *InsertPos = 0;
1695 ClassTemplateSpecializationDecl *Decl
Douglas Gregor910f8002010-11-07 23:05:16 +00001696 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
1697 InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001698 if (!Decl) {
1699 // This is the first time we have referenced this class template
1700 // specialization. Create the canonical declaration and add it to
1701 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001702 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001703 ClassTemplate->getTemplatedDecl()->getTagKind(),
1704 ClassTemplate->getDeclContext(),
1705 ClassTemplate->getLocation(),
Douglas Gregor910f8002010-11-07 23:05:16 +00001706 ClassTemplate,
1707 Converted.data(),
1708 Converted.size(), 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001709 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001710 Decl->setLexicalDeclContext(CurContext);
1711 }
1712
1713 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001714 assert(isa<RecordType>(CanonType) &&
1715 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001716 }
Mike Stump1eb44332009-09-09 15:08:12 +00001717
Douglas Gregor40808ce2009-03-09 23:48:35 +00001718 // Build the fully-sugared type for this class template
1719 // specialization, which refers back to the class template
1720 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00001721 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001722}
1723
John McCallf312b1e2010-08-26 23:41:50 +00001724TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001725Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001726 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001727 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001728 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001729 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001730
Douglas Gregor40808ce2009-03-09 23:48:35 +00001731 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001732 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001733 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001734
John McCalld5532b62009-11-23 01:53:49 +00001735 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001736 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001737
1738 if (Result.isNull())
1739 return true;
1740
John McCalla93c9342009-12-07 02:54:59 +00001741 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001742 TemplateSpecializationTypeLoc TL
1743 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1744 TL.setTemplateNameLoc(TemplateLoc);
1745 TL.setLAngleLoc(LAngleLoc);
1746 TL.setRAngleLoc(RAngleLoc);
1747 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1748 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1749
John McCallb3d87482010-08-24 05:47:05 +00001750 return CreateParsedType(Result, DI);
John McCall6b2becf2009-09-08 17:47:29 +00001751}
John McCallf1bbbb42009-09-04 01:14:41 +00001752
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001753TypeResult Sema::ActOnTagTemplateIdType(CXXScopeSpec &SS,
1754 TypeResult TypeResult,
John McCallf312b1e2010-08-26 23:41:50 +00001755 TagUseKind TUK,
1756 TypeSpecifierType TagSpec,
1757 SourceLocation TagLoc) {
John McCall6b2becf2009-09-08 17:47:29 +00001758 if (TypeResult.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001759 return ::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001760
John McCalla93c9342009-12-07 02:54:59 +00001761 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001762 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001763
John McCall6b2becf2009-09-08 17:47:29 +00001764 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001765 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001766
John McCall6b2becf2009-09-08 17:47:29 +00001767 if (const RecordType *RT = Type->getAs<RecordType>()) {
1768 RecordDecl *D = RT->getDecl();
1769
1770 IdentifierInfo *Id = D->getIdentifier();
1771 assert(Id && "templated class must have an identifier");
1772
1773 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1774 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001775 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001776 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001777 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001778 }
1779 }
1780
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001781 ElaboratedTypeKeyword Keyword
1782 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1783 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001784
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001785 TypeSourceInfo *ElabDI = Context.CreateTypeSourceInfo(ElabType);
1786 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(ElabDI->getTypeLoc());
1787 TL.setKeywordLoc(TagLoc);
1788 TL.setQualifierRange(SS.getRange());
1789 TL.getNamedTypeLoc().initializeFullCopy(DI->getTypeLoc());
1790 return CreateParsedType(ElabType, ElabDI);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001791}
1792
John McCall60d7b3a2010-08-24 06:29:42 +00001793ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001794 LookupResult &R,
1795 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001796 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001797 // FIXME: Can we do any checking at this point? I guess we could check the
1798 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001799 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001800 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001801
1802 // These should be filtered out by our callers.
1803 assert(!R.empty() && "empty lookup results when building templateid");
1804 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1805
1806 NestedNameSpecifier *Qualifier = 0;
1807 SourceRange QualifierRange;
1808 if (SS.isSet()) {
1809 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1810 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001811 }
John McCallc373d482010-01-27 01:50:18 +00001812
1813 // We don't want lookup warnings at this point.
1814 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001815
John McCallf7a1a742009-11-24 19:00:30 +00001816 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001817 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001818 Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00001819 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001820 RequiresADL, TemplateArgs,
1821 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001822
1823 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001824}
1825
John McCallf7a1a742009-11-24 19:00:30 +00001826// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00001827ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001828Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001829 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +00001830 const TemplateArgumentListInfo &TemplateArgs) {
1831 DeclContext *DC;
1832 if (!(DC = computeDeclContext(SS, false)) ||
1833 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001834 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara25777432010-08-11 22:01:17 +00001835 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001836
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001837 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00001838 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001839 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1840 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001841
John McCallf7a1a742009-11-24 19:00:30 +00001842 if (R.isAmbiguous())
1843 return ExprError();
1844
1845 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001846 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1847 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001848 return ExprError();
1849 }
1850
1851 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001852 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1853 << (NestedNameSpecifier*) SS.getScopeRep()
1854 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001855 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1856 return ExprError();
1857 }
1858
1859 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001860}
1861
Douglas Gregorc45c2322009-03-31 00:43:58 +00001862/// \brief Form a dependent template name.
1863///
1864/// This action forms a dependent template name given the template
1865/// name and its (presumably dependent) scope specifier. For
1866/// example, given "MetaFun::template apply", the scope specifier \p
1867/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1868/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001869TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1870 SourceLocation TemplateKWLoc,
1871 CXXScopeSpec &SS,
1872 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00001873 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001874 bool EnteringContext,
1875 TemplateTy &Result) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00001876 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1877 !getLangOptions().CPlusPlus0x)
1878 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1879 << FixItHint::CreateRemoval(TemplateKWLoc);
1880
Douglas Gregor0707bc52010-01-19 16:01:07 +00001881 DeclContext *LookupCtx = 0;
1882 if (SS.isSet())
1883 LookupCtx = computeDeclContext(SS, EnteringContext);
1884 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00001885 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00001886 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001887 // C++0x [temp.names]p5:
1888 // If a name prefixed by the keyword template is not the name of
1889 // a template, the program is ill-formed. [Note: the keyword
1890 // template may not be applied to non-template members of class
1891 // templates. -end note ] [ Note: as is the case with the
1892 // typename prefix, the template prefix is allowed in cases
1893 // where it is not strictly necessary; i.e., when the
1894 // nested-name-specifier or the expression on the left of the ->
1895 // or . is not dependent on a template-parameter, or the use
1896 // does not appear in the scope of a template. -end note]
1897 //
1898 // Note: C++03 was more strict here, because it banned the use of
1899 // the "template" keyword prior to a template-name that was not a
1900 // dependent name. C++ DR468 relaxed this requirement (the
1901 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00001902 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001903 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001904 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1905 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001906 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001907 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1908 isa<CXXRecordDecl>(LookupCtx) &&
1909 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00001910 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001911 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001912 Diag(Name.getSourceRange().getBegin(),
1913 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001914 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001915 << Name.getSourceRange()
1916 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001917 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001918 } else {
1919 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001920 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001921 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001922 }
1923
Mike Stump1eb44332009-09-09 15:08:12 +00001924 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001925 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001926
1927 switch (Name.getKind()) {
1928 case UnqualifiedId::IK_Identifier:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001929 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1930 Name.Identifier));
1931 return TNK_Dependent_template_name;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001932
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001933 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001934 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001935 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00001936 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00001937
1938 case UnqualifiedId::IK_LiteralOperatorId:
1939 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1940
Douglas Gregor014e88d2009-11-03 23:16:33 +00001941 default:
1942 break;
1943 }
1944
1945 Diag(Name.getSourceRange().getBegin(),
1946 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001947 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001948 << Name.getSourceRange()
1949 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001950 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001951}
1952
Mike Stump1eb44332009-09-09 15:08:12 +00001953bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001954 const TemplateArgumentLoc &AL,
Douglas Gregor910f8002010-11-07 23:05:16 +00001955 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001956 const TemplateArgument &Arg = AL.getArgument();
1957
Anders Carlsson436b1562009-06-13 00:33:33 +00001958 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001959 switch(Arg.getKind()) {
1960 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001961 // C++ [temp.arg.type]p1:
1962 // A template-argument for a template-parameter which is a
1963 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001964 break;
1965 case TemplateArgument::Template: {
1966 // We have a template type parameter but the template argument
1967 // is a template without any arguments.
1968 SourceRange SR = AL.getSourceRange();
1969 TemplateName Name = Arg.getAsTemplate();
1970 Diag(SR.getBegin(), diag::err_template_missing_args)
1971 << Name << SR;
1972 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1973 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001974
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001975 return true;
1976 }
1977 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001978 // We have a template type parameter but the template argument
1979 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001980 SourceRange SR = AL.getSourceRange();
1981 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001982 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Anders Carlsson436b1562009-06-13 00:33:33 +00001984 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001985 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001986 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001987
John McCalla93c9342009-12-07 02:54:59 +00001988 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001989 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Anders Carlsson436b1562009-06-13 00:33:33 +00001991 // Add the converted template type argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001992 Converted.push_back(
John McCall833ca992009-10-29 08:12:44 +00001993 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001994 return false;
1995}
1996
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001997/// \brief Substitute template arguments into the default template argument for
1998/// the given template type parameter.
1999///
2000/// \param SemaRef the semantic analysis object for which we are performing
2001/// the substitution.
2002///
2003/// \param Template the template that we are synthesizing template arguments
2004/// for.
2005///
2006/// \param TemplateLoc the location of the template name that started the
2007/// template-id we are checking.
2008///
2009/// \param RAngleLoc the location of the right angle bracket ('>') that
2010/// terminates the template-id.
2011///
2012/// \param Param the template template parameter whose default we are
2013/// substituting into.
2014///
2015/// \param Converted the list of template arguments provided for template
2016/// parameters that precede \p Param in the template parameter list.
2017///
2018/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00002019static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002020SubstDefaultTemplateArgument(Sema &SemaRef,
2021 TemplateDecl *Template,
2022 SourceLocation TemplateLoc,
2023 SourceLocation RAngleLoc,
2024 TemplateTypeParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002025 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00002026 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002027
2028 // If the argument type is dependent, instantiate it now based
2029 // on the previously-computed template arguments.
2030 if (ArgType->getType()->isDependentType()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002031 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2032 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002033
2034 MultiLevelTemplateArgumentList AllTemplateArgs
2035 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2036
2037 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002038 Template, Converted.data(),
2039 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002040 SourceRange(TemplateLoc, RAngleLoc));
2041
2042 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2043 Param->getDefaultArgumentLoc(),
2044 Param->getDeclName());
2045 }
2046
2047 return ArgType;
2048}
2049
2050/// \brief Substitute template arguments into the default template argument for
2051/// the given non-type template parameter.
2052///
2053/// \param SemaRef the semantic analysis object for which we are performing
2054/// the substitution.
2055///
2056/// \param Template the template that we are synthesizing template arguments
2057/// for.
2058///
2059/// \param TemplateLoc the location of the template name that started the
2060/// template-id we are checking.
2061///
2062/// \param RAngleLoc the location of the right angle bracket ('>') that
2063/// terminates the template-id.
2064///
Douglas Gregor788cd062009-11-11 01:00:40 +00002065/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002066/// substituting into.
2067///
2068/// \param Converted the list of template arguments provided for template
2069/// parameters that precede \p Param in the template parameter list.
2070///
2071/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00002072static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002073SubstDefaultTemplateArgument(Sema &SemaRef,
2074 TemplateDecl *Template,
2075 SourceLocation TemplateLoc,
2076 SourceLocation RAngleLoc,
2077 NonTypeTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002078 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2079 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2080 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002081
2082 MultiLevelTemplateArgumentList AllTemplateArgs
2083 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2084
2085 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002086 Template, Converted.data(),
2087 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002088 SourceRange(TemplateLoc, RAngleLoc));
2089
2090 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2091}
2092
Douglas Gregor788cd062009-11-11 01:00:40 +00002093/// \brief Substitute template arguments into the default template argument for
2094/// the given template template parameter.
2095///
2096/// \param SemaRef the semantic analysis object for which we are performing
2097/// the substitution.
2098///
2099/// \param Template the template that we are synthesizing template arguments
2100/// for.
2101///
2102/// \param TemplateLoc the location of the template name that started the
2103/// template-id we are checking.
2104///
2105/// \param RAngleLoc the location of the right angle bracket ('>') that
2106/// terminates the template-id.
2107///
2108/// \param Param the template template parameter whose default we are
2109/// substituting into.
2110///
2111/// \param Converted the list of template arguments provided for template
2112/// parameters that precede \p Param in the template parameter list.
2113///
2114/// \returns the substituted template argument, or NULL if an error occurred.
2115static TemplateName
2116SubstDefaultTemplateArgument(Sema &SemaRef,
2117 TemplateDecl *Template,
2118 SourceLocation TemplateLoc,
2119 SourceLocation RAngleLoc,
2120 TemplateTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002121 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2122 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2123 Converted.data(), Converted.size());
Douglas Gregor788cd062009-11-11 01:00:40 +00002124
2125 MultiLevelTemplateArgumentList AllTemplateArgs
2126 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2127
2128 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002129 Template, Converted.data(),
2130 Converted.size(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002131 SourceRange(TemplateLoc, RAngleLoc));
2132
2133 return SemaRef.SubstTemplateName(
2134 Param->getDefaultArgument().getArgument().getAsTemplate(),
2135 Param->getDefaultArgument().getTemplateNameLoc(),
2136 AllTemplateArgs);
2137}
2138
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002139/// \brief If the given template parameter has a default template
2140/// argument, substitute into that default template argument and
2141/// return the corresponding template argument.
2142TemplateArgumentLoc
2143Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2144 SourceLocation TemplateLoc,
2145 SourceLocation RAngleLoc,
2146 Decl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002147 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2148 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002149 if (!TypeParm->hasDefaultArgument())
2150 return TemplateArgumentLoc();
2151
John McCalla93c9342009-12-07 02:54:59 +00002152 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002153 TemplateLoc,
2154 RAngleLoc,
2155 TypeParm,
2156 Converted);
2157 if (DI)
2158 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2159
2160 return TemplateArgumentLoc();
2161 }
2162
2163 if (NonTypeTemplateParmDecl *NonTypeParm
2164 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2165 if (!NonTypeParm->hasDefaultArgument())
2166 return TemplateArgumentLoc();
2167
John McCall60d7b3a2010-08-24 06:29:42 +00002168 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002169 TemplateLoc,
2170 RAngleLoc,
2171 NonTypeParm,
2172 Converted);
2173 if (Arg.isInvalid())
2174 return TemplateArgumentLoc();
2175
2176 Expr *ArgE = Arg.takeAs<Expr>();
2177 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2178 }
2179
2180 TemplateTemplateParmDecl *TempTempParm
2181 = cast<TemplateTemplateParmDecl>(Param);
2182 if (!TempTempParm->hasDefaultArgument())
2183 return TemplateArgumentLoc();
2184
2185 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2186 TemplateLoc,
2187 RAngleLoc,
2188 TempTempParm,
2189 Converted);
2190 if (TName.isNull())
2191 return TemplateArgumentLoc();
2192
2193 return TemplateArgumentLoc(TemplateArgument(TName),
2194 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2195 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2196}
2197
Douglas Gregore7526412009-11-11 19:31:23 +00002198/// \brief Check that the given template argument corresponds to the given
2199/// template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002200///
2201/// \param Param The template parameter against which the argument will be
2202/// checked.
2203///
2204/// \param Arg The template argument.
2205///
2206/// \param Template The template in which the template argument resides.
2207///
2208/// \param TemplateLoc The location of the template name for the template
2209/// whose argument list we're matching.
2210///
2211/// \param RAngleLoc The location of the right angle bracket ('>') that closes
2212/// the template argument list.
2213///
2214/// \param ArgumentPackIndex The index into the argument pack where this
2215/// argument will be placed. Only valid if the parameter is a parameter pack.
2216///
2217/// \param Converted The checked, converted argument will be added to the
2218/// end of this small vector.
2219///
2220/// \param CTAK Describes how we arrived at this particular template argument:
2221/// explicitly written, deduced, etc.
2222///
2223/// \returns true on error, false otherwise.
Douglas Gregore7526412009-11-11 19:31:23 +00002224bool Sema::CheckTemplateArgument(NamedDecl *Param,
2225 const TemplateArgumentLoc &Arg,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002226 NamedDecl *Template,
Douglas Gregore7526412009-11-11 19:31:23 +00002227 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002228 SourceLocation RAngleLoc,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002229 unsigned ArgumentPackIndex,
Douglas Gregor910f8002010-11-07 23:05:16 +00002230 llvm::SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor02024a92010-03-28 02:42:43 +00002231 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002232 // Check template type parameters.
2233 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002234 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002235
Douglas Gregord9e15302009-11-11 19:41:09 +00002236 // Check non-type template parameters.
2237 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002238 // Do substitution on the type of the non-type template parameter
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002239 // with the template arguments we've seen thus far. But if the
2240 // template has a dependent context then we cannot substitute yet.
Douglas Gregore7526412009-11-11 19:31:23 +00002241 QualType NTTPType = NTTP->getType();
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002242 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
2243 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
2244
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002245 if (NTTPType->isDependentType() &&
2246 !isa<TemplateTemplateParmDecl>(Template) &&
2247 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002248 // Do substitution on the type of the non-type template parameter.
2249 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002250 NTTP, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002251 SourceRange(TemplateLoc, RAngleLoc));
2252
Douglas Gregor910f8002010-11-07 23:05:16 +00002253 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2254 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002255 NTTPType = SubstType(NTTPType,
2256 MultiLevelTemplateArgumentList(TemplateArgs),
2257 NTTP->getLocation(),
2258 NTTP->getDeclName());
2259 // If that worked, check the non-type template parameter type
2260 // for validity.
2261 if (!NTTPType.isNull())
2262 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2263 NTTP->getLocation());
2264 if (NTTPType.isNull())
2265 return true;
2266 }
2267
2268 switch (Arg.getArgument().getKind()) {
2269 case TemplateArgument::Null:
2270 assert(false && "Should never see a NULL template argument here");
2271 return true;
2272
2273 case TemplateArgument::Expression: {
2274 Expr *E = Arg.getArgument().getAsExpr();
2275 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002276 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002277 return true;
2278
Douglas Gregor910f8002010-11-07 23:05:16 +00002279 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002280 break;
2281 }
2282
2283 case TemplateArgument::Declaration:
2284 case TemplateArgument::Integral:
2285 // We've already checked this template argument, so just copy
2286 // it to the list of converted arguments.
Douglas Gregor910f8002010-11-07 23:05:16 +00002287 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002288 break;
2289
2290 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00002291 case TemplateArgument::TemplateExpansion:
Douglas Gregore7526412009-11-11 19:31:23 +00002292 // We were given a template template argument. It may not be ill-formed;
2293 // see below.
2294 if (DependentTemplateName *DTN
Douglas Gregora7fc9012011-01-05 18:58:31 +00002295 = Arg.getArgument().getAsTemplateOrTemplatePattern()
2296 .getAsDependentTemplateName()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002297 // We have a template argument such as \c T::template X, which we
2298 // parsed as a template template argument. However, since we now
2299 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002300 // template name into an expression.
2301
2302 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2303 Arg.getTemplateNameLoc());
2304
John McCallf7a1a742009-11-24 19:00:30 +00002305 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2306 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002307 Arg.getTemplateQualifierRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002308 NameInfo);
Douglas Gregore7526412009-11-11 19:31:23 +00002309
Douglas Gregora7fc9012011-01-05 18:58:31 +00002310 // If we parsed the template argument as a pack expansion, create a
2311 // pack expansion expression.
2312 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
2313 ExprResult Expansion = ActOnPackExpansion(E,
2314 Arg.getTemplateEllipsisLoc());
2315 if (Expansion.isInvalid())
2316 return true;
2317
2318 E = Expansion.get();
2319 }
2320
Douglas Gregore7526412009-11-11 19:31:23 +00002321 TemplateArgument Result;
2322 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2323 return true;
2324
Douglas Gregor910f8002010-11-07 23:05:16 +00002325 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002326 break;
2327 }
2328
2329 // We have a template argument that actually does refer to a class
2330 // template, template alias, or template template parameter, and
2331 // therefore cannot be a non-type template argument.
2332 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2333 << Arg.getSourceRange();
2334
2335 Diag(Param->getLocation(), diag::note_template_param_here);
2336 return true;
2337
2338 case TemplateArgument::Type: {
2339 // We have a non-type template parameter but the template
2340 // argument is a type.
2341
2342 // C++ [temp.arg]p2:
2343 // In a template-argument, an ambiguity between a type-id and
2344 // an expression is resolved to a type-id, regardless of the
2345 // form of the corresponding template-parameter.
2346 //
2347 // We warn specifically about this case, since it can be rather
2348 // confusing for users.
2349 QualType T = Arg.getArgument().getAsType();
2350 SourceRange SR = Arg.getSourceRange();
2351 if (T->isFunctionType())
2352 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2353 else
2354 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2355 Diag(Param->getLocation(), diag::note_template_param_here);
2356 return true;
2357 }
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
2367
2368 // Check template template parameters.
2369 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2370
2371 // Substitute into the template parameter list of the template
2372 // template parameter, since previously-supplied template arguments
2373 // may appear within the template template parameter.
2374 {
2375 // Set up a template instantiation context.
2376 LocalInstantiationScope Scope(*this);
2377 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002378 TempParm, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002379 SourceRange(TemplateLoc, RAngleLoc));
2380
Douglas Gregor910f8002010-11-07 23:05:16 +00002381 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2382 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002383 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2384 SubstDecl(TempParm, CurContext,
2385 MultiLevelTemplateArgumentList(TemplateArgs)));
2386 if (!TempParm)
2387 return true;
Douglas Gregore7526412009-11-11 19:31:23 +00002388 }
2389
2390 switch (Arg.getArgument().getKind()) {
2391 case TemplateArgument::Null:
2392 assert(false && "Should never see a NULL template argument here");
2393 return true;
2394
2395 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00002396 case TemplateArgument::TemplateExpansion:
Douglas Gregore7526412009-11-11 19:31:23 +00002397 if (CheckTemplateArgument(TempParm, Arg))
2398 return true;
2399
Douglas Gregor910f8002010-11-07 23:05:16 +00002400 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002401 break;
2402
2403 case TemplateArgument::Expression:
2404 case TemplateArgument::Type:
2405 // We have a template template parameter but the template
2406 // argument does not refer to a template.
2407 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2408 return true;
2409
2410 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002411 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002412 "Declaration argument with template template parameter");
2413 break;
2414 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002415 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002416 "Integral argument with template template parameter");
2417 break;
2418
2419 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002420 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002421 break;
2422 }
2423
2424 return false;
2425}
2426
Douglas Gregorc15cb382009-02-09 23:23:08 +00002427/// \brief Check that the given template argument list is well-formed
2428/// for specializing the given template.
2429bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2430 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002431 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002432 bool PartialTemplateArgs,
Douglas Gregor910f8002010-11-07 23:05:16 +00002433 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002434 TemplateParameterList *Params = Template->getTemplateParameters();
2435 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002436 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002437 bool Invalid = false;
2438
John McCalld5532b62009-11-23 01:53:49 +00002439 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2440
Mike Stump1eb44332009-09-09 15:08:12 +00002441 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002442 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002443
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002444 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002445 (NumArgs < Params->getMinRequiredArguments() &&
2446 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002447 // FIXME: point at either the first arg beyond what we can handle,
2448 // or the '>', depending on whether we have too many or too few
2449 // arguments.
2450 SourceRange Range;
2451 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002452 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002453 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2454 << (NumArgs > NumParams)
2455 << (isa<ClassTemplateDecl>(Template)? 0 :
2456 isa<FunctionTemplateDecl>(Template)? 1 :
2457 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2458 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002459 Diag(Template->getLocation(), diag::note_template_decl_here)
2460 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002461 Invalid = true;
2462 }
Mike Stump1eb44332009-09-09 15:08:12 +00002463
2464 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002465 // [...] The type and form of each template-argument specified in
2466 // a template-id shall match the type and form specified for the
2467 // corresponding parameter declared by the template in its
2468 // template-parameter-list.
Douglas Gregor14be16b2010-12-20 16:57:52 +00002469 llvm::SmallVector<TemplateArgument, 2> ArgumentPack;
2470 TemplateParameterList::iterator Param = Params->begin(),
2471 ParamEnd = Params->end();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002472 unsigned ArgIdx = 0;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002473 while (Param != ParamEnd) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002474 if (ArgIdx > NumArgs && PartialTemplateArgs)
2475 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002476
Douglas Gregorf35f8282009-11-11 21:54:23 +00002477 if (ArgIdx < NumArgs) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002478 // If we have an expanded parameter pack, make sure we don't have too
2479 // many arguments.
2480 if (NonTypeTemplateParmDecl *NTTP
2481 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2482 if (NTTP->isExpandedParameterPack() &&
2483 ArgumentPack.size() >= NTTP->getNumExpansionTypes()) {
2484 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2485 << true
2486 << (isa<ClassTemplateDecl>(Template)? 0 :
2487 isa<FunctionTemplateDecl>(Template)? 1 :
2488 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2489 << Template;
2490 Diag(Template->getLocation(), diag::note_template_decl_here)
2491 << Params->getSourceRange();
2492 return true;
2493 }
2494 }
2495
Douglas Gregorf35f8282009-11-11 21:54:23 +00002496 // Check the template argument we were given.
2497 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002498 TemplateLoc, RAngleLoc,
2499 ArgumentPack.size(), Converted))
Douglas Gregorf35f8282009-11-11 21:54:23 +00002500 return true;
2501
Douglas Gregor14be16b2010-12-20 16:57:52 +00002502 if ((*Param)->isTemplateParameterPack()) {
2503 // The template parameter was a template parameter pack, so take the
2504 // deduced argument and place it on the argument pack. Note that we
2505 // stay on the same template parameter so that we can deduce more
2506 // arguments.
2507 ArgumentPack.push_back(Converted.back());
2508 Converted.pop_back();
2509 } else {
2510 // Move to the next template parameter.
2511 ++Param;
2512 }
2513 ++ArgIdx;
Douglas Gregorf35f8282009-11-11 21:54:23 +00002514 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002515 }
Douglas Gregore7526412009-11-11 19:31:23 +00002516
Douglas Gregor14be16b2010-12-20 16:57:52 +00002517 // If we have a template parameter pack with no more corresponding
2518 // arguments, just break out now and we'll fill in the argument pack below.
2519 if ((*Param)->isTemplateParameterPack())
2520 break;
2521
Douglas Gregorf35f8282009-11-11 21:54:23 +00002522 // We have a default template argument that we will use.
2523 TemplateArgumentLoc Arg;
2524
2525 // Retrieve the default template argument from the template
2526 // parameter. For each kind of template parameter, we substitute the
2527 // template arguments provided thus far and any "outer" template arguments
2528 // (when the template parameter was part of a nested template) into
2529 // the default argument.
2530 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2531 if (!TTP->hasDefaultArgument()) {
2532 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2533 break;
2534 }
2535
John McCalla93c9342009-12-07 02:54:59 +00002536 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002537 Template,
2538 TemplateLoc,
2539 RAngleLoc,
2540 TTP,
2541 Converted);
2542 if (!ArgType)
2543 return true;
2544
2545 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2546 ArgType);
2547 } else if (NonTypeTemplateParmDecl *NTTP
2548 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2549 if (!NTTP->hasDefaultArgument()) {
2550 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2551 break;
2552 }
2553
John McCall60d7b3a2010-08-24 06:29:42 +00002554 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002555 TemplateLoc,
2556 RAngleLoc,
2557 NTTP,
2558 Converted);
2559 if (E.isInvalid())
2560 return true;
2561
2562 Expr *Ex = E.takeAs<Expr>();
2563 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2564 } else {
2565 TemplateTemplateParmDecl *TempParm
2566 = cast<TemplateTemplateParmDecl>(*Param);
2567
2568 if (!TempParm->hasDefaultArgument()) {
2569 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2570 break;
2571 }
2572
2573 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2574 TemplateLoc,
2575 RAngleLoc,
2576 TempParm,
2577 Converted);
2578 if (Name.isNull())
2579 return true;
2580
2581 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2582 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2583 TempParm->getDefaultArgument().getTemplateNameLoc());
2584 }
2585
2586 // Introduce an instantiation record that describes where we are using
2587 // the default template argument.
2588 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002589 Converted.data(), Converted.size(),
Douglas Gregorf35f8282009-11-11 21:54:23 +00002590 SourceRange(TemplateLoc, RAngleLoc));
2591
2592 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002593 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002594 RAngleLoc, 0, Converted))
Douglas Gregore7526412009-11-11 19:31:23 +00002595 return true;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002596
2597 // Move to the next template parameter and argument.
2598 ++Param;
2599 ++ArgIdx;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002600 }
Douglas Gregor14be16b2010-12-20 16:57:52 +00002601
2602 // Form argument packs for each of the parameter packs remaining.
2603 while (Param != ParamEnd) {
Douglas Gregord3731192011-01-10 07:32:04 +00002604 // If we're checking a partial list of template arguments, don't fill
2605 // in arguments for non-template parameter packs.
2606
Douglas Gregor14be16b2010-12-20 16:57:52 +00002607 if ((*Param)->isTemplateParameterPack()) {
Douglas Gregord3731192011-01-10 07:32:04 +00002608 if (PartialTemplateArgs && ArgumentPack.empty()) {
2609 Converted.push_back(TemplateArgument());
Douglas Gregor203e6a32011-01-11 23:09:57 +00002610 } else if (ArgumentPack.empty())
Douglas Gregor14be16b2010-12-20 16:57:52 +00002611 Converted.push_back(TemplateArgument(0, 0));
Douglas Gregor203e6a32011-01-11 23:09:57 +00002612 else {
2613 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
2614 ArgumentPack.data(),
2615 ArgumentPack.size()));
Douglas Gregor14be16b2010-12-20 16:57:52 +00002616 ArgumentPack.clear();
2617 }
2618 }
2619
2620 ++Param;
2621 }
2622
Douglas Gregorc15cb382009-02-09 23:23:08 +00002623 return Invalid;
2624}
2625
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002626namespace {
2627 class UnnamedLocalNoLinkageFinder
2628 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2629 {
2630 Sema &S;
2631 SourceRange SR;
2632
2633 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2634
2635 public:
2636 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2637
2638 bool Visit(QualType T) {
2639 return inherited::Visit(T.getTypePtr());
2640 }
2641
2642#define TYPE(Class, Parent) \
2643 bool Visit##Class##Type(const Class##Type *);
2644#define ABSTRACT_TYPE(Class, Parent) \
2645 bool Visit##Class##Type(const Class##Type *) { return false; }
2646#define NON_CANONICAL_TYPE(Class, Parent) \
2647 bool Visit##Class##Type(const Class##Type *) { return false; }
2648#include "clang/AST/TypeNodes.def"
2649
2650 bool VisitTagDecl(const TagDecl *Tag);
2651 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2652 };
2653}
2654
2655bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2656 return false;
2657}
2658
2659bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2660 return Visit(T->getElementType());
2661}
2662
2663bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2664 return Visit(T->getPointeeType());
2665}
2666
2667bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2668 const BlockPointerType* T) {
2669 return Visit(T->getPointeeType());
2670}
2671
2672bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2673 const LValueReferenceType* T) {
2674 return Visit(T->getPointeeType());
2675}
2676
2677bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2678 const RValueReferenceType* T) {
2679 return Visit(T->getPointeeType());
2680}
2681
2682bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2683 const MemberPointerType* T) {
2684 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2685}
2686
2687bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2688 const ConstantArrayType* T) {
2689 return Visit(T->getElementType());
2690}
2691
2692bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2693 const IncompleteArrayType* T) {
2694 return Visit(T->getElementType());
2695}
2696
2697bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2698 const VariableArrayType* T) {
2699 return Visit(T->getElementType());
2700}
2701
2702bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2703 const DependentSizedArrayType* T) {
2704 return Visit(T->getElementType());
2705}
2706
2707bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2708 const DependentSizedExtVectorType* T) {
2709 return Visit(T->getElementType());
2710}
2711
2712bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2713 return Visit(T->getElementType());
2714}
2715
2716bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2717 return Visit(T->getElementType());
2718}
2719
2720bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2721 const FunctionProtoType* T) {
2722 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2723 AEnd = T->arg_type_end();
2724 A != AEnd; ++A) {
2725 if (Visit(*A))
2726 return true;
2727 }
2728
2729 return Visit(T->getResultType());
2730}
2731
2732bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2733 const FunctionNoProtoType* T) {
2734 return Visit(T->getResultType());
2735}
2736
2737bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2738 const UnresolvedUsingType*) {
2739 return false;
2740}
2741
2742bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2743 return false;
2744}
2745
2746bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2747 return Visit(T->getUnderlyingType());
2748}
2749
2750bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2751 return false;
2752}
2753
2754bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2755 return VisitTagDecl(T->getDecl());
2756}
2757
2758bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2759 return VisitTagDecl(T->getDecl());
2760}
2761
2762bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2763 const TemplateTypeParmType*) {
2764 return false;
2765}
2766
Douglas Gregorc3069d62011-01-14 02:55:32 +00002767bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
2768 const SubstTemplateTypeParmPackType *) {
2769 return false;
2770}
2771
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002772bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2773 const TemplateSpecializationType*) {
2774 return false;
2775}
2776
2777bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2778 const InjectedClassNameType* T) {
2779 return VisitTagDecl(T->getDecl());
2780}
2781
2782bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2783 const DependentNameType* T) {
2784 return VisitNestedNameSpecifier(T->getQualifier());
2785}
2786
2787bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2788 const DependentTemplateSpecializationType* T) {
2789 return VisitNestedNameSpecifier(T->getQualifier());
2790}
2791
Douglas Gregor7536dd52010-12-20 02:24:11 +00002792bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
2793 const PackExpansionType* T) {
2794 return Visit(T->getPattern());
2795}
2796
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002797bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2798 return false;
2799}
2800
2801bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2802 const ObjCInterfaceType *) {
2803 return false;
2804}
2805
2806bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2807 const ObjCObjectPointerType *) {
2808 return false;
2809}
2810
2811bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2812 if (Tag->getDeclContext()->isFunctionOrMethod()) {
2813 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2814 << S.Context.getTypeDeclType(Tag) << SR;
2815 return true;
2816 }
2817
2818 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2819 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2820 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2821 return true;
2822 }
2823
2824 return false;
2825}
2826
2827bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2828 NestedNameSpecifier *NNS) {
2829 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2830 return true;
2831
2832 switch (NNS->getKind()) {
2833 case NestedNameSpecifier::Identifier:
2834 case NestedNameSpecifier::Namespace:
2835 case NestedNameSpecifier::Global:
2836 return false;
2837
2838 case NestedNameSpecifier::TypeSpec:
2839 case NestedNameSpecifier::TypeSpecWithTemplate:
2840 return Visit(QualType(NNS->getAsType(), 0));
2841 }
Fariborz Jahanian7b1ec6c2010-10-13 16:19:16 +00002842 return false;
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002843}
2844
2845
Douglas Gregorc15cb382009-02-09 23:23:08 +00002846/// \brief Check a template argument against its corresponding
2847/// template type parameter.
2848///
2849/// This routine implements the semantics of C++ [temp.arg.type]. It
2850/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002851bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002852 TypeSourceInfo *ArgInfo) {
2853 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002854 QualType Arg = ArgInfo->getType();
Douglas Gregor0fddb972010-05-22 16:17:30 +00002855 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth17fb8552010-09-03 21:12:34 +00002856
2857 if (Arg->isVariablyModifiedType()) {
2858 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002859 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00002860 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002861 }
2862
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002863 // C++03 [temp.arg.type]p2:
2864 // A local type, a type with no linkage, an unnamed type or a type
2865 // compounded from any of these types shall not be used as a
2866 // template-argument for a template type-parameter.
2867 //
2868 // C++0x allows these, and even in C++03 we allow them as an extension with
2869 // a warning.
Douglas Gregordb4d4bb2010-10-13 18:05:20 +00002870 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002871 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2872 (void)Finder.Visit(Context.getCanonicalType(Arg));
2873 }
2874
Douglas Gregorc15cb382009-02-09 23:23:08 +00002875 return false;
2876}
2877
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002878/// \brief Checks whether the given template argument is the address
2879/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002880static bool
2881CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2882 NonTypeTemplateParmDecl *Param,
2883 QualType ParamType,
2884 Expr *ArgIn,
2885 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002886 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002887 Expr *Arg = ArgIn;
2888 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002889
2890 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002891 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002892 Arg = Cast->getSubExpr();
2893
2894 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002895 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002896 // A template-argument for a non-type, non-template
2897 // template-parameter shall be one of: [...]
2898 //
2899 // -- the address of an object or function with external
2900 // linkage, including function templates and function
2901 // template-ids but excluding non-static class members,
2902 // expressed as & id-expression where the & is optional if
2903 // the name refers to a function or array, or if the
2904 // corresponding template-parameter is a reference; or
2905 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002906
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002907 // In C++98/03 mode, give an extension warning on any extra parentheses.
2908 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2909 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002910 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002911 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002912 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002913 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002914 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002915 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002916 }
2917
2918 Arg = Parens->getSubExpr();
2919 }
2920
Douglas Gregorb7a09262010-04-01 18:32:35 +00002921 bool AddressTaken = false;
2922 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002923 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002924 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002925 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002926 AddressTaken = true;
2927 AddrOpLoc = UnOp->getOperatorLoc();
2928 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002929 } else
2930 DRE = dyn_cast<DeclRefExpr>(Arg);
2931
Douglas Gregorb7a09262010-04-01 18:32:35 +00002932 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002933 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2934 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002935 S.Diag(Param->getLocation(), diag::note_template_param_here);
2936 return true;
2937 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002938
2939 // Stop checking the precise nature of the argument if it is value dependent,
2940 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002941 if (Arg->isValueDependent()) {
John McCall3fa5cae2010-10-26 07:05:15 +00002942 Converted = TemplateArgument(ArgIn);
Chandler Carruth038cc392010-01-31 10:01:20 +00002943 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002944 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002945
Douglas Gregorb7a09262010-04-01 18:32:35 +00002946 if (!isa<ValueDecl>(DRE->getDecl())) {
2947 S.Diag(Arg->getSourceRange().getBegin(),
2948 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002949 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002950 S.Diag(Param->getLocation(), diag::note_template_param_here);
2951 return true;
2952 }
2953
2954 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002955
2956 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002957 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2958 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002959 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002960 S.Diag(Param->getLocation(), diag::note_template_param_here);
2961 return true;
2962 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002963
2964 // Cannot refer to non-static member functions
2965 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002966 if (!Method->isStatic()) {
2967 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002968 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002969 S.Diag(Param->getLocation(), diag::note_template_param_here);
2970 return true;
2971 }
Mike Stump1eb44332009-09-09 15:08:12 +00002972
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002973 // Functions must have external linkage.
2974 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002975 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002976 S.Diag(Arg->getSourceRange().getBegin(),
2977 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002978 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002979 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002980 << true;
2981 return true;
2982 }
2983
2984 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002985 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002986
Douglas Gregorb7a09262010-04-01 18:32:35 +00002987 // If the template parameter has pointer type, the function decays.
2988 if (ParamType->isPointerType() && !AddressTaken)
2989 ArgType = S.Context.getPointerType(Func->getType());
2990 else if (AddressTaken && ParamType->isReferenceType()) {
2991 // If we originally had an address-of operator, but the
2992 // parameter has reference type, complain and (if things look
2993 // like they will work) drop the address-of operator.
2994 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2995 ParamType.getNonReferenceType())) {
2996 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2997 << ParamType;
2998 S.Diag(Param->getLocation(), diag::note_template_param_here);
2999 return true;
3000 }
3001
3002 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3003 << ParamType
3004 << FixItHint::CreateRemoval(AddrOpLoc);
3005 S.Diag(Param->getLocation(), diag::note_template_param_here);
3006
3007 ArgType = Func->getType();
3008 }
3009 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00003010 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003011 S.Diag(Arg->getSourceRange().getBegin(),
3012 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003013 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003014 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003015 << true;
3016 return true;
3017 }
3018
Douglas Gregorb7a09262010-04-01 18:32:35 +00003019 // A value of reference type is not an object.
3020 if (Var->getType()->isReferenceType()) {
3021 S.Diag(Arg->getSourceRange().getBegin(),
3022 diag::err_template_arg_reference_var)
3023 << Var->getType() << Arg->getSourceRange();
3024 S.Diag(Param->getLocation(), diag::note_template_param_here);
3025 return true;
3026 }
3027
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003028 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003029 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00003030
3031 // If the template parameter has pointer type, we must have taken
3032 // the address of this object.
3033 if (ParamType->isReferenceType()) {
3034 if (AddressTaken) {
3035 // If we originally had an address-of operator, but the
3036 // parameter has reference type, complain and (if things look
3037 // like they will work) drop the address-of operator.
3038 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
3039 ParamType.getNonReferenceType())) {
3040 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3041 << ParamType;
3042 S.Diag(Param->getLocation(), diag::note_template_param_here);
3043 return true;
3044 }
3045
3046 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3047 << ParamType
3048 << FixItHint::CreateRemoval(AddrOpLoc);
3049 S.Diag(Param->getLocation(), diag::note_template_param_here);
3050
3051 ArgType = Var->getType();
3052 }
3053 } else if (!AddressTaken && ParamType->isPointerType()) {
3054 if (Var->getType()->isArrayType()) {
3055 // Array-to-pointer decay.
3056 ArgType = S.Context.getArrayDecayedType(Var->getType());
3057 } else {
3058 // If the template parameter has pointer type but the address of
3059 // this object was not taken, complain and (possibly) recover by
3060 // taking the address of the entity.
3061 ArgType = S.Context.getPointerType(Var->getType());
3062 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
3063 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3064 << ParamType;
3065 S.Diag(Param->getLocation(), diag::note_template_param_here);
3066 return true;
3067 }
3068
3069 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3070 << ParamType
3071 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
3072
3073 S.Diag(Param->getLocation(), diag::note_template_param_here);
3074 }
3075 }
3076 } else {
3077 // We found something else, but we don't know specifically what it is.
3078 S.Diag(Arg->getSourceRange().getBegin(),
3079 diag::err_template_arg_not_object_or_func)
3080 << Arg->getSourceRange();
3081 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
3082 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003083 }
Mike Stump1eb44332009-09-09 15:08:12 +00003084
Douglas Gregorb7a09262010-04-01 18:32:35 +00003085 if (ParamType->isPointerType() &&
3086 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
3087 S.IsQualificationConversion(ArgType, ParamType)) {
3088 // For pointer-to-object types, qualification conversions are
3089 // permitted.
3090 } else {
3091 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
3092 if (!ParamRef->getPointeeType()->isFunctionType()) {
3093 // C++ [temp.arg.nontype]p5b3:
3094 // For a non-type template-parameter of type reference to
3095 // object, no conversions apply. The type referred to by the
3096 // reference may be more cv-qualified than the (otherwise
3097 // identical) type of the template- argument. The
3098 // template-parameter is bound directly to the
3099 // template-argument, which shall be an lvalue.
3100
3101 // FIXME: Other qualifiers?
3102 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
3103 unsigned ArgQuals = ArgType.getCVRQualifiers();
3104
3105 if ((ParamQuals | ArgQuals) != ParamQuals) {
3106 S.Diag(Arg->getSourceRange().getBegin(),
3107 diag::err_template_arg_ref_bind_ignores_quals)
3108 << ParamType << Arg->getType()
3109 << Arg->getSourceRange();
3110 S.Diag(Param->getLocation(), diag::note_template_param_here);
3111 return true;
3112 }
3113 }
3114 }
3115
3116 // At this point, the template argument refers to an object or
3117 // function with external linkage. We now need to check whether the
3118 // argument and parameter types are compatible.
3119 if (!S.Context.hasSameUnqualifiedType(ArgType,
3120 ParamType.getNonReferenceType())) {
3121 // We can't perform this conversion or binding.
3122 if (ParamType->isReferenceType())
3123 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
3124 << ParamType << Arg->getType() << Arg->getSourceRange();
3125 else
3126 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
3127 << Arg->getType() << ParamType << Arg->getSourceRange();
3128 S.Diag(Param->getLocation(), diag::note_template_param_here);
3129 return true;
3130 }
3131 }
3132
3133 // Create the template argument.
3134 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00003135 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00003136 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003137}
3138
3139/// \brief Checks whether the given template argument is a pointer to
3140/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003141bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
3142 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003143 bool Invalid = false;
3144
3145 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003146 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003147 Arg = Cast->getSubExpr();
3148
3149 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003150 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003151 // A template-argument for a non-type, non-template
3152 // template-parameter shall be one of: [...]
3153 //
3154 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003155 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003156
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003157 // In C++98/03 mode, give an extension warning on any extra parentheses.
3158 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3159 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003160 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003161 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00003162 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003163 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003164 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003165 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003166 }
3167
3168 Arg = Parens->getSubExpr();
3169 }
3170
Douglas Gregorcaddba02009-11-12 18:38:13 +00003171 // A pointer-to-member constant written &Class::member.
3172 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00003173 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00003174 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3175 if (DRE && !DRE->getQualifier())
3176 DRE = 0;
3177 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00003178 }
3179 // A constant of pointer-to-member type.
3180 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
3181 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
3182 if (VD->getType()->isMemberPointerType()) {
3183 if (isa<NonTypeTemplateParmDecl>(VD) ||
3184 (isa<VarDecl>(VD) &&
3185 Context.getCanonicalType(VD->getType()).isConstQualified())) {
3186 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003187 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003188 else
3189 Converted = TemplateArgument(VD->getCanonicalDecl());
3190 return Invalid;
3191 }
3192 }
3193 }
3194
3195 DRE = 0;
3196 }
3197
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003198 if (!DRE)
3199 return Diag(Arg->getSourceRange().getBegin(),
3200 diag::err_template_arg_not_pointer_to_member_form)
3201 << Arg->getSourceRange();
3202
3203 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3204 assert((isa<FieldDecl>(DRE->getDecl()) ||
3205 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3206 "Only non-static member pointers can make it here");
3207
3208 // Okay: this is the address of a non-static member, and therefore
3209 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003210 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003211 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003212 else
3213 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003214 return Invalid;
3215 }
3216
3217 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00003218 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003219 diag::err_template_arg_not_pointer_to_member_form)
3220 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003221 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003222 diag::note_template_arg_refers_here);
3223 return true;
3224}
3225
Douglas Gregorc15cb382009-02-09 23:23:08 +00003226/// \brief Check a template argument against its corresponding
3227/// non-type template parameter.
3228///
Douglas Gregor2943aed2009-03-03 04:44:36 +00003229/// This routine implements the semantics of C++ [temp.arg.nontype].
3230/// It returns true if an error occurred, and false otherwise. \p
3231/// InstantiatedParamType is the type of the non-type template
3232/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003233///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003234/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00003235bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00003236 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00003237 TemplateArgument &Converted,
3238 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00003239 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3240
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003241 // If either the parameter has a dependent type or the argument is
3242 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00003243 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3244 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003245 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003246 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00003247 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003248
3249 // C++ [temp.arg.nontype]p5:
3250 // The following conversions are performed on each expression used
3251 // as a non-type template-argument. If a non-type
3252 // template-argument cannot be converted to the type of the
3253 // corresponding template-parameter then the program is
3254 // ill-formed.
3255 //
3256 // -- for a non-type template-parameter of integral or
3257 // enumeration type, integral promotions (4.5) and integral
3258 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00003259 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00003260 QualType ArgType = Arg->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003261 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003262 // C++ [temp.arg.nontype]p1:
3263 // A template-argument for a non-type, non-template
3264 // template-parameter shall be one of:
3265 //
3266 // -- an integral constant-expression of integral or enumeration
3267 // type; or
3268 // -- the name of a non-type template-parameter; or
3269 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003270 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003271 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003272 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003273 diag::err_template_arg_not_integral_or_enumeral)
3274 << ArgType << Arg->getSourceRange();
3275 Diag(Param->getLocation(), diag::note_template_param_here);
3276 return true;
3277 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003278 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003279 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3280 << ArgType << Arg->getSourceRange();
3281 return true;
3282 }
3283
Douglas Gregor02024a92010-03-28 02:42:43 +00003284 // From here on out, all we care about are the unqualified forms
3285 // of the parameter and argument types.
3286 ParamType = ParamType.getUnqualifiedType();
3287 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003288
3289 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00003290 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003291 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00003292 } else if (CTAK == CTAK_Deduced) {
3293 // C++ [temp.deduct.type]p17:
3294 // If, in the declaration of a function template with a non-type
3295 // template-parameter, the non-type template- parameter is used
3296 // in an expression in the function parameter-list and, if the
3297 // corresponding template-argument is deduced, the
3298 // template-argument type shall match the type of the
3299 // template-parameter exactly, except that a template-argument
3300 // deduced from an array bound may be of any integral type.
3301 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3302 << ArgType << ParamType;
3303 Diag(Param->getLocation(), diag::note_template_param_here);
John McCalldaa8e4e2010-11-15 09:13:47 +00003304 return true;
3305 } else if (ParamType->isBooleanType()) {
3306 // This is an integral-to-boolean conversion.
3307 ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003308 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3309 !ParamType->isEnumeralType()) {
3310 // This is an integral promotion or conversion.
John McCall2de56d12010-08-25 11:45:40 +00003311 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003312 } else {
3313 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003314 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003315 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003316 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003317 Diag(Param->getLocation(), diag::note_template_param_here);
3318 return true;
3319 }
3320
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003321 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00003322 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003323 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003324
3325 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003326 llvm::APSInt OldValue = Value;
3327
3328 // Coerce the template argument's value to the value it will have
3329 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003330 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003331 if (Value.getBitWidth() != AllowedBits)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003332 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003333 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003334
3335 // Complain if an unsigned parameter received a negative value.
3336 if (IntegerType->isUnsignedIntegerType()
3337 && (OldValue.isSigned() && OldValue.isNegative())) {
3338 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3339 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3340 << Arg->getSourceRange();
3341 Diag(Param->getLocation(), diag::note_template_param_here);
3342 }
3343
3344 // Complain if we overflowed the template parameter's type.
3345 unsigned RequiredBits;
3346 if (IntegerType->isUnsignedIntegerType())
3347 RequiredBits = OldValue.getActiveBits();
3348 else if (OldValue.isUnsigned())
3349 RequiredBits = OldValue.getActiveBits() + 1;
3350 else
3351 RequiredBits = OldValue.getMinSignedBits();
3352 if (RequiredBits > AllowedBits) {
3353 Diag(Arg->getSourceRange().getBegin(),
3354 diag::warn_template_arg_too_large)
3355 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3356 << Arg->getSourceRange();
3357 Diag(Param->getLocation(), diag::note_template_param_here);
3358 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003359 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003360
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003361 // Add the value of this argument to the list of converted
3362 // arguments. We use the bitwidth and signedness of the template
3363 // parameter.
3364 if (Arg->isValueDependent()) {
3365 // The argument is value-dependent. Create a new
3366 // TemplateArgument with the converted expression.
3367 Converted = TemplateArgument(Arg);
3368 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003369 }
3370
John McCall833ca992009-10-29 08:12:44 +00003371 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00003372 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003373 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003374 return false;
3375 }
Douglas Gregora35284b2009-02-11 00:19:33 +00003376
John McCall6bb80172010-03-30 21:47:33 +00003377 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3378
Douglas Gregorb7a09262010-04-01 18:32:35 +00003379 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3380 // from a template argument of type std::nullptr_t to a non-type
3381 // template parameter of type pointer to object, pointer to
3382 // function, or pointer-to-member, respectively.
3383 if (ArgType->isNullPtrType() &&
3384 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3385 Converted = TemplateArgument((NamedDecl *)0);
3386 return false;
3387 }
3388
Douglas Gregorb86b0572009-02-11 01:18:59 +00003389 // Handle pointer-to-function, reference-to-function, and
3390 // pointer-to-member-function all in (roughly) the same way.
3391 if (// -- For a non-type template-parameter of type pointer to
3392 // function, only the function-to-pointer conversion (4.3) is
3393 // applied. If the template-argument represents a set of
3394 // overloaded functions (or a pointer to such), the matching
3395 // function is selected from the set (13.4).
3396 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003397 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003398 // -- For a non-type template-parameter of type reference to
3399 // function, no conversions apply. If the template-argument
3400 // represents a set of overloaded functions, the matching
3401 // function is selected from the set (13.4).
3402 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003403 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003404 // -- For a non-type template-parameter of type pointer to
3405 // member function, no conversions apply. If the
3406 // template-argument represents a set of overloaded member
3407 // functions, the matching member function is selected from
3408 // the set (13.4).
3409 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003410 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00003411 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003412
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003413 if (Arg->getType() == Context.OverloadTy) {
3414 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3415 true,
3416 FoundResult)) {
3417 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3418 return true;
3419
3420 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3421 ArgType = Arg->getType();
3422 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003423 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00003424 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003425
Douglas Gregorb7a09262010-04-01 18:32:35 +00003426 if (!ParamType->isMemberPointerType())
3427 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3428 ParamType,
3429 Arg, Converted);
3430
3431 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCall2de56d12010-08-25 11:45:40 +00003432 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb7a09262010-04-01 18:32:35 +00003433 } else if (!Context.hasSameUnqualifiedType(ArgType,
3434 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00003435 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003436 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00003437 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003438 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00003439 Diag(Param->getLocation(), diag::note_template_param_here);
3440 return true;
3441 }
Mike Stump1eb44332009-09-09 15:08:12 +00003442
Douglas Gregorb7a09262010-04-01 18:32:35 +00003443 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00003444 }
3445
Chris Lattnerfe90de72009-02-20 21:37:53 +00003446 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003447 // -- for a non-type template-parameter of type pointer to
3448 // object, qualification conversions (4.4) and the
3449 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00003450 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00003451 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003452 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003453
Douglas Gregorb7a09262010-04-01 18:32:35 +00003454 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3455 ParamType,
3456 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003457 }
Mike Stump1eb44332009-09-09 15:08:12 +00003458
Ted Kremenek6217b802009-07-29 21:53:49 +00003459 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003460 // -- For a non-type template-parameter of type reference to
3461 // object, no conversions apply. The type referred to by the
3462 // reference may be more cv-qualified than the (otherwise
3463 // identical) type of the template-argument. The
3464 // template-parameter is bound directly to the
3465 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00003466 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003467 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003468
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003469 if (Arg->getType() == Context.OverloadTy) {
3470 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3471 ParamRefType->getPointeeType(),
3472 true,
3473 FoundResult)) {
3474 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3475 return true;
3476
3477 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3478 ArgType = Arg->getType();
3479 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00003480 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00003481 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003482
Douglas Gregorb7a09262010-04-01 18:32:35 +00003483 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3484 ParamType,
3485 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00003486 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00003487
3488 // -- For a non-type template-parameter of type pointer to data
3489 // member, qualification conversions (4.4) are applied.
3490 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3491
Douglas Gregor8e6563b2009-02-11 18:22:40 +00003492 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00003493 // Types match exactly: nothing more to do here.
3494 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCall2de56d12010-08-25 11:45:40 +00003495 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor658bbb52009-02-11 16:16:59 +00003496 } else {
3497 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003498 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00003499 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003500 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00003501 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00003502 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00003503 }
3504
Douglas Gregorcaddba02009-11-12 18:38:13 +00003505 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00003506}
3507
3508/// \brief Check a template argument against its corresponding
3509/// template template parameter.
3510///
3511/// This routine implements the semantics of C++ [temp.arg.template].
3512/// It returns true if an error occurred, and false otherwise.
3513bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003514 const TemplateArgumentLoc &Arg) {
3515 TemplateName Name = Arg.getArgument().getAsTemplate();
3516 TemplateDecl *Template = Name.getAsTemplateDecl();
3517 if (!Template) {
3518 // Any dependent template name is fine.
3519 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3520 return false;
3521 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003522
3523 // C++ [temp.arg.template]p1:
3524 // A template-argument for a template template-parameter shall be
3525 // the name of a class template, expressed as id-expression. Only
3526 // primary class templates are considered when matching the
3527 // template template argument with the corresponding parameter;
3528 // partial specializations are not considered even if their
3529 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003530 //
3531 // Note that we also allow template template parameters here, which
3532 // will happen when we are dealing with, e.g., class template
3533 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003534 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003535 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003536 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003537 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003538 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003539 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003540 << Template;
3541 }
3542
3543 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3544 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003545 true,
3546 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003547 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003548}
3549
Douglas Gregor02024a92010-03-28 02:42:43 +00003550/// \brief Given a non-type template argument that refers to a
3551/// declaration and the type of its corresponding non-type template
3552/// parameter, produce an expression that properly refers to that
3553/// declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00003554ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003555Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3556 QualType ParamType,
3557 SourceLocation Loc) {
3558 assert(Arg.getKind() == TemplateArgument::Declaration &&
3559 "Only declaration template arguments permitted here");
3560 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3561
3562 if (VD->getDeclContext()->isRecord() &&
3563 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3564 // If the value is a class member, we might have a pointer-to-member.
3565 // Determine whether the non-type template template parameter is of
3566 // pointer-to-member type. If so, we need to build an appropriate
3567 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3568 // would refer to the member itself.
3569 if (ParamType->isMemberPointerType()) {
3570 QualType ClassType
3571 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3572 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00003573 = NestedNameSpecifier::Create(Context, 0, false,
3574 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00003575 CXXScopeSpec SS;
3576 SS.setScopeRep(Qualifier);
John McCalldfa1edb2010-11-23 20:48:44 +00003577
3578 // The actual value-ness of this is unimportant, but for
3579 // internal consistency's sake, references to instance methods
3580 // are r-values.
3581 ExprValueKind VK = VK_LValue;
3582 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
3583 VK = VK_RValue;
3584
John McCall60d7b3a2010-08-24 06:29:42 +00003585 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCallf89e55a2010-11-18 06:31:45 +00003586 VD->getType().getNonReferenceType(),
John McCalldfa1edb2010-11-23 20:48:44 +00003587 VK,
John McCallf89e55a2010-11-18 06:31:45 +00003588 Loc,
3589 &SS);
Douglas Gregor02024a92010-03-28 02:42:43 +00003590 if (RefExpr.isInvalid())
3591 return ExprError();
3592
John McCall2de56d12010-08-25 11:45:40 +00003593 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorc0c83002010-04-30 21:46:38 +00003594
3595 // We might need to perform a trailing qualification conversion, since
3596 // the element type on the parameter could be more qualified than the
3597 // element type in the expression we constructed.
3598 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3599 ParamType.getUnqualifiedType())) {
3600 Expr *RefE = RefExpr.takeAs<Expr>();
John McCall2de56d12010-08-25 11:45:40 +00003601 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorc0c83002010-04-30 21:46:38 +00003602 RefExpr = Owned(RefE);
3603 }
3604
Douglas Gregor02024a92010-03-28 02:42:43 +00003605 assert(!RefExpr.isInvalid() &&
3606 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003607 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003608 return move(RefExpr);
3609 }
3610 }
3611
3612 QualType T = VD->getType().getNonReferenceType();
3613 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003614 // When the non-type template parameter is a pointer, take the
3615 // address of the declaration.
John McCallf89e55a2010-11-18 06:31:45 +00003616 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003617 if (RefExpr.isInvalid())
3618 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003619
3620 if (T->isFunctionType() || T->isArrayType()) {
3621 // Decay functions and arrays.
3622 Expr *RefE = (Expr *)RefExpr.get();
3623 DefaultFunctionArrayConversion(RefE);
3624 if (RefE != RefExpr.get()) {
3625 RefExpr.release();
3626 RefExpr = Owned(RefE);
3627 }
3628
3629 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003630 }
3631
Douglas Gregorb7a09262010-04-01 18:32:35 +00003632 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00003633 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00003634 }
3635
John McCallf89e55a2010-11-18 06:31:45 +00003636 ExprValueKind VK = VK_RValue;
3637
Douglas Gregor02024a92010-03-28 02:42:43 +00003638 // If the non-type template parameter has reference type, qualify the
3639 // resulting declaration reference with the extra qualifiers on the
3640 // type that the reference refers to.
John McCallf89e55a2010-11-18 06:31:45 +00003641 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
3642 VK = VK_LValue;
3643 T = Context.getQualifiedType(T,
3644 TargetRef->getPointeeType().getQualifiers());
3645 }
Douglas Gregor02024a92010-03-28 02:42:43 +00003646
John McCallf89e55a2010-11-18 06:31:45 +00003647 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003648}
3649
3650/// \brief Construct a new expression that refers to the given
3651/// integral template argument with the given source-location
3652/// information.
3653///
3654/// This routine takes care of the mapping from an integral template
3655/// argument (which may have any integral type) to the appropriate
3656/// literal value.
John McCall60d7b3a2010-08-24 06:29:42 +00003657ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003658Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3659 SourceLocation Loc) {
3660 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregord3731192011-01-10 07:32:04 +00003661 "Operation is only valid for integral template arguments");
Douglas Gregor02024a92010-03-28 02:42:43 +00003662 QualType T = Arg.getIntegralType();
3663 if (T->isCharType() || T->isWideCharType())
3664 return Owned(new (Context) CharacterLiteral(
3665 Arg.getAsIntegral()->getZExtValue(),
3666 T->isWideCharType(),
3667 T,
3668 Loc));
3669 if (T->isBooleanType())
3670 return Owned(new (Context) CXXBoolLiteralExpr(
3671 Arg.getAsIntegral()->getBoolValue(),
3672 T,
3673 Loc));
3674
Peter Collingbournefb7b3632010-12-15 15:06:14 +00003675 QualType BT;
3676 if (const EnumType *ET = T->getAs<EnumType>())
3677 BT = ET->getDecl()->getPromotionType();
3678 else
3679 BT = T;
3680
3681 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
3682 ImpCastExprToType(E, T, CK_IntegralCast);
3683
3684 return Owned(E);
Douglas Gregor02024a92010-03-28 02:42:43 +00003685}
3686
Douglas Gregorab7ddf02011-01-12 23:45:44 +00003687/// \brief Match two template parameters within template parameter lists.
3688static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
3689 bool Complain,
3690 Sema::TemplateParameterListEqualKind Kind,
3691 SourceLocation TemplateArgLoc) {
3692 // Check the actual kind (type, non-type, template).
3693 if (Old->getKind() != New->getKind()) {
3694 if (Complain) {
3695 unsigned NextDiag = diag::err_template_param_different_kind;
3696 if (TemplateArgLoc.isValid()) {
3697 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3698 NextDiag = diag::note_template_param_different_kind;
3699 }
3700 S.Diag(New->getLocation(), NextDiag)
3701 << (Kind != Sema::TPL_TemplateMatch);
3702 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
3703 << (Kind != Sema::TPL_TemplateMatch);
3704 }
3705
3706 return false;
3707 }
3708
3709 // Check that both are parameter packs are neither are parameter packs.
Douglas Gregora0347822011-01-13 00:08:50 +00003710 // However, if we are matching a template template argument to a
3711 // template template parameter, the template template parameter can have
3712 // a parameter pack where the template template argument does not.
3713 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
3714 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
3715 Old->isTemplateParameterPack())) {
Douglas Gregorab7ddf02011-01-12 23:45:44 +00003716 if (Complain) {
3717 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3718 if (TemplateArgLoc.isValid()) {
3719 S.Diag(TemplateArgLoc,
3720 diag::err_template_arg_template_params_mismatch);
3721 NextDiag = diag::note_template_parameter_pack_non_pack;
3722 }
3723
3724 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
3725 : isa<NonTypeTemplateParmDecl>(New)? 1
3726 : 2;
3727 S.Diag(New->getLocation(), NextDiag)
3728 << ParamKind << New->isParameterPack();
3729 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
3730 << ParamKind << Old->isParameterPack();
3731 }
3732
3733 return false;
3734 }
3735
3736 // For non-type template parameters, check the type of the parameter.
3737 if (NonTypeTemplateParmDecl *OldNTTP
3738 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
3739 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
3740
3741 // If we are matching a template template argument to a template
3742 // template parameter and one of the non-type template parameter types
3743 // is dependent, then we must wait until template instantiation time
3744 // to actually compare the arguments.
3745 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
3746 (OldNTTP->getType()->isDependentType() ||
3747 NewNTTP->getType()->isDependentType()))
3748 return true;
3749
3750 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
3751 if (Complain) {
3752 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3753 if (TemplateArgLoc.isValid()) {
3754 S.Diag(TemplateArgLoc,
3755 diag::err_template_arg_template_params_mismatch);
3756 NextDiag = diag::note_template_nontype_parm_different_type;
3757 }
3758 S.Diag(NewNTTP->getLocation(), NextDiag)
3759 << NewNTTP->getType()
3760 << (Kind != Sema::TPL_TemplateMatch);
3761 S.Diag(OldNTTP->getLocation(),
3762 diag::note_template_nontype_parm_prev_declaration)
3763 << OldNTTP->getType();
3764 }
3765
3766 return false;
3767 }
3768
3769 return true;
3770 }
3771
3772 // For template template parameters, check the template parameter types.
3773 // The template parameter lists of template template
3774 // parameters must agree.
3775 if (TemplateTemplateParmDecl *OldTTP
3776 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
3777 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
3778 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3779 OldTTP->getTemplateParameters(),
3780 Complain,
3781 (Kind == Sema::TPL_TemplateMatch
3782 ? Sema::TPL_TemplateTemplateParmMatch
3783 : Kind),
3784 TemplateArgLoc);
3785 }
3786
3787 return true;
3788}
Douglas Gregor02024a92010-03-28 02:42:43 +00003789
Douglas Gregora0347822011-01-13 00:08:50 +00003790/// \brief Diagnose a known arity mismatch when comparing template argument
3791/// lists.
3792static
3793void DiagnoseTemplateParameterListArityMismatch(Sema &S,
3794 TemplateParameterList *New,
3795 TemplateParameterList *Old,
3796 Sema::TemplateParameterListEqualKind Kind,
3797 SourceLocation TemplateArgLoc) {
3798 unsigned NextDiag = diag::err_template_param_list_different_arity;
3799 if (TemplateArgLoc.isValid()) {
3800 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3801 NextDiag = diag::note_template_param_list_different_arity;
3802 }
3803 S.Diag(New->getTemplateLoc(), NextDiag)
3804 << (New->size() > Old->size())
3805 << (Kind != Sema::TPL_TemplateMatch)
3806 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
3807 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
3808 << (Kind != Sema::TPL_TemplateMatch)
3809 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3810}
3811
Douglas Gregorddc29e12009-02-06 22:42:48 +00003812/// \brief Determine whether the given template parameter lists are
3813/// equivalent.
3814///
Mike Stump1eb44332009-09-09 15:08:12 +00003815/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003816/// source code as part of a new template declaration.
3817///
3818/// \param Old The old template parameter list, typically found via
3819/// name lookup of the template declared with this template parameter
3820/// list.
3821///
3822/// \param Complain If true, this routine will produce a diagnostic if
3823/// the template parameter lists are not equivalent.
3824///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003825/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003826///
3827/// \param TemplateArgLoc If this source location is valid, then we
3828/// are actually checking the template parameter list of a template
3829/// argument (New) against the template parameter list of its
3830/// corresponding template template parameter (Old). We produce
3831/// slightly different diagnostics in this scenario.
3832///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003833/// \returns True if the template parameter lists are equal, false
3834/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003835bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003836Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3837 TemplateParameterList *Old,
3838 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003839 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003840 SourceLocation TemplateArgLoc) {
Douglas Gregora0347822011-01-13 00:08:50 +00003841 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
3842 if (Complain)
3843 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
3844 TemplateArgLoc);
Douglas Gregorddc29e12009-02-06 22:42:48 +00003845
3846 return false;
3847 }
3848
Douglas Gregorab7ddf02011-01-12 23:45:44 +00003849 // C++0x [temp.arg.template]p3:
3850 // A template-argument matches a template template-parameter (call it P)
3851 // when each of the template parameters in the template-parameter-list of
3852 // the template-argument’s corresponding class template or template alias
3853 // (call it A) matches the corresponding template parameter in the
Douglas Gregora0347822011-01-13 00:08:50 +00003854 // template-parameter-list of P. [...]
3855 TemplateParameterList::iterator NewParm = New->begin();
3856 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003857 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregora0347822011-01-13 00:08:50 +00003858 OldParmEnd = Old->end();
3859 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregorc421f542011-01-13 18:47:47 +00003860 if (Kind != TPL_TemplateTemplateArgumentMatch ||
3861 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregora0347822011-01-13 00:08:50 +00003862 if (NewParm == NewParmEnd) {
3863 if (Complain)
3864 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
3865 TemplateArgLoc);
3866
3867 return false;
3868 }
3869
3870 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
3871 Kind, TemplateArgLoc))
3872 return false;
3873
3874 ++NewParm;
3875 continue;
3876 }
3877
3878 // C++0x [temp.arg.template]p3:
3879 // [...] When P’s template- parameter-list contains a template parameter
3880 // pack (14.5.3), the template parameter pack will match zero or more
3881 // template parameters or template parameter packs in the
3882 // template-parameter-list of A with the same type and form as the
3883 // template parameter pack in P (ignoring whether those template
3884 // parameters are template parameter packs).
3885 for (; NewParm != NewParmEnd; ++NewParm) {
3886 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
3887 Kind, TemplateArgLoc))
3888 return false;
3889 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003890 }
Douglas Gregora0347822011-01-13 00:08:50 +00003891
3892 // Make sure we exhausted all of the arguments.
3893 if (NewParm != NewParmEnd) {
3894 if (Complain)
3895 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
3896 TemplateArgLoc);
3897
3898 return false;
3899 }
3900
Douglas Gregorddc29e12009-02-06 22:42:48 +00003901 return true;
3902}
3903
3904/// \brief Check whether a template can be declared within this scope.
3905///
3906/// If the template declaration is valid in this scope, returns
3907/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003908bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003909Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003910 // Find the nearest enclosing declaration scope.
3911 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3912 (S->getFlags() & Scope::TemplateParamScope) != 0)
3913 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003914
Douglas Gregorddc29e12009-02-06 22:42:48 +00003915 // C++ [temp]p2:
3916 // A template-declaration can appear only as a namespace scope or
3917 // class scope declaration.
3918 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003919 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3920 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003921 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003922 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003923
Eli Friedman1503f772009-07-31 01:43:05 +00003924 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003925 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003926
3927 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3928 return false;
3929
Mike Stump1eb44332009-09-09 15:08:12 +00003930 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003931 diag::err_template_outside_namespace_or_class_scope)
3932 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003933}
Douglas Gregorcc636682009-02-17 23:15:12 +00003934
Douglas Gregord5cb8762009-10-07 00:13:32 +00003935/// \brief Determine what kind of template specialization the given declaration
3936/// is.
3937static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3938 if (!D)
3939 return TSK_Undeclared;
3940
Douglas Gregorf6b11852009-10-08 15:14:33 +00003941 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3942 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003943 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3944 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003945 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3946 return Var->getTemplateSpecializationKind();
3947
Douglas Gregord5cb8762009-10-07 00:13:32 +00003948 return TSK_Undeclared;
3949}
3950
Douglas Gregor9302da62009-10-14 23:50:59 +00003951/// \brief Check whether a specialization is well-formed in the current
3952/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003953///
Douglas Gregor9302da62009-10-14 23:50:59 +00003954/// This routine determines whether a template specialization can be declared
3955/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003956///
3957/// \param S the semantic analysis object for which this check is being
3958/// performed.
3959///
3960/// \param Specialized the entity being specialized or instantiated, which
3961/// may be a kind of template (class template, function template, etc.) or
3962/// a member of a class template (member function, static data member,
3963/// member class).
3964///
3965/// \param PrevDecl the previous declaration of this entity, if any.
3966///
3967/// \param Loc the location of the explicit specialization or instantiation of
3968/// this entity.
3969///
3970/// \param IsPartialSpecialization whether this is a partial specialization of
3971/// a class template.
3972///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003973/// \returns true if there was an error that we cannot recover from, false
3974/// otherwise.
3975static bool CheckTemplateSpecializationScope(Sema &S,
3976 NamedDecl *Specialized,
3977 NamedDecl *PrevDecl,
3978 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003979 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003980 // Keep these "kind" numbers in sync with the %select statements in the
3981 // various diagnostics emitted by this routine.
3982 int EntityKind = 0;
Ted Kremenekfe62b062011-01-14 22:31:36 +00003983 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003984 EntityKind = IsPartialSpecialization? 1 : 0;
Ted Kremenekfe62b062011-01-14 22:31:36 +00003985 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003986 EntityKind = 2;
Ted Kremenekfe62b062011-01-14 22:31:36 +00003987 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003988 EntityKind = 3;
3989 else if (isa<VarDecl>(Specialized))
3990 EntityKind = 4;
3991 else if (isa<RecordDecl>(Specialized))
3992 EntityKind = 5;
3993 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003994 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3995 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003996 return true;
3997 }
3998
Douglas Gregor88b70942009-02-25 22:02:03 +00003999 // C++ [temp.expl.spec]p2:
4000 // An explicit specialization shall be declared in the namespace
4001 // of which the template is a member, or, for member templates, in
4002 // the namespace of which the enclosing class or enclosing class
4003 // template is a member. An explicit specialization of a member
4004 // function, member class or static data member of a class
4005 // template shall be declared in the namespace of which the class
4006 // template is a member. Such a declaration may also be a
4007 // definition. If the declaration is not a definition, the
4008 // specialization may be defined later in the name- space in which
4009 // the explicit specialization was declared, or in a namespace
4010 // that encloses the one in which the explicit specialization was
4011 // declared.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004012 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004013 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00004014 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00004015 return true;
4016 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004017
Douglas Gregor0a407472009-10-07 17:30:37 +00004018 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
4019 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00004020 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00004021 return true;
4022 }
4023
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004024 // C++ [temp.class.spec]p6:
4025 // A class template partial specialization may be declared or redeclared
4026 // in any namespace scope in which its definition may be defined (14.5.1
4027 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00004028 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004029 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00004030 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004031 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00004032 if ((!PrevDecl ||
4033 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
4034 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregor121dc9a2010-09-12 05:08:28 +00004035 // C++ [temp.exp.spec]p2:
4036 // An explicit specialization shall be declared in the namespace of which
4037 // the template is a member, or, for member templates, in the namespace
4038 // of which the enclosing class or enclosing class template is a member.
4039 // An explicit specialization of a member function, member class or
4040 // static data member of a class template shall be declared in the
4041 // namespace of which the class template is a member.
4042 //
4043 // C++0x [temp.expl.spec]p2:
4044 // An explicit specialization shall be declared in a namespace enclosing
4045 // the specialized template.
4046 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
4047 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregora4d5de52010-09-12 05:24:55 +00004048 bool IsCPlusPlus0xExtension
4049 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00004050 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00004051 S.Diag(Loc, IsCPlusPlus0xExtension
4052 ? diag::ext_template_spec_decl_out_of_scope_global
4053 : diag::err_template_spec_decl_out_of_scope_global)
4054 << EntityKind << Specialized;
Douglas Gregor9302da62009-10-14 23:50:59 +00004055 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00004056 S.Diag(Loc, IsCPlusPlus0xExtension
4057 ? diag::ext_template_spec_decl_out_of_scope
4058 : diag::err_template_spec_decl_out_of_scope)
4059 << EntityKind << Specialized
4060 << cast<NamedDecl>(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00004061
4062 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4063 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00004064 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004065 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00004066
4067 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00004068 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00004069 // Note that HandleDeclarator() performs this check for explicit
4070 // specializations of function templates, static data members, and member
4071 // functions, so we skip the check here for those kinds of entities.
4072 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00004073 // Should we refactor that check, so that it occurs later?
4074 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00004075 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
4076 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00004077 if (isa<TranslationUnitDecl>(SpecializedContext))
4078 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
4079 << EntityKind << Specialized;
4080 else if (isa<NamespaceDecl>(SpecializedContext))
4081 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
4082 << EntityKind << Specialized
4083 << cast<NamedDecl>(SpecializedContext);
4084
Douglas Gregor9302da62009-10-14 23:50:59 +00004085 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00004086 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00004087
4088 // FIXME: check for specialization-after-instantiation errors and such.
4089
Douglas Gregor88b70942009-02-25 22:02:03 +00004090 return false;
4091}
Douglas Gregorbacb9492011-01-03 21:13:47 +00004092
4093/// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
4094/// that checks non-type template partial specialization arguments.
4095static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
4096 NonTypeTemplateParmDecl *Param,
4097 const TemplateArgument *Args,
4098 unsigned NumArgs) {
4099 for (unsigned I = 0; I != NumArgs; ++I) {
4100 if (Args[I].getKind() == TemplateArgument::Pack) {
4101 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
4102 Args[I].pack_begin(),
4103 Args[I].pack_size()))
4104 return true;
4105
Douglas Gregore94866f2009-06-12 21:21:02 +00004106 continue;
Douglas Gregorbacb9492011-01-03 21:13:47 +00004107 }
4108
4109 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004110 if (!ArgExpr) {
Douglas Gregore94866f2009-06-12 21:21:02 +00004111 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004112 }
Douglas Gregore94866f2009-06-12 21:21:02 +00004113
Douglas Gregor7a21fd42011-01-03 21:37:45 +00004114 // We can have a pack expansion of any of the bullets below.
Douglas Gregorbacb9492011-01-03 21:13:47 +00004115 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
4116 ArgExpr = Expansion->getPattern();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00004117
4118 // Strip off any implicit casts we added as part of type checking.
4119 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4120 ArgExpr = ICE->getSubExpr();
Douglas Gregorb9c66312010-12-23 17:13:55 +00004121
Douglas Gregore94866f2009-06-12 21:21:02 +00004122 // C++ [temp.class.spec]p8:
4123 // A non-type argument is non-specialized if it is the name of a
4124 // non-type parameter. All other non-type arguments are
4125 // specialized.
4126 //
4127 // Below, we check the two conditions that only apply to
4128 // specialized non-type arguments, so skip any non-specialized
4129 // arguments.
4130 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00004131 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregore94866f2009-06-12 21:21:02 +00004132 continue;
Douglas Gregorb9c66312010-12-23 17:13:55 +00004133
Douglas Gregore94866f2009-06-12 21:21:02 +00004134 // C++ [temp.class.spec]p9:
4135 // Within the argument list of a class template partial
4136 // specialization, the following restrictions apply:
4137 // -- A partially specialized non-type argument expression
4138 // shall not involve a template parameter of the partial
4139 // specialization except when the argument expression is a
4140 // simple identifier.
4141 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004142 S.Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00004143 diag::err_dependent_non_type_arg_in_partial_spec)
4144 << ArgExpr->getSourceRange();
4145 return true;
4146 }
Douglas Gregorbacb9492011-01-03 21:13:47 +00004147
Douglas Gregore94866f2009-06-12 21:21:02 +00004148 // -- The type of a template parameter corresponding to a
4149 // specialized non-type argument shall not be dependent on a
4150 // parameter of the specialization.
4151 if (Param->getType()->isDependentType()) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004152 S.Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00004153 diag::err_dependent_typed_non_type_arg_in_partial_spec)
4154 << Param->getType()
4155 << ArgExpr->getSourceRange();
Douglas Gregorbacb9492011-01-03 21:13:47 +00004156 S.Diag(Param->getLocation(), diag::note_template_param_here);
Douglas Gregore94866f2009-06-12 21:21:02 +00004157 return true;
4158 }
4159 }
Douglas Gregorbacb9492011-01-03 21:13:47 +00004160
4161 return false;
4162}
4163
4164/// \brief Check the non-type template arguments of a class template
4165/// partial specialization according to C++ [temp.class.spec]p9.
4166///
4167/// \param TemplateParams the template parameters of the primary class
4168/// template.
4169///
4170/// \param TemplateArg the template arguments of the class template
4171/// partial specialization.
4172///
4173/// \returns true if there was an error, false otherwise.
4174static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
4175 TemplateParameterList *TemplateParams,
4176 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs) {
4177 const TemplateArgument *ArgList = TemplateArgs.data();
4178
4179 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4180 NonTypeTemplateParmDecl *Param
4181 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
4182 if (!Param)
4183 continue;
4184
4185 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
4186 &ArgList[I], 1))
4187 return true;
4188 }
Douglas Gregore94866f2009-06-12 21:21:02 +00004189
4190 return false;
4191}
4192
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004193/// \brief Retrieve the previous declaration of the given declaration.
4194static NamedDecl *getPreviousDecl(NamedDecl *ND) {
4195 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4196 return VD->getPreviousDeclaration();
4197 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
4198 return FD->getPreviousDeclaration();
4199 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
4200 return TD->getPreviousDeclaration();
4201 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
4202 return TD->getPreviousDeclaration();
4203 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4204 return FTD->getPreviousDeclaration();
4205 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
4206 return CTD->getPreviousDeclaration();
4207 return 0;
4208}
4209
John McCalld226f652010-08-21 09:40:31 +00004210DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00004211Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
4212 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00004213 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004214 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004215 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00004216 SourceLocation TemplateNameLoc,
4217 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00004218 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00004219 SourceLocation RAngleLoc,
4220 AttributeList *Attr,
4221 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004222 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00004223
Douglas Gregorcc636682009-02-17 23:15:12 +00004224 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00004225 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004226 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00004227 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
4228
4229 if (!ClassTemplate) {
4230 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
4231 << (Name.getAsTemplateDecl() &&
4232 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
4233 return true;
4234 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004235
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004236 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004237 bool isPartialSpecialization = false;
4238
Douglas Gregor88b70942009-02-25 22:02:03 +00004239 // Check the validity of the template headers that introduce this
4240 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004241 // FIXME: We probably shouldn't complain about these headers for
4242 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004243 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00004244 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00004245 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
4246 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004247 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00004248 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004249 isExplicitSpecialization,
4250 Invalid);
4251 if (Invalid)
4252 return true;
4253
Abramo Bagnara9b934882010-06-12 08:15:14 +00004254 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
4255 if (TemplateParams)
4256 --NumMatchedTemplateParamLists;
4257
Douglas Gregor05396e22009-08-25 17:23:04 +00004258 if (TemplateParams && TemplateParams->size() > 0) {
4259 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00004260
Douglas Gregorb0ee93c2010-12-21 08:14:57 +00004261 if (TUK == TUK_Friend) {
4262 Diag(KWLoc, diag::err_partial_specialization_friend)
4263 << SourceRange(LAngleLoc, RAngleLoc);
4264 return true;
4265 }
4266
Douglas Gregor05396e22009-08-25 17:23:04 +00004267 // C++ [temp.class.spec]p10:
4268 // The template parameter list of a specialization shall not
4269 // contain default template argument values.
4270 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4271 Decl *Param = TemplateParams->getParam(I);
4272 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4273 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004274 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004275 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00004276 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004277 }
4278 } else if (NonTypeTemplateParmDecl *NTTP
4279 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4280 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004281 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004282 diag::err_default_arg_in_partial_spec)
4283 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004284 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004285 }
4286 } else {
4287 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00004288 if (TTP->hasDefaultArgument()) {
4289 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004290 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00004291 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004292 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004293 }
4294 }
4295 }
Douglas Gregora735b202009-10-13 14:39:41 +00004296 } else if (TemplateParams) {
4297 if (TUK == TUK_Friend)
4298 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00004299 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00004300 SourceRange(TemplateParams->getTemplateLoc(),
4301 TemplateParams->getRAngleLoc()))
4302 << SourceRange(LAngleLoc, RAngleLoc);
4303 else
4304 isExplicitSpecialization = true;
4305 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00004306 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00004307 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004308 isExplicitSpecialization = true;
4309 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004310
Douglas Gregorcc636682009-02-17 23:15:12 +00004311 // Check that the specialization uses the same tag kind as the
4312 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004313 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4314 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004315 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004316 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004317 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004318 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00004319 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004320 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00004321 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004322 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004323 diag::note_previous_use);
4324 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4325 }
4326
Douglas Gregor40808ce2009-03-09 23:48:35 +00004327 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004328 TemplateArgumentListInfo TemplateArgs;
4329 TemplateArgs.setLAngleLoc(LAngleLoc);
4330 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004331 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00004332
Douglas Gregor925910d2011-01-03 20:35:03 +00004333 // Check for unexpanded parameter packs in any of the template arguments.
4334 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4335 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4336 UPPC_PartialSpecialization))
4337 return true;
4338
Douglas Gregorcc636682009-02-17 23:15:12 +00004339 // Check that the template argument list is well-formed for this
4340 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00004341 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00004342 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4343 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004344 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004345
Douglas Gregor910f8002010-11-07 23:05:16 +00004346 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregorcc636682009-02-17 23:15:12 +00004347 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004348
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004349 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00004350 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004351 if (isPartialSpecialization) {
Douglas Gregorbacb9492011-01-03 21:13:47 +00004352 if (CheckClassTemplatePartialSpecializationArgs(*this,
Douglas Gregore94866f2009-06-12 21:21:02 +00004353 ClassTemplate->getTemplateParameters(),
Douglas Gregorb9c66312010-12-23 17:13:55 +00004354 Converted))
Douglas Gregore94866f2009-06-12 21:21:02 +00004355 return true;
4356
Douglas Gregorde090962010-02-09 00:37:32 +00004357 if (!Name.isDependent() &&
4358 !TemplateSpecializationType::anyDependentTemplateArguments(
4359 TemplateArgs.getArgumentArray(),
4360 TemplateArgs.size())) {
4361 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4362 << ClassTemplate->getDeclName();
4363 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00004364 }
4365 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004366
Douglas Gregorcc636682009-02-17 23:15:12 +00004367 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004368 ClassTemplateSpecializationDecl *PrevDecl = 0;
4369
4370 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004371 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004372 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004373 = ClassTemplate->findPartialSpecialization(Converted.data(),
4374 Converted.size(),
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004375 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004376 else
4377 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004378 = ClassTemplate->findSpecialization(Converted.data(),
4379 Converted.size(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00004380
4381 ClassTemplateSpecializationDecl *Specialization = 0;
4382
Douglas Gregor88b70942009-02-25 22:02:03 +00004383 // Check whether we can declare a class template specialization in
4384 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004385 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00004386 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00004387 TemplateNameLoc,
4388 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004389 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004390
Douglas Gregorb88e8882009-07-30 17:40:51 +00004391 // The canonical type
4392 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004393 if (PrevDecl &&
4394 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00004395 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004396 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004397 // arguments was referenced but not declared, or we're only
4398 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00004399 // declaration node as our own, updating its source location to
4400 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004401 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004402 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00004403 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00004404 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004405 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00004406 // Build the canonical type that describes the converted template
4407 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00004408 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4409 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb9c66312010-12-23 17:13:55 +00004410 Converted.data(),
4411 Converted.size());
4412
4413 if (Context.hasSameType(CanonType,
4414 ClassTemplate->getInjectedClassNameSpecialization())) {
4415 // C++ [temp.class.spec]p9b3:
4416 //
4417 // -- The argument list of the specialization shall not be identical
4418 // to the implicit argument list of the primary template.
4419 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4420 << (TUK == TUK_Definition)
4421 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4422 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
4423 ClassTemplate->getIdentifier(),
4424 TemplateNameLoc,
4425 Attr,
4426 TemplateParams,
4427 AS_none);
4428 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00004429
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004430 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004431 ClassTemplatePartialSpecializationDecl *PrevPartial
4432 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004433 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004434 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00004435 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00004436 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004437 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00004438 TemplateNameLoc,
4439 TemplateParams,
4440 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004441 Converted.data(),
4442 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00004443 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00004444 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004445 PrevPartial,
4446 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00004447 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004448 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004449 Partial->setTemplateParameterListsInfo(Context,
4450 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004451 (TemplateParameterList**) TemplateParameterLists.release());
4452 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004453
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004454 if (!PrevPartial)
4455 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004456 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00004457
Douglas Gregored9c0f92009-10-29 00:04:11 +00004458 // If we are providing an explicit specialization of a member class
4459 // template specialization, make a note of that.
4460 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4461 PrevPartial->setMemberSpecialization();
4462
Douglas Gregor031a5882009-06-13 00:26:55 +00004463 // Check that all of the template parameters of the class template
4464 // partial specialization are deducible from the template
4465 // arguments. If not, this class template partial specialization
4466 // will never be used.
4467 llvm::SmallVector<bool, 8> DeducibleParams;
4468 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00004469 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004470 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00004471 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00004472 unsigned NumNonDeducible = 0;
4473 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4474 if (!DeducibleParams[I])
4475 ++NumNonDeducible;
4476
4477 if (NumNonDeducible) {
4478 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4479 << (NumNonDeducible > 1)
4480 << SourceRange(TemplateNameLoc, RAngleLoc);
4481 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4482 if (!DeducibleParams[I]) {
4483 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4484 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00004485 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004486 diag::note_partial_spec_unused_parameter)
4487 << Param->getDeclName();
4488 else
Mike Stump1eb44332009-09-09 15:08:12 +00004489 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004490 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00004491 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00004492 }
4493 }
4494 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004495 } else {
4496 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004497 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004498 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004499 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00004500 ClassTemplate->getDeclContext(),
4501 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004502 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004503 Converted.data(),
4504 Converted.size(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004505 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004506 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004507 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004508 Specialization->setTemplateParameterListsInfo(Context,
4509 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004510 (TemplateParameterList**) TemplateParameterLists.release());
4511 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004512
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004513 if (!PrevDecl)
4514 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00004515
4516 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004517 }
4518
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004519 // C++ [temp.expl.spec]p6:
4520 // If a template, a member template or the member of a class template is
4521 // explicitly specialized then that specialization shall be declared
4522 // before the first use of that specialization that would cause an implicit
4523 // instantiation to take place, in every translation unit in which such a
4524 // use occurs; no diagnostic is required.
4525 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004526 bool Okay = false;
4527 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4528 // Is there any previous explicit specialization declaration?
4529 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4530 Okay = true;
4531 break;
4532 }
4533 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004534
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004535 if (!Okay) {
4536 SourceRange Range(TemplateNameLoc, RAngleLoc);
4537 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4538 << Context.getTypeDeclType(Specialization) << Range;
4539
4540 Diag(PrevDecl->getPointOfInstantiation(),
4541 diag::note_instantiation_required_here)
4542 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004543 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004544 return true;
4545 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004546 }
4547
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004548 // If this is not a friend, note that this is an explicit specialization.
4549 if (TUK != TUK_Friend)
4550 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004551
4552 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004553 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00004554 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004555 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004556 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004557 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00004558 Diag(Def->getLocation(), diag::note_previous_definition);
4559 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00004560 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004561 }
4562 }
4563
John McCall7f1b9872010-12-18 03:30:47 +00004564 if (Attr)
4565 ProcessDeclAttributeList(S, Specialization, Attr);
4566
Douglas Gregorfc705b82009-02-26 22:19:44 +00004567 // Build the fully-sugared type for this class template
4568 // specialization as the user wrote in the specialization
4569 // itself. This means that we'll pretty-print the type retrieved
4570 // from the specialization's declaration the way that the user
4571 // actually wrote the specialization, rather than formatting the
4572 // name based on the "canonical" representation used to store the
4573 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004574 TypeSourceInfo *WrittenTy
4575 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4576 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004577 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004578 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor7e9b57b2010-07-06 18:33:12 +00004579 if (TemplateParams)
4580 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004581 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00004582 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00004583
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004584 // C++ [temp.expl.spec]p9:
4585 // A template explicit specialization is in the scope of the
4586 // namespace in which the template was defined.
4587 //
4588 // We actually implement this paragraph where we set the semantic
4589 // context (in the creation of the ClassTemplateSpecializationDecl),
4590 // but we also maintain the lexical context where the actual
4591 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00004592 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004593
Douglas Gregorcc636682009-02-17 23:15:12 +00004594 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004595 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00004596 Specialization->startDefinition();
4597
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004598 if (TUK == TUK_Friend) {
4599 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4600 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00004601 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004602 /*FIXME:*/KWLoc);
4603 Friend->setAccess(AS_public);
4604 CurContext->addDecl(Friend);
4605 } else {
4606 // Add the specialization into its lexical context, so that it can
4607 // be seen when iterating through the list of declarations in that
4608 // context. However, specializations are not found by name lookup.
4609 CurContext->addDecl(Specialization);
4610 }
John McCalld226f652010-08-21 09:40:31 +00004611 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00004612}
Douglas Gregord57959a2009-03-27 23:10:48 +00004613
John McCalld226f652010-08-21 09:40:31 +00004614Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00004615 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004616 Declarator &D) {
Douglas Gregore542c862009-06-23 23:11:28 +00004617 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4618}
4619
John McCalld226f652010-08-21 09:40:31 +00004620Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004621 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004622 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00004623 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004624 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00004625
Douglas Gregor52591bf2009-06-24 00:54:41 +00004626 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004627 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00004628 }
Mike Stump1eb44332009-09-09 15:08:12 +00004629
Douglas Gregor52591bf2009-06-24 00:54:41 +00004630 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004631
John McCalld226f652010-08-21 09:40:31 +00004632 Decl *DP = HandleDeclarator(ParentScope, D,
4633 move(TemplateParameterLists),
4634 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004635 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00004636 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00004637 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00004638 FunctionTemplate->getTemplatedDecl());
4639 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4640 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4641 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00004642}
4643
John McCall75042392010-02-11 01:33:53 +00004644/// \brief Strips various properties off an implicit instantiation
4645/// that has just been explicitly specialized.
4646static void StripImplicitInstantiation(NamedDecl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00004647 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00004648
4649 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4650 FD->setInlineSpecified(false);
4651 }
4652}
4653
Douglas Gregor454885e2009-10-15 15:54:05 +00004654/// \brief Diagnose cases where we have an explicit template specialization
4655/// before/after an explicit template instantiation, producing diagnostics
4656/// for those cases where they are required and determining whether the
4657/// new specialization/instantiation will have any effect.
4658///
Douglas Gregor454885e2009-10-15 15:54:05 +00004659/// \param NewLoc the location of the new explicit specialization or
4660/// instantiation.
4661///
4662/// \param NewTSK the kind of the new explicit specialization or instantiation.
4663///
4664/// \param PrevDecl the previous declaration of the entity.
4665///
4666/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4667///
4668/// \param PrevPointOfInstantiation if valid, indicates where the previus
4669/// declaration was instantiated (either implicitly or explicitly).
4670///
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004671/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00004672/// specialization or instantiation has no effect and should be ignored.
4673///
4674/// \returns true if there was an error that should prevent the introduction of
4675/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004676bool
4677Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4678 TemplateSpecializationKind NewTSK,
4679 NamedDecl *PrevDecl,
4680 TemplateSpecializationKind PrevTSK,
4681 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004682 bool &HasNoEffect) {
4683 HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004684
4685 switch (NewTSK) {
4686 case TSK_Undeclared:
4687 case TSK_ImplicitInstantiation:
4688 assert(false && "Don't check implicit instantiations here");
4689 return false;
4690
4691 case TSK_ExplicitSpecialization:
4692 switch (PrevTSK) {
4693 case TSK_Undeclared:
4694 case TSK_ExplicitSpecialization:
4695 // Okay, we're just specializing something that is either already
4696 // explicitly specialized or has merely been mentioned without any
4697 // instantiation.
4698 return false;
4699
4700 case TSK_ImplicitInstantiation:
4701 if (PrevPointOfInstantiation.isInvalid()) {
4702 // The declaration itself has not actually been instantiated, so it is
4703 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004704 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004705 return false;
4706 }
4707 // Fall through
4708
4709 case TSK_ExplicitInstantiationDeclaration:
4710 case TSK_ExplicitInstantiationDefinition:
4711 assert((PrevTSK == TSK_ImplicitInstantiation ||
4712 PrevPointOfInstantiation.isValid()) &&
4713 "Explicit instantiation without point of instantiation?");
4714
4715 // C++ [temp.expl.spec]p6:
4716 // If a template, a member template or the member of a class template
4717 // is explicitly specialized then that specialization shall be declared
4718 // before the first use of that specialization that would cause an
4719 // implicit instantiation to take place, in every translation unit in
4720 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004721 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4722 // Is there any previous explicit specialization declaration?
4723 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4724 return false;
4725 }
4726
Douglas Gregor0d035142009-10-27 18:42:08 +00004727 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004728 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004729 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004730 << (PrevTSK != TSK_ImplicitInstantiation);
4731
4732 return true;
4733 }
4734 break;
4735
4736 case TSK_ExplicitInstantiationDeclaration:
4737 switch (PrevTSK) {
4738 case TSK_ExplicitInstantiationDeclaration:
4739 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004740 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004741 return false;
4742
4743 case TSK_Undeclared:
4744 case TSK_ImplicitInstantiation:
4745 // We're explicitly instantiating something that may have already been
4746 // implicitly instantiated; that's fine.
4747 return false;
4748
4749 case TSK_ExplicitSpecialization:
4750 // C++0x [temp.explicit]p4:
4751 // For a given set of template parameters, if an explicit instantiation
4752 // of a template appears after a declaration of an explicit
4753 // specialization for that template, the explicit instantiation has no
4754 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004755 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004756 return false;
4757
4758 case TSK_ExplicitInstantiationDefinition:
4759 // C++0x [temp.explicit]p10:
4760 // If an entity is the subject of both an explicit instantiation
4761 // declaration and an explicit instantiation definition in the same
4762 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004763 Diag(NewLoc,
4764 diag::err_explicit_instantiation_declaration_after_definition);
4765 Diag(PrevPointOfInstantiation,
4766 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004767 assert(PrevPointOfInstantiation.isValid() &&
4768 "Explicit instantiation without point of instantiation?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004769 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004770 return false;
4771 }
4772 break;
4773
4774 case TSK_ExplicitInstantiationDefinition:
4775 switch (PrevTSK) {
4776 case TSK_Undeclared:
4777 case TSK_ImplicitInstantiation:
4778 // We're explicitly instantiating something that may have already been
4779 // implicitly instantiated; that's fine.
4780 return false;
4781
4782 case TSK_ExplicitSpecialization:
4783 // C++ DR 259, C++0x [temp.explicit]p4:
4784 // For a given set of template parameters, if an explicit
4785 // instantiation of a template appears after a declaration of
4786 // an explicit specialization for that template, the explicit
4787 // instantiation has no effect.
4788 //
4789 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004790 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004791 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004792 if (!getLangOptions().CPlusPlus0x) {
4793 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004794 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004795 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004796 diag::note_previous_template_specialization);
4797 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004798 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004799 return false;
4800
4801 case TSK_ExplicitInstantiationDeclaration:
4802 // We're explicity instantiating a definition for something for which we
4803 // were previously asked to suppress instantiations. That's fine.
4804 return false;
4805
4806 case TSK_ExplicitInstantiationDefinition:
4807 // C++0x [temp.spec]p5:
4808 // For a given template and a given set of template-arguments,
4809 // - an explicit instantiation definition shall appear at most once
4810 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004811 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004812 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004813 Diag(PrevPointOfInstantiation,
4814 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004815 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004816 return false;
4817 }
4818 break;
4819 }
4820
4821 assert(false && "Missing specialization/instantiation case?");
4822
4823 return false;
4824}
4825
John McCallaf2094e2010-04-08 09:05:18 +00004826/// \brief Perform semantic analysis for the given dependent function
4827/// template specialization. The only possible way to get a dependent
4828/// function template specialization is with a friend declaration,
4829/// like so:
4830///
4831/// template <class T> void foo(T);
4832/// template <class T> class A {
4833/// friend void foo<>(T);
4834/// };
4835///
4836/// There really isn't any useful analysis we can do here, so we
4837/// just store the information.
4838bool
4839Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4840 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4841 LookupResult &Previous) {
4842 // Remove anything from Previous that isn't a function template in
4843 // the correct context.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004844 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallaf2094e2010-04-08 09:05:18 +00004845 LookupResult::Filter F = Previous.makeFilter();
4846 while (F.hasNext()) {
4847 NamedDecl *D = F.next()->getUnderlyingDecl();
4848 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl7a126a42010-08-31 00:36:30 +00004849 !FDLookupContext->InEnclosingNamespaceSetOf(
4850 D->getDeclContext()->getRedeclContext()))
John McCallaf2094e2010-04-08 09:05:18 +00004851 F.erase();
4852 }
4853 F.done();
4854
4855 // Should this be diagnosed here?
4856 if (Previous.empty()) return true;
4857
4858 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4859 ExplicitTemplateArgs);
4860 return false;
4861}
4862
Abramo Bagnarae03db982010-05-20 15:32:11 +00004863/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004864/// specialization.
4865///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004866/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004867/// explicit function template specialization. On successful completion,
4868/// the function declaration \p FD will become a function template
4869/// specialization.
4870///
4871/// \param FD the function declaration, which will be updated to become a
4872/// function template specialization.
4873///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004874/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4875/// if any. Note that this may be valid info even when 0 arguments are
4876/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4877/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004878///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004879/// \param PrevDecl the set of declarations that may be specialized by
4880/// this function specialization.
4881bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004882Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004883 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004884 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004885 // The set of function template specializations that could match this
4886 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004887 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004888
Sebastian Redl7a126a42010-08-31 00:36:30 +00004889 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall68263142009-11-18 22:49:29 +00004890 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4891 I != E; ++I) {
4892 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4893 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004894 // Only consider templates found within the same semantic lookup scope as
4895 // FD.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004896 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4897 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004898 continue;
4899
4900 // C++ [temp.expl.spec]p11:
4901 // A trailing template-argument can be left unspecified in the
4902 // template-id naming an explicit function template specialization
4903 // provided it can be deduced from the function argument type.
4904 // Perform template argument deduction to determine whether we may be
4905 // specializing this template.
4906 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004907 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004908 FunctionDecl *Specialization = 0;
4909 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004910 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004911 FD->getType(),
4912 Specialization,
4913 Info)) {
4914 // FIXME: Template argument deduction failed; record why it failed, so
4915 // that we can provide nifty diagnostics.
4916 (void)TDK;
4917 continue;
4918 }
4919
4920 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004921 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004922 }
4923 }
4924
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004925 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004926 UnresolvedSetIterator Result
4927 = getMostSpecialized(Candidates.begin(), Candidates.end(),
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004928 TPOC_Other, 0, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004929 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004930 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004931 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004932 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004933 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004934 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004935 return true;
John McCallc373d482010-01-27 01:50:18 +00004936
4937 // Ignore access information; it doesn't figure into redeclaration checking.
4938 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004939 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004940
4941 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004942 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004943
4944 // If this is a friend declaration, then we're not really declaring
4945 // an explicit specialization.
4946 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004947
Douglas Gregord5cb8762009-10-07 00:13:32 +00004948 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004949 if (!isFriend &&
4950 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004951 Specialization->getPrimaryTemplate(),
4952 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004953 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004954 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004955
4956 // C++ [temp.expl.spec]p6:
4957 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004958 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004959 // before the first use of that specialization that would cause an implicit
4960 // instantiation to take place, in every translation unit in which such a
4961 // use occurs; no diagnostic is required.
4962 FunctionTemplateSpecializationInfo *SpecInfo
4963 = Specialization->getTemplateSpecializationInfo();
4964 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004965
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004966 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00004967 if (!isFriend &&
4968 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004969 TSK_ExplicitSpecialization,
4970 Specialization,
4971 SpecInfo->getTemplateSpecializationKind(),
4972 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004973 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004974 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004975
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004976 // Mark the prior declaration as an explicit specialization, so that later
4977 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004978 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00004979 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004980 MarkUnusedFileScopedDecl(Specialization);
4981 }
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004982
4983 // Turn the given function declaration into a function template
4984 // specialization, with the template arguments from the previous
4985 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004986 // Take copies of (semantic and syntactic) template argument lists.
4987 const TemplateArgumentList* TemplArgs = new (Context)
4988 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4989 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4990 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004991 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004992 TemplArgs, /*InsertPos=*/0,
4993 SpecInfo->getTemplateSpecializationKind(),
4994 TemplArgsAsWritten);
4995
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004996 // The "previous declaration" for this function template specialization is
4997 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004998 Previous.clear();
4999 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005000 return false;
5001}
5002
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005003/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005004/// specialization.
5005///
5006/// This routine performs all of the semantic analysis required for an
5007/// explicit member function specialization. On successful completion,
5008/// the function declaration \p FD will become a member function
5009/// specialization.
5010///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005011/// \param Member the member declaration, which will be updated to become a
5012/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005013///
John McCall68263142009-11-18 22:49:29 +00005014/// \param Previous the set of declarations, one of which may be specialized
5015/// by this function specialization; the set will be modified to contain the
5016/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005017bool
John McCall68263142009-11-18 22:49:29 +00005018Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005019 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00005020
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005021 // Try to find the member we are instantiating.
5022 NamedDecl *Instantiation = 0;
5023 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005024 MemberSpecializationInfo *MSInfo = 0;
5025
John McCall68263142009-11-18 22:49:29 +00005026 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005027 // Nowhere to look anyway.
5028 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00005029 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5030 I != E; ++I) {
5031 NamedDecl *D = (*I)->getUnderlyingDecl();
5032 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005033 if (Context.hasSameType(Function->getType(), Method->getType())) {
5034 Instantiation = Method;
5035 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005036 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005037 break;
5038 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005039 }
5040 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005041 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00005042 VarDecl *PrevVar;
5043 if (Previous.isSingleResult() &&
5044 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005045 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00005046 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005047 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005048 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005049 }
5050 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00005051 CXXRecordDecl *PrevRecord;
5052 if (Previous.isSingleResult() &&
5053 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
5054 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005055 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005056 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005057 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005058 }
5059
5060 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005061 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005062 // specializations are always out-of-line, the caller will complain about
5063 // this mismatch later.
5064 return false;
5065 }
John McCall77e8b112010-04-13 20:37:33 +00005066
5067 // If this is a friend, just bail out here before we start turning
5068 // things into explicit specializations.
5069 if (Member->getFriendObjectKind() != Decl::FOK_None) {
5070 // Preserve instantiation information.
5071 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
5072 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
5073 cast<CXXMethodDecl>(InstantiatedFrom),
5074 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
5075 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
5076 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
5077 cast<CXXRecordDecl>(InstantiatedFrom),
5078 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
5079 }
5080
5081 Previous.clear();
5082 Previous.addDecl(Instantiation);
5083 return false;
5084 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005085
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005086 // Make sure that this is a specialization of a member.
5087 if (!InstantiatedFrom) {
5088 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
5089 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005090 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
5091 return true;
5092 }
5093
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005094 // C++ [temp.expl.spec]p6:
5095 // If a template, a member template or the member of a class template is
5096 // explicitly specialized then that spe- cialization shall be declared
5097 // before the first use of that specialization that would cause an implicit
5098 // instantiation to take place, in every translation unit in which such a
5099 // use occurs; no diagnostic is required.
5100 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00005101
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005102 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00005103 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
5104 TSK_ExplicitSpecialization,
5105 Instantiation,
5106 MSInfo->getTemplateSpecializationKind(),
5107 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005108 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005109 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005110
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005111 // Check the scope of this explicit specialization.
5112 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005113 InstantiatedFrom,
5114 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00005115 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005116 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00005117
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005118 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00005119 // the original declaration to note that it is an explicit specialization
5120 // (if it was previously an implicit instantiation). This latter step
5121 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005122 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005123 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
5124 if (InstantiationFunction->getTemplateSpecializationKind() ==
5125 TSK_ImplicitInstantiation) {
5126 InstantiationFunction->setTemplateSpecializationKind(
5127 TSK_ExplicitSpecialization);
5128 InstantiationFunction->setLocation(Member->getLocation());
5129 }
5130
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005131 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
5132 cast<CXXMethodDecl>(InstantiatedFrom),
5133 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005134 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005135 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005136 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
5137 if (InstantiationVar->getTemplateSpecializationKind() ==
5138 TSK_ImplicitInstantiation) {
5139 InstantiationVar->setTemplateSpecializationKind(
5140 TSK_ExplicitSpecialization);
5141 InstantiationVar->setLocation(Member->getLocation());
5142 }
5143
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005144 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
5145 cast<VarDecl>(InstantiatedFrom),
5146 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005147 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005148 } else {
5149 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00005150 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
5151 if (InstantiationClass->getTemplateSpecializationKind() ==
5152 TSK_ImplicitInstantiation) {
5153 InstantiationClass->setTemplateSpecializationKind(
5154 TSK_ExplicitSpecialization);
5155 InstantiationClass->setLocation(Member->getLocation());
5156 }
5157
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005158 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00005159 cast<CXXRecordDecl>(InstantiatedFrom),
5160 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00005161 }
5162
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005163 // Save the caller the trouble of having to figure out which declaration
5164 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00005165 Previous.clear();
5166 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005167 return false;
5168}
5169
Douglas Gregor558c0322009-10-14 23:41:34 +00005170/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00005171///
5172/// \returns true if a serious error occurs, false otherwise.
5173static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00005174 SourceLocation InstLoc,
5175 bool WasQualifiedName) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005176 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
5177 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregor558c0322009-10-14 23:41:34 +00005178
Douglas Gregor669eed82010-07-13 00:10:04 +00005179 if (CurContext->isRecord()) {
5180 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
5181 << D;
5182 return true;
5183 }
5184
Douglas Gregor558c0322009-10-14 23:41:34 +00005185 // C++0x [temp.explicit]p2:
5186 // An explicit instantiation shall appear in an enclosing namespace of its
5187 // template.
5188 //
5189 // This is DR275, which we do not retroactively apply to C++98/03.
5190 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005191 !CurContext->Encloses(OrigContext)) {
5192 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00005193 S.Diag(InstLoc,
5194 S.getLangOptions().CPlusPlus0x?
5195 diag::err_explicit_instantiation_out_of_scope
5196 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00005197 << D << NS;
5198 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00005199 S.Diag(InstLoc,
5200 S.getLangOptions().CPlusPlus0x?
5201 diag::err_explicit_instantiation_must_be_global
5202 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00005203 << D;
5204 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00005205 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00005206 }
Sebastian Redl7a126a42010-08-31 00:36:30 +00005207
Douglas Gregor558c0322009-10-14 23:41:34 +00005208 // C++0x [temp.explicit]p2:
5209 // If the name declared in the explicit instantiation is an unqualified
5210 // name, the explicit instantiation shall appear in the namespace where
5211 // its template is declared or, if that namespace is inline (7.3.1), any
5212 // namespace from its enclosing namespace set.
5213 if (WasQualifiedName)
Douglas Gregor669eed82010-07-13 00:10:04 +00005214 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005215
5216 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor669eed82010-07-13 00:10:04 +00005217 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005218
Douglas Gregor2166beb2010-05-11 17:39:34 +00005219 S.Diag(InstLoc,
5220 S.getLangOptions().CPlusPlus0x?
5221 diag::err_explicit_instantiation_unqualified_wrong_namespace
5222 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl7a126a42010-08-31 00:36:30 +00005223 << D << OrigContext;
Douglas Gregor558c0322009-10-14 23:41:34 +00005224 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00005225 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00005226}
5227
5228/// \brief Determine whether the given scope specifier has a template-id in it.
5229static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
5230 if (!SS.isSet())
5231 return false;
5232
5233 // C++0x [temp.explicit]p2:
5234 // If the explicit instantiation is for a member function, a member class
5235 // or a static data member of a class template specialization, the name of
5236 // the class template specialization in the qualified-id for the member
5237 // name shall be a simple-template-id.
5238 //
5239 // C++98 has the same restriction, just worded differently.
5240 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
5241 NNS; NNS = NNS->getPrefix())
John McCallf4c73712011-01-19 06:33:43 +00005242 if (const Type *T = NNS->getAsType())
Douglas Gregor558c0322009-10-14 23:41:34 +00005243 if (isa<TemplateSpecializationType>(T))
5244 return true;
5245
5246 return false;
5247}
5248
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005249// Explicit instantiation of a class template specialization
John McCallf312b1e2010-08-26 23:41:50 +00005250DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005251Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005252 SourceLocation ExternLoc,
5253 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005254 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005255 SourceLocation KWLoc,
5256 const CXXScopeSpec &SS,
5257 TemplateTy TemplateD,
5258 SourceLocation TemplateNameLoc,
5259 SourceLocation LAngleLoc,
5260 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005261 SourceLocation RAngleLoc,
5262 AttributeList *Attr) {
5263 // Find the class template we're specializing
5264 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00005265 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005266 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
5267
5268 // Check that the specialization uses the same tag kind as the
5269 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005270 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5271 assert(Kind != TTK_Enum &&
5272 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005273 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00005274 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005275 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005276 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005277 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00005278 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005279 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00005280 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005281 diag::note_previous_use);
5282 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5283 }
5284
Douglas Gregor558c0322009-10-14 23:41:34 +00005285 // C++0x [temp.explicit]p2:
5286 // There are two forms of explicit instantiation: an explicit instantiation
5287 // definition and an explicit instantiation declaration. An explicit
5288 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00005289 TemplateSpecializationKind TSK
5290 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5291 : TSK_ExplicitInstantiationDeclaration;
5292
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005293 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00005294 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00005295 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005296
5297 // Check that the template argument list is well-formed for this
5298 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00005299 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00005300 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5301 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005302 return true;
5303
Douglas Gregor910f8002010-11-07 23:05:16 +00005304 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005305 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00005306
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005307 // Find the class template specialization declaration that
5308 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005309 void *InsertPos = 0;
5310 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00005311 = ClassTemplate->findSpecialization(Converted.data(),
5312 Converted.size(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005313
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005314 TemplateSpecializationKind PrevDecl_TSK
5315 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5316
Douglas Gregord5cb8762009-10-07 00:13:32 +00005317 // C++0x [temp.explicit]p2:
5318 // [...] An explicit instantiation shall appear in an enclosing
5319 // namespace of its template. [...]
5320 //
5321 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00005322 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5323 SS.isSet()))
5324 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00005325
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005326 ClassTemplateSpecializationDecl *Specialization = 0;
5327
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005328 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005329 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00005330 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005331 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005332 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005333 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00005334 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005335
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005336 // Even though HasNoEffect == true means that this explicit instantiation
5337 // has no effect on semantics, we go on to put its syntax in the AST.
5338
5339 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5340 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00005341 // Since the only prior class template specialization with these
5342 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005343 // declaration node as our own, updating the source location
5344 // for the template name to reflect our new declaration.
5345 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00005346 Specialization = PrevDecl;
5347 Specialization->setLocation(TemplateNameLoc);
5348 PrevDecl = 0;
5349 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005350 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005351
Douglas Gregor52604ab2009-09-11 21:19:12 +00005352 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005353 // Create a new class template specialization declaration node for
5354 // this explicit specialization.
5355 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00005356 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005357 ClassTemplate->getDeclContext(),
5358 TemplateNameLoc,
5359 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005360 Converted.data(),
5361 Converted.size(),
5362 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00005363 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005364
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005365 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005366 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005367 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005368 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005369 }
5370
5371 // Build the fully-sugared type for this explicit instantiation as
5372 // the user wrote in the explicit instantiation itself. This means
5373 // that we'll pretty-print the type retrieved from the
5374 // specialization's declaration the way that the user actually wrote
5375 // the explicit instantiation, rather than formatting the name based
5376 // on the "canonical" representation used to store the template
5377 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00005378 TypeSourceInfo *WrittenTy
5379 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5380 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005381 Context.getTypeDeclType(Specialization));
5382 Specialization->setTypeAsWritten(WrittenTy);
5383 TemplateArgsIn.release();
5384
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005385 // Set source locations for keywords.
5386 Specialization->setExternLoc(ExternLoc);
5387 Specialization->setTemplateKeywordLoc(TemplateLoc);
5388
5389 // Add the explicit instantiation into its lexical context. However,
5390 // since explicit instantiations are never found by name lookup, we
5391 // just put it into the declaration context directly.
5392 Specialization->setLexicalDeclContext(CurContext);
5393 CurContext->addDecl(Specialization);
5394
5395 // Syntax is now OK, so return if it has no other effect on semantics.
5396 if (HasNoEffect) {
5397 // Set the template specialization kind.
5398 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005399 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00005400 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005401
5402 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005403 // A definition of a class template or class member template
5404 // shall be in scope at the point of the explicit instantiation of
5405 // the class template or class member template.
5406 //
5407 // This check comes when we actually try to perform the
5408 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005409 ClassTemplateSpecializationDecl *Def
5410 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005411 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005412 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005413 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005414 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005415 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005416 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5417 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005418
Douglas Gregor0d035142009-10-27 18:42:08 +00005419 // Instantiate the members of this class template specialization.
5420 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005421 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005422 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00005423 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5424
5425 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5426 // TSK_ExplicitInstantiationDefinition
5427 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5428 TSK == TSK_ExplicitInstantiationDefinition)
5429 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005430
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005431 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005432 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005433
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005434 // Set the template specialization kind.
5435 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005436 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005437}
5438
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005439// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00005440DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005441Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005442 SourceLocation ExternLoc,
5443 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005444 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005445 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005446 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005447 IdentifierInfo *Name,
5448 SourceLocation NameLoc,
5449 AttributeList *Attr) {
5450
Douglas Gregor402abb52009-05-28 23:31:59 +00005451 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00005452 bool IsDependent = false;
John McCallf312b1e2010-08-26 23:41:50 +00005453 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCalld226f652010-08-21 09:40:31 +00005454 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5455 MultiTemplateParamsArg(*this, 0, 0),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00005456 Owned, IsDependent, false, false,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005457 TypeResult());
John McCallc4e70192009-09-11 04:59:25 +00005458 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5459
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005460 if (!TagD)
5461 return true;
5462
John McCalld226f652010-08-21 09:40:31 +00005463 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005464 if (Tag->isEnum()) {
5465 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5466 << Context.getTypeDeclType(Tag);
5467 return true;
5468 }
5469
Douglas Gregord0c87372009-05-27 17:30:49 +00005470 if (Tag->isInvalidDecl())
5471 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00005472
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005473 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5474 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5475 if (!Pattern) {
5476 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5477 << Context.getTypeDeclType(Record);
5478 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5479 return true;
5480 }
5481
Douglas Gregor558c0322009-10-14 23:41:34 +00005482 // C++0x [temp.explicit]p2:
5483 // If the explicit instantiation is for a class or member class, the
5484 // elaborated-type-specifier in the declaration shall include a
5485 // simple-template-id.
5486 //
5487 // C++98 has the same restriction, just worded differently.
5488 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00005489 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005490 << Record << SS.getRange();
5491
5492 // C++0x [temp.explicit]p2:
5493 // There are two forms of explicit instantiation: an explicit instantiation
5494 // definition and an explicit instantiation declaration. An explicit
5495 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00005496 TemplateSpecializationKind TSK
5497 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5498 : TSK_ExplicitInstantiationDeclaration;
5499
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005500 // C++0x [temp.explicit]p2:
5501 // [...] An explicit instantiation shall appear in an enclosing
5502 // namespace of its template. [...]
5503 //
5504 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00005505 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00005506
5507 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00005508 CXXRecordDecl *PrevDecl
5509 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00005510 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00005511 PrevDecl = Record;
5512 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00005513 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005514 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00005515 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00005516 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00005517 PrevDecl,
5518 MSInfo->getTemplateSpecializationKind(),
5519 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005520 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005521 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005522 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00005523 return TagD;
5524 }
5525
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005526 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00005527 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005528 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005529 // C++ [temp.explicit]p3:
5530 // A definition of a member class of a class template shall be in scope
5531 // at the point of an explicit instantiation of the member class.
5532 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00005533 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005534 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00005535 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5536 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005537 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5538 << Pattern;
5539 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00005540 } else {
5541 if (InstantiateClass(NameLoc, Record, Def,
5542 getTemplateInstantiationArgs(Record),
5543 TSK))
5544 return true;
5545
Douglas Gregor952b0172010-02-11 01:04:33 +00005546 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00005547 if (!RecordDef)
5548 return true;
5549 }
5550 }
5551
5552 // Instantiate all of the members of the class.
5553 InstantiateClassMembers(NameLoc, RecordDef,
5554 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005555
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005556 if (TSK == TSK_ExplicitInstantiationDefinition)
5557 MarkVTableUsed(NameLoc, RecordDef, true);
5558
Mike Stump390b4cc2009-05-16 07:39:55 +00005559 // FIXME: We don't have any representation for explicit instantiations of
5560 // member classes. Such a representation is not needed for compilation, but it
5561 // should be available for clients that want to see all of the declarations in
5562 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005563 return TagD;
5564}
5565
John McCallf312b1e2010-08-26 23:41:50 +00005566DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5567 SourceLocation ExternLoc,
5568 SourceLocation TemplateLoc,
5569 Declarator &D) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005570 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00005571 // TODO: check if/when DNInfo should replace Name.
5572 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5573 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005574 if (!Name) {
5575 if (!D.isInvalidType())
5576 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5577 diag::err_explicit_instantiation_requires_name)
5578 << D.getDeclSpec().getSourceRange()
5579 << D.getSourceRange();
5580
5581 return true;
5582 }
5583
5584 // The scope passed in may not be a decl scope. Zip up the scope tree until
5585 // we find one that is.
5586 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5587 (S->getFlags() & Scope::TemplateParamScope) != 0)
5588 S = S->getParent();
5589
5590 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00005591 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5592 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005593 if (R.isNull())
5594 return true;
5595
5596 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5597 // Cannot explicitly instantiate a typedef.
5598 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5599 << Name;
5600 return true;
5601 }
5602
Douglas Gregor663b5a02009-10-14 20:14:33 +00005603 // C++0x [temp.explicit]p1:
5604 // [...] An explicit instantiation of a function template shall not use the
5605 // inline or constexpr specifiers.
5606 // Presumably, this also applies to member functions of class templates as
5607 // well.
5608 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5609 Diag(D.getDeclSpec().getInlineSpecLoc(),
5610 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00005611 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00005612
5613 // FIXME: check for constexpr specifier.
5614
Douglas Gregor558c0322009-10-14 23:41:34 +00005615 // C++0x [temp.explicit]p2:
5616 // There are two forms of explicit instantiation: an explicit instantiation
5617 // definition and an explicit instantiation declaration. An explicit
5618 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00005619 TemplateSpecializationKind TSK
5620 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5621 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00005622
Abramo Bagnara25777432010-08-11 22:01:17 +00005623 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005624 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005625
5626 if (!R->isFunctionType()) {
5627 // C++ [temp.explicit]p1:
5628 // A [...] static data member of a class template can be explicitly
5629 // instantiated from the member definition associated with its class
5630 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00005631 if (Previous.isAmbiguous())
5632 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005633
John McCall1bcee0a2009-12-02 08:25:40 +00005634 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005635 if (!Prev || !Prev->isStaticDataMember()) {
5636 // We expect to see a data data member here.
5637 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5638 << Name;
5639 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5640 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00005641 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005642 return true;
5643 }
5644
5645 if (!Prev->getInstantiatedFromStaticDataMember()) {
5646 // FIXME: Check for explicit specialization?
5647 Diag(D.getIdentifierLoc(),
5648 diag::err_explicit_instantiation_data_member_not_instantiated)
5649 << Prev;
5650 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5651 // FIXME: Can we provide a note showing where this was declared?
5652 return true;
5653 }
5654
Douglas Gregor558c0322009-10-14 23:41:34 +00005655 // C++0x [temp.explicit]p2:
5656 // If the explicit instantiation is for a member function, a member class
5657 // or a static data member of a class template specialization, the name of
5658 // the class template specialization in the qualified-id for the member
5659 // name shall be a simple-template-id.
5660 //
5661 // C++98 has the same restriction, just worded differently.
5662 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5663 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005664 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005665 << Prev << D.getCXXScopeSpec().getRange();
5666
5667 // Check the scope of this explicit instantiation.
5668 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5669
Douglas Gregor454885e2009-10-15 15:54:05 +00005670 // Verify that it is okay to explicitly instantiate here.
5671 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5672 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005673 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005674 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005675 MSInfo->getTemplateSpecializationKind(),
5676 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005677 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005678 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005679 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005680 return (Decl*) 0;
Douglas Gregor454885e2009-10-15 15:54:05 +00005681
Douglas Gregord5a423b2009-09-25 18:43:00 +00005682 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005683 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005684 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005685 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005686
5687 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00005688 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005689 }
5690
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005691 // If the declarator is a template-id, translate the parser's template
5692 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005693 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005694 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005695 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5696 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005697 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5698 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005699 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5700 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005701 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005702 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005703 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005704 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005705 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005706
Douglas Gregord5a423b2009-09-25 18:43:00 +00005707 // C++ [temp.explicit]p1:
5708 // A [...] function [...] can be explicitly instantiated from its template.
5709 // A member function [...] of a class template can be explicitly
5710 // instantiated from the member definition associated with its class
5711 // template.
John McCallc373d482010-01-27 01:50:18 +00005712 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005713 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5714 P != PEnd; ++P) {
5715 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005716 if (!HasExplicitTemplateArgs) {
5717 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5718 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5719 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005720
John McCallc373d482010-01-27 01:50:18 +00005721 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005722 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5723 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005724 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005725 }
5726 }
5727
5728 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5729 if (!FunTmpl)
5730 continue;
5731
John McCall5769d612010-02-08 23:07:23 +00005732 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005733 FunctionDecl *Specialization = 0;
5734 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005735 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005736 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005737 R, Specialization, Info)) {
5738 // FIXME: Keep track of almost-matches?
5739 (void)TDK;
5740 continue;
5741 }
5742
John McCallc373d482010-01-27 01:50:18 +00005743 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005744 }
5745
5746 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005747 UnresolvedSetIterator Result
Douglas Gregor5c7bf422011-01-11 17:34:58 +00005748 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005749 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005750 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5751 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5752 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005753
John McCallc373d482010-01-27 01:50:18 +00005754 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005755 return true;
John McCallc373d482010-01-27 01:50:18 +00005756
5757 // Ignore access control bits, we don't need them for redeclaration checking.
5758 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005759
Douglas Gregor0a897e32009-10-15 17:21:20 +00005760 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005761 Diag(D.getIdentifierLoc(),
5762 diag::err_explicit_instantiation_member_function_not_instantiated)
5763 << Specialization
5764 << (Specialization->getTemplateSpecializationKind() ==
5765 TSK_ExplicitSpecialization);
5766 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5767 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005768 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005769
Douglas Gregor0a897e32009-10-15 17:21:20 +00005770 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005771 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5772 PrevDecl = Specialization;
5773
Douglas Gregor0a897e32009-10-15 17:21:20 +00005774 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005775 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005776 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005777 PrevDecl,
5778 PrevDecl->getTemplateSpecializationKind(),
5779 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005780 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00005781 return true;
5782
5783 // FIXME: We may still want to build some representation of this
5784 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005785 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005786 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005787 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005788
5789 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005790
5791 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005792 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005793
Douglas Gregor558c0322009-10-14 23:41:34 +00005794 // C++0x [temp.explicit]p2:
5795 // If the explicit instantiation is for a member function, a member class
5796 // or a static data member of a class template specialization, the name of
5797 // the class template specialization in the qualified-id for the member
5798 // name shall be a simple-template-id.
5799 //
5800 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005801 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005802 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005803 D.getCXXScopeSpec().isSet() &&
5804 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5805 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005806 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005807 << Specialization << D.getCXXScopeSpec().getRange();
5808
5809 CheckExplicitInstantiationScope(*this,
5810 FunTmpl? (NamedDecl *)FunTmpl
5811 : Specialization->getInstantiatedFromMemberFunction(),
5812 D.getIdentifierLoc(),
5813 D.getCXXScopeSpec().isSet());
5814
Douglas Gregord5a423b2009-09-25 18:43:00 +00005815 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00005816 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005817}
5818
John McCallf312b1e2010-08-26 23:41:50 +00005819TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005820Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5821 const CXXScopeSpec &SS, IdentifierInfo *Name,
5822 SourceLocation TagLoc, SourceLocation NameLoc) {
5823 // This has to hold, because SS is expected to be defined.
5824 assert(Name && "Expected a name in a dependent tag");
5825
5826 NestedNameSpecifier *NNS
5827 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5828 if (!NNS)
5829 return true;
5830
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005831 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005832
Douglas Gregor48c89f42010-04-24 16:38:41 +00005833 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5834 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005835 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005836 return true;
5837 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005838
5839 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallb3d87482010-08-24 05:47:05 +00005840 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCallc4e70192009-09-11 04:59:25 +00005841}
5842
John McCallf312b1e2010-08-26 23:41:50 +00005843TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005844Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5845 const CXXScopeSpec &SS, const IdentifierInfo &II,
5846 SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005847 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005848 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5849 if (!NNS)
5850 return true;
5851
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005852 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5853 !getLangOptions().CPlusPlus0x)
5854 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5855 << FixItHint::CreateRemoval(TypenameLoc);
5856
Douglas Gregor107de902010-04-24 15:35:55 +00005857 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005858 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005859 if (T.isNull())
5860 return true;
John McCall63b43852010-04-29 23:50:39 +00005861
5862 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5863 if (isa<DependentNameType>(T)) {
5864 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005865 TL.setKeywordLoc(TypenameLoc);
5866 TL.setQualifierRange(SS.getRange());
5867 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005868 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005869 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005870 TL.setKeywordLoc(TypenameLoc);
5871 TL.setQualifierRange(SS.getRange());
5872 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005873 }
5874
John McCallb3d87482010-08-24 05:47:05 +00005875 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00005876}
5877
John McCallf312b1e2010-08-26 23:41:50 +00005878TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005879Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5880 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallb3d87482010-08-24 05:47:05 +00005881 ParsedType Ty) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005882 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5883 !getLangOptions().CPlusPlus0x)
5884 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5885 << FixItHint::CreateRemoval(TypenameLoc);
5886
John McCall4e449832010-05-28 23:32:21 +00005887 TypeSourceInfo *InnerTSI = 0;
5888 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCall4e449832010-05-28 23:32:21 +00005889
5890 assert(isa<TemplateSpecializationType>(T) &&
5891 "Expected a template specialization type");
Douglas Gregor17343172009-04-01 00:28:59 +00005892
Douglas Gregor6946baf2009-09-02 13:05:45 +00005893 if (computeDeclContext(SS, false)) {
5894 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005895 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005896 // track of the nested-name-specifier.
John McCall4e449832010-05-28 23:32:21 +00005897
5898 // Push the inner type, preserving its source locations if possible.
5899 TypeLocBuilder Builder;
5900 if (InnerTSI)
5901 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5902 else
5903 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5904
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005905 /* Note: NNS already embedded in template specialization type T. */
5906 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCall4e449832010-05-28 23:32:21 +00005907 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5908 TL.setKeywordLoc(TypenameLoc);
5909 TL.setQualifierRange(SS.getRange());
5910
5911 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallb3d87482010-08-24 05:47:05 +00005912 return CreateParsedType(T, TSI);
Douglas Gregor6946baf2009-09-02 13:05:45 +00005913 }
Mike Stump1eb44332009-09-09 15:08:12 +00005914
John McCall33500952010-06-11 00:33:02 +00005915 // TODO: it's really silly that we make a template specialization
5916 // type earlier only to drop it again here.
John McCallf4c73712011-01-19 06:33:43 +00005917 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
John McCall33500952010-06-11 00:33:02 +00005918 DependentTemplateName *DTN =
5919 TST->getTemplateName().getAsDependentTemplateName();
5920 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005921 assert(DTN->getQualifier()
5922 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5923 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5924 DTN->getQualifier(),
John McCall33500952010-06-11 00:33:02 +00005925 DTN->getIdentifier(),
5926 TST->getNumArgs(),
5927 TST->getArgs());
John McCall63b43852010-04-29 23:50:39 +00005928 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCall33500952010-06-11 00:33:02 +00005929 DependentTemplateSpecializationTypeLoc TL =
5930 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5931 if (InnerTSI) {
5932 TemplateSpecializationTypeLoc TSTL =
5933 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5934 TL.setLAngleLoc(TSTL.getLAngleLoc());
5935 TL.setRAngleLoc(TSTL.getRAngleLoc());
5936 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5937 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5938 } else {
5939 TL.initializeLocal(SourceLocation());
5940 }
John McCall4e449832010-05-28 23:32:21 +00005941 TL.setKeywordLoc(TypenameLoc);
5942 TL.setQualifierRange(SS.getRange());
John McCallb3d87482010-08-24 05:47:05 +00005943 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00005944}
5945
Douglas Gregord57959a2009-03-27 23:10:48 +00005946/// \brief Build the type that describes a C++ typename specifier,
5947/// e.g., "typename T::type".
5948QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005949Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5950 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005951 SourceLocation KeywordLoc, SourceRange NNSRange,
5952 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005953 CXXScopeSpec SS;
5954 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005955 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005956
John McCall77bb1aa2010-05-01 00:40:08 +00005957 DeclContext *Ctx = computeDeclContext(SS);
5958 if (!Ctx) {
5959 // If the nested-name-specifier is dependent and couldn't be
5960 // resolved to a type, build a typename type.
5961 assert(NNS->isDependent());
5962 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005963 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005964
John McCall77bb1aa2010-05-01 00:40:08 +00005965 // If the nested-name-specifier refers to the current instantiation,
5966 // the "typename" keyword itself is superfluous. In C++03, the
5967 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5968 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00005969 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005970
John McCall77bb1aa2010-05-01 00:40:08 +00005971 if (RequireCompleteDeclContext(SS, Ctx))
5972 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005973
5974 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005975 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005976 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005977 unsigned DiagID = 0;
5978 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005979 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005980 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005981 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005982 break;
Douglas Gregord9545042010-12-09 00:06:27 +00005983
5984 case LookupResult::FoundUnresolvedValue: {
5985 // We found a using declaration that is a value. Most likely, the using
5986 // declaration itself is meant to have the 'typename' keyword.
5987 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5988 IILoc);
5989 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
5990 << Name << Ctx << FullRange;
5991 if (UnresolvedUsingValueDecl *Using
5992 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
5993 SourceLocation Loc = Using->getTargetNestedNameRange().getBegin();
5994 Diag(Loc, diag::note_using_value_decl_missing_typename)
5995 << FixItHint::CreateInsertion(Loc, "typename ");
5996 }
5997 }
5998 // Fall through to create a dependent typename type, from which we can recover
5999 // better.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00006000
6001 case LookupResult::NotFoundInCurrentInstantiation:
6002 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00006003 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00006004
6005 case LookupResult::Found:
Douglas Gregor1a15dae2010-06-16 22:31:08 +00006006 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006007 // We found a type. Build an ElaboratedType, since the
6008 // typename-specifier was just sugar.
6009 return Context.getElaboratedType(ETK_Typename, NNS,
6010 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00006011 }
6012
6013 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00006014 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00006015 break;
6016
Douglas Gregord9545042010-12-09 00:06:27 +00006017
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00006018 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00006019 return QualType();
6020
Douglas Gregord57959a2009-03-27 23:10:48 +00006021 case LookupResult::FoundOverloaded:
6022 DiagID = diag::err_typename_nested_not_type;
6023 Referenced = *Result.begin();
6024 break;
6025
John McCall6e247262009-10-10 05:48:19 +00006026 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00006027 return QualType();
6028 }
6029
6030 // If we get here, it's because name lookup did not find a
6031 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00006032 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
6033 IILoc);
6034 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00006035 if (Referenced)
6036 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
6037 << Name;
6038 return QualType();
6039}
Douglas Gregor4a959d82009-08-06 16:20:37 +00006040
6041namespace {
6042 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00006043 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00006044 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00006045 SourceLocation Loc;
6046 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00006047
Douglas Gregor4a959d82009-08-06 16:20:37 +00006048 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00006049 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
6050
Mike Stump1eb44332009-09-09 15:08:12 +00006051 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00006052 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00006053 DeclarationName Entity)
6054 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00006055 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00006056
6057 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00006058 /// transformed.
6059 ///
6060 /// For the purposes of type reconstruction, a type has already been
6061 /// transformed if it is NULL or if it is not dependent.
6062 bool AlreadyTransformed(QualType T) {
6063 return T.isNull() || !T->isDependentType();
6064 }
Mike Stump1eb44332009-09-09 15:08:12 +00006065
6066 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00006067 /// rebuilt.
6068 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00006069
Douglas Gregor4a959d82009-08-06 16:20:37 +00006070 /// \brief Returns the name of the entity whose type is being rebuilt.
6071 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00006072
Douglas Gregor972e6ce2009-10-27 06:26:26 +00006073 /// \brief Sets the "base" location and entity when that
6074 /// information is known based on another transformation.
6075 void setBase(SourceLocation Loc, DeclarationName Entity) {
6076 this->Loc = Loc;
6077 this->Entity = Entity;
6078 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00006079 };
6080}
6081
Douglas Gregor4a959d82009-08-06 16:20:37 +00006082/// \brief Rebuilds a type within the context of the current instantiation.
6083///
Mike Stump1eb44332009-09-09 15:08:12 +00006084/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00006085/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00006086/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00006087/// partial specialization thereof). This routine will rebuild that type now
6088/// that we have entered the declarator's scope, which may produce different
6089/// canonical types, e.g.,
6090///
6091/// \code
6092/// template<typename T>
6093/// struct X {
6094/// typedef T* pointer;
6095/// pointer data();
6096/// };
6097///
6098/// template<typename T>
6099/// typename X<T>::pointer X<T>::data() { ... }
6100/// \endcode
6101///
Douglas Gregor4714c122010-03-31 17:34:00 +00006102/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00006103/// since we do not know that we can look into X<T> when we parsed the type.
6104/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006105/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00006106/// as the canonical type of T*, allowing the return types of the out-of-line
6107/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00006108TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6109 SourceLocation Loc,
6110 DeclarationName Name) {
6111 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00006112 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00006113
Douglas Gregor4a959d82009-08-06 16:20:37 +00006114 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
6115 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00006116}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006117
John McCall60d7b3a2010-08-24 06:29:42 +00006118ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00006119 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
6120 DeclarationName());
6121 return Rebuilder.TransformExpr(E);
6122}
6123
John McCall63b43852010-04-29 23:50:39 +00006124bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
6125 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00006126
6127 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6128 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
6129 DeclarationName());
6130 NestedNameSpecifier *Rebuilt =
6131 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00006132 if (!Rebuilt) return true;
6133
6134 SS.setScopeRep(Rebuilt);
6135 return false;
John McCall31f17ec2010-04-27 00:57:59 +00006136}
6137
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006138/// \brief Produces a formatted string that describes the binding of
6139/// template parameters to template arguments.
6140std::string
6141Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6142 const TemplateArgumentList &Args) {
Douglas Gregor910f8002010-11-07 23:05:16 +00006143 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006144}
6145
6146std::string
6147Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6148 const TemplateArgument *Args,
6149 unsigned NumArgs) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006150 llvm::SmallString<128> Str;
6151 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006152
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006153 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00006154 return std::string();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006155
6156 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00006157 if (I >= NumArgs)
6158 break;
6159
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006160 if (I == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00006161 Out << "[with ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006162 else
Douglas Gregor87dd6972010-12-20 16:52:59 +00006163 Out << ", ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006164
6165 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006166 Out << Id->getName();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006167 } else {
Douglas Gregor87dd6972010-12-20 16:52:59 +00006168 Out << '$' << I;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006169 }
6170
Douglas Gregor87dd6972010-12-20 16:52:59 +00006171 Out << " = ";
6172 Args[I].print(Context.PrintingPolicy, Out);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006173 }
Douglas Gregor87dd6972010-12-20 16:52:59 +00006174
6175 Out << ']';
6176 return Out.str();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00006177}