blob: 9d7dd0a056944772206a71b88a1930969c835db0 [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-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 Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000020#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000021#include "llvm/Support/Compiler.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000022#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000023using namespace clang;
24
Douglas Gregorb7bfe792009-09-02 22:59:36 +000025/// \brief Determine whether the declaration found is acceptable as the name
26/// of a template and, if so, return that template declaration. Otherwise,
27/// returns NULL.
28static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
29 if (!D)
30 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000031
Douglas Gregorb7bfe792009-09-02 22:59:36 +000032 if (isa<TemplateDecl>(D))
33 return D;
Mike Stump11289f42009-09-09 15:08:12 +000034
Douglas Gregorb7bfe792009-09-02 22:59:36 +000035 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
36 // C++ [temp.local]p1:
37 // Like normal (non-template) classes, class templates have an
38 // injected-class-name (Clause 9). The injected-class-name
39 // can be used with or without a template-argument-list. When
40 // it is used without a template-argument-list, it is
41 // equivalent to the injected-class-name followed by the
42 // template-parameters of the class template enclosed in
43 // <>. When it is used with a template-argument-list, it
44 // refers to the specified class template specialization,
45 // which could be the current specialization or another
46 // specialization.
47 if (Record->isInjectedClassName()) {
48 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
49 if (Record->getDescribedClassTemplate())
50 return Record->getDescribedClassTemplate();
51
52 if (ClassTemplateSpecializationDecl *Spec
53 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
54 return Spec->getSpecializedTemplate();
55 }
Mike Stump11289f42009-09-09 15:08:12 +000056
Douglas Gregorb7bfe792009-09-02 22:59:36 +000057 return 0;
58 }
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregorb7bfe792009-09-02 22:59:36 +000060 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
61 if (!Ovl)
62 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000063
Douglas Gregorb7bfe792009-09-02 22:59:36 +000064 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
65 FEnd = Ovl->function_end();
66 F != FEnd; ++F) {
67 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
68 // We've found a function template. Determine whether there are
69 // any other function templates we need to bundle together in an
70 // OverloadedFunctionDecl
71 for (++F; F != FEnd; ++F) {
72 if (isa<FunctionTemplateDecl>(*F))
73 break;
74 }
Mike Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregorb7bfe792009-09-02 22:59:36 +000076 if (F != FEnd) {
77 // Build an overloaded function decl containing only the
78 // function templates in Ovl.
Mike Stump11289f42009-09-09 15:08:12 +000079 OverloadedFunctionDecl *OvlTemplate
Douglas Gregorb7bfe792009-09-02 22:59:36 +000080 = OverloadedFunctionDecl::Create(Context,
81 Ovl->getDeclContext(),
82 Ovl->getDeclName());
83 OvlTemplate->addOverload(FuncTmpl);
84 OvlTemplate->addOverload(*F);
85 for (++F; F != FEnd; ++F) {
86 if (isa<FunctionTemplateDecl>(*F))
87 OvlTemplate->addOverload(*F);
88 }
Mike Stump11289f42009-09-09 15:08:12 +000089
Douglas Gregorb7bfe792009-09-02 22:59:36 +000090 return OvlTemplate;
91 }
92
93 return FuncTmpl;
94 }
95 }
Mike Stump11289f42009-09-09 15:08:12 +000096
Douglas Gregorb7bfe792009-09-02 22:59:36 +000097 return 0;
98}
99
100TemplateNameKind Sema::isTemplateName(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +0000101 const IdentifierInfo &II,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000102 SourceLocation IdLoc,
Douglas Gregore861bac2009-08-25 22:51:20 +0000103 const CXXScopeSpec *SS,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000104 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000105 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000106 TemplateTy &TemplateResult) {
107 // Determine where to perform name lookup
108 DeclContext *LookupCtx = 0;
109 bool isDependent = false;
110 if (ObjectTypePtr) {
111 // This nested-name-specifier occurs in a member access expression, e.g.,
112 // x->B::f, and we are looking into the type of the object.
Mike Stump11289f42009-09-09 15:08:12 +0000113 assert((!SS || !SS->isSet()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000114 "ObjectType and scope specifier cannot coexist");
115 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
116 LookupCtx = computeDeclContext(ObjectType);
117 isDependent = ObjectType->isDependentType();
118 } else if (SS && SS->isSet()) {
119 // This nested-name-specifier occurs after another nested-name-specifier,
120 // so long into the context associated with the prior nested-name-specifier.
121
122 LookupCtx = computeDeclContext(*SS, EnteringContext);
123 isDependent = isDependentScopeSpecifier(*SS);
124 }
Mike Stump11289f42009-09-09 15:08:12 +0000125
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000126 LookupResult Found;
127 bool ObjectTypeSearchedInScope = false;
128 if (LookupCtx) {
129 // Perform "qualified" name lookup into the declaration context we
130 // computed, which is either the type of the base of a member access
Mike Stump11289f42009-09-09 15:08:12 +0000131 // expression or the declaration context associated with a prior
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000132 // nested-name-specifier.
133
134 // The declaration context must be complete.
135 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
136 return TNK_Non_template;
Mike Stump11289f42009-09-09 15:08:12 +0000137
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000138 Found = LookupQualifiedName(LookupCtx, &II, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +0000139
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000140 if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
141 // C++ [basic.lookup.classref]p1:
142 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump11289f42009-09-09 15:08:12 +0000143 // immediately followed by an identifier followed by a <, the
144 // identifier must be looked up to determine whether the < is the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000145 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump11289f42009-09-09 15:08:12 +0000146 // The identifier is first looked up in the class of the object
147 // expression. If the identifier is not found, it is then looked up in
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000148 // the context of the entire postfix-expression and shall name a class
149 // or function template.
150 //
151 // FIXME: When we're instantiating a template, do we actually have to
152 // look in the scope of the template? Seems fishy...
153 Found = LookupName(S, &II, LookupOrdinaryName);
154 ObjectTypeSearchedInScope = true;
155 }
156 } else if (isDependent) {
Mike Stump11289f42009-09-09 15:08:12 +0000157 // We cannot look into a dependent object type or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158 return TNK_Non_template;
159 } else {
160 // Perform unqualified name lookup in the current scope.
161 Found = LookupName(S, &II, LookupOrdinaryName);
162 }
Mike Stump11289f42009-09-09 15:08:12 +0000163
Douglas Gregore861bac2009-08-25 22:51:20 +0000164 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump11289f42009-09-09 15:08:12 +0000165 assert(!Found.isAmbiguous() &&
Douglas Gregore861bac2009-08-25 22:51:20 +0000166 "Cannot handle template name-lookup ambiguities");
Douglas Gregordc572a32009-03-30 22:58:21 +0000167
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000168 NamedDecl *Template = isAcceptableTemplateName(Context, Found);
169 if (!Template)
170 return TNK_Non_template;
171
172 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
173 // C++ [basic.lookup.classref]p1:
Mike Stump11289f42009-09-09 15:08:12 +0000174 // [...] If the lookup in the class of the object expression finds a
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000175 // template, the name is also looked up in the context of the entire
176 // postfix-expression and [...]
177 //
178 LookupResult FoundOuter = LookupName(S, &II, LookupOrdinaryName);
179 // FIXME: Handle ambiguities in this lookup better
180 NamedDecl *OuterTemplate = isAcceptableTemplateName(Context, FoundOuter);
Mike Stump11289f42009-09-09 15:08:12 +0000181
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000182 if (!OuterTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +0000183 // - if the name is not found, the name found in the class of the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000184 // object expression is used, otherwise
185 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump11289f42009-09-09 15:08:12 +0000186 // - if the name is found in the context of the entire
187 // postfix-expression and does not name a class template, the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000188 // found in the class of the object expression is used, otherwise
189 } else {
190 // - if the name found is a class template, it must refer to the same
Mike Stump11289f42009-09-09 15:08:12 +0000191 // entity as the one found in the class of the object expression,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000192 // otherwise the program is ill-formed.
193 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
194 Diag(IdLoc, diag::err_nested_name_member_ref_lookup_ambiguous)
195 << &II;
196 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
197 << QualType::getFromOpaquePtr(ObjectTypePtr);
198 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump11289f42009-09-09 15:08:12 +0000199
200 // Recover by taking the template that we found in the object
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000201 // expression's type.
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000202 }
Mike Stump11289f42009-09-09 15:08:12 +0000203 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000204 }
Mike Stump11289f42009-09-09 15:08:12 +0000205
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000206 if (SS && SS->isSet() && !SS->isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000207 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000208 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000209 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000210 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000211 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000212 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
213 Ovl));
214 else
Mike Stump11289f42009-09-09 15:08:12 +0000215 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000216 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000217 cast<TemplateDecl>(Template)));
218 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000219 = dyn_cast<OverloadedFunctionDecl>(Template)) {
220 TemplateResult = TemplateTy::make(TemplateName(Ovl));
221 } else {
222 TemplateResult = TemplateTy::make(
223 TemplateName(cast<TemplateDecl>(Template)));
224 }
Mike Stump11289f42009-09-09 15:08:12 +0000225
226 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000227 isa<TemplateTemplateParmDecl>(Template))
228 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000229
230 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000231 isa<OverloadedFunctionDecl>(Template)) &&
232 "Unhandled template kind in Sema::isTemplateName");
233 return TNK_Function_template;
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000234}
235
Douglas Gregor5101c242008-12-05 18:15:24 +0000236/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
237/// that the template parameter 'PrevDecl' is being shadowed by a new
238/// declaration at location Loc. Returns true to indicate that this is
239/// an error, and false otherwise.
240bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000241 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000242
243 // Microsoft Visual C++ permits template parameters to be shadowed.
244 if (getLangOptions().Microsoft)
245 return false;
246
247 // C++ [temp.local]p4:
248 // A template-parameter shall not be redeclared within its
249 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000250 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000251 << cast<NamedDecl>(PrevDecl)->getDeclName();
252 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
253 return true;
254}
255
Douglas Gregor463421d2009-03-03 04:44:36 +0000256/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000257/// the parameter D to reference the templated declaration and return a pointer
258/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000259TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000260 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000261 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000262 return Temp;
263 }
264 return 0;
265}
266
Douglas Gregor5101c242008-12-05 18:15:24 +0000267/// ActOnTypeParameter - Called when a C++ template type parameter
268/// (e.g., "typename T") has been parsed. Typename specifies whether
269/// the keyword "typename" was used to declare the type parameter
270/// (otherwise, "class" was used), and KeyLoc is the location of the
271/// "class" or "typename" keyword. ParamName is the name of the
272/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000273/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000274/// If the type parameter has a default argument, it will be added
275/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000276Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000277 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000278 SourceLocation KeyLoc,
279 IdentifierInfo *ParamName,
280 SourceLocation ParamNameLoc,
281 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000282 assert(S->isTemplateParamScope() &&
283 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000284 bool Invalid = false;
285
286 if (ParamName) {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000287 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000288 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000289 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000290 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000291 }
292
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000293 SourceLocation Loc = ParamNameLoc;
294 if (!ParamName)
295 Loc = KeyLoc;
296
Douglas Gregor5101c242008-12-05 18:15:24 +0000297 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000298 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
299 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000300 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000301 if (Invalid)
302 Param->setInvalidDecl();
303
304 if (ParamName) {
305 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000306 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000307 IdResolver.AddDecl(Param);
308 }
309
Chris Lattner83f095c2009-03-28 19:18:32 +0000310 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000311}
312
Douglas Gregordba32632009-02-10 19:49:53 +0000313/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000314/// Default) to the given template type parameter (TypeParam).
315void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000316 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000317 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000318 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000319 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000320 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000321 // FIXME: Preserve type source info.
322 QualType Default = GetTypeFromParser(DefaultT);
Douglas Gregordba32632009-02-10 19:49:53 +0000323
Anders Carlssond3824352009-06-12 22:30:13 +0000324 // C++0x [temp.param]p9:
325 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000326 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000327 if (Parm->isParameterPack()) {
328 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000329 return;
330 }
Mike Stump11289f42009-09-09 15:08:12 +0000331
Douglas Gregordba32632009-02-10 19:49:53 +0000332 // C++ [temp.param]p14:
333 // A template-parameter shall not be used in its own default argument.
334 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000335
Douglas Gregordba32632009-02-10 19:49:53 +0000336 // Check the template argument itself.
337 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
338 Parm->setInvalidDecl();
339 return;
340 }
341
342 Parm->setDefaultArgument(Default, DefaultLoc, false);
343}
344
Douglas Gregor463421d2009-03-03 04:44:36 +0000345/// \brief Check that the type of a non-type template parameter is
346/// well-formed.
347///
348/// \returns the (possibly-promoted) parameter type if valid;
349/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000350QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000351Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
352 // C++ [temp.param]p4:
353 //
354 // A non-type template-parameter shall have one of the following
355 // (optionally cv-qualified) types:
356 //
357 // -- integral or enumeration type,
358 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000359 // -- pointer to object or pointer to function,
360 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000361 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
362 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000363 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000364 T->isReferenceType() ||
365 // -- pointer to member.
366 T->isMemberPointerType() ||
367 // If T is a dependent type, we can't do the check now, so we
368 // assume that it is well-formed.
369 T->isDependentType())
370 return T;
371 // C++ [temp.param]p8:
372 //
373 // A non-type template-parameter of type "array of T" or
374 // "function returning T" is adjusted to be of type "pointer to
375 // T" or "pointer to function returning T", respectively.
376 else if (T->isArrayType())
377 // FIXME: Keep the type prior to promotion?
378 return Context.getArrayDecayedType(T);
379 else if (T->isFunctionType())
380 // FIXME: Keep the type prior to promotion?
381 return Context.getPointerType(T);
382
383 Diag(Loc, diag::err_template_nontype_parm_bad_type)
384 << T;
385
386 return QualType();
387}
388
Douglas Gregor5101c242008-12-05 18:15:24 +0000389/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
390/// template parameter (e.g., "int Size" in "template<int Size>
391/// class Array") has been parsed. S is the current scope and D is
392/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000393Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000394 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000395 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000396 DeclaratorInfo *DInfo = 0;
397 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000398
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000399 assert(S->isTemplateParamScope() &&
400 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000401 bool Invalid = false;
402
403 IdentifierInfo *ParamName = D.getIdentifier();
404 if (ParamName) {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000405 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000406 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000407 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000408 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000409 }
410
Douglas Gregor463421d2009-03-03 04:44:36 +0000411 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000412 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000413 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000414 Invalid = true;
415 }
Douglas Gregor81338792009-02-10 17:43:50 +0000416
Douglas Gregor5101c242008-12-05 18:15:24 +0000417 NonTypeTemplateParmDecl *Param
418 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000419 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000420 if (Invalid)
421 Param->setInvalidDecl();
422
423 if (D.getIdentifier()) {
424 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000425 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000426 IdResolver.AddDecl(Param);
427 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000428 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000429}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000430
Douglas Gregordba32632009-02-10 19:49:53 +0000431/// \brief Adds a default argument to the given non-type template
432/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000433void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000434 SourceLocation EqualLoc,
435 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000436 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000437 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000438 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000439
Douglas Gregordba32632009-02-10 19:49:53 +0000440 // C++ [temp.param]p14:
441 // A template-parameter shall not be used in its own default argument.
442 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000443
Douglas Gregordba32632009-02-10 19:49:53 +0000444 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000445 TemplateArgument Converted;
446 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
447 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000448 TemplateParm->setInvalidDecl();
449 return;
450 }
451
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000452 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000453}
454
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000455
456/// ActOnTemplateTemplateParameter - Called when a C++ template template
457/// parameter (e.g. T in template <template <typename> class T> class array)
458/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000459Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
460 SourceLocation TmpLoc,
461 TemplateParamsTy *Params,
462 IdentifierInfo *Name,
463 SourceLocation NameLoc,
464 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000465 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000466 assert(S->isTemplateParamScope() &&
467 "Template template parameter not in template parameter scope!");
468
469 // Construct the parameter object.
470 TemplateTemplateParmDecl *Param =
471 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
472 Position, Name,
473 (TemplateParameterList*)Params);
474
475 // Make sure the parameter is valid.
476 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
477 // do anything yet. However, if the template parameter list or (eventual)
478 // default value is ever invalidated, that will propagate here.
479 bool Invalid = false;
480 if (Invalid) {
481 Param->setInvalidDecl();
482 }
483
484 // If the tt-param has a name, then link the identifier into the scope
485 // and lookup mechanisms.
486 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000487 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000488 IdResolver.AddDecl(Param);
489 }
490
Chris Lattner83f095c2009-03-28 19:18:32 +0000491 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000492}
493
Douglas Gregordba32632009-02-10 19:49:53 +0000494/// \brief Adds a default argument to the given template template
495/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000496void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000497 SourceLocation EqualLoc,
498 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000499 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000500 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000501
502 // Since a template-template parameter's default argument is an
503 // id-expression, it must be a DeclRefExpr.
Mike Stump11289f42009-09-09 15:08:12 +0000504 DeclRefExpr *Default
Douglas Gregordba32632009-02-10 19:49:53 +0000505 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
506
507 // C++ [temp.param]p14:
508 // A template-parameter shall not be used in its own default argument.
509 // FIXME: Implement this check! Needs a recursive walk over the types.
510
511 // Check the well-formedness of the template argument.
512 if (!isa<TemplateDecl>(Default->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +0000513 Diag(Default->getSourceRange().getBegin(),
Douglas Gregordba32632009-02-10 19:49:53 +0000514 diag::err_template_arg_must_be_template)
515 << Default->getSourceRange();
516 TemplateParm->setInvalidDecl();
517 return;
Mike Stump11289f42009-09-09 15:08:12 +0000518 }
Douglas Gregordba32632009-02-10 19:49:53 +0000519 if (CheckTemplateArgument(TemplateParm, Default)) {
520 TemplateParm->setInvalidDecl();
521 return;
522 }
523
524 DefaultE.release();
525 TemplateParm->setDefaultArgument(Default);
526}
527
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000528/// ActOnTemplateParameterList - Builds a TemplateParameterList that
529/// contains the template parameters in Params/NumParams.
530Sema::TemplateParamsTy *
531Sema::ActOnTemplateParameterList(unsigned Depth,
532 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000533 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000534 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000535 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000536 SourceLocation RAngleLoc) {
537 if (ExportLoc.isValid())
538 Diag(ExportLoc, diag::note_template_export_unsupported);
539
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000540 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000541 (NamedDecl**)Params, NumParams,
542 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000543}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000544
Douglas Gregorc08f4892009-03-25 00:13:59 +0000545Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000546Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000547 SourceLocation KWLoc, const CXXScopeSpec &SS,
548 IdentifierInfo *Name, SourceLocation NameLoc,
549 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000550 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000551 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000552 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000553 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000554 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000555 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000556
557 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000558 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000559 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000560
John McCall27b5c252009-09-14 21:59:20 +0000561 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
562 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000563
564 // There is no such thing as an unnamed class template.
565 if (!Name) {
566 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000567 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000568 }
569
570 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000571 DeclContext *SemanticContext;
572 LookupResult Previous;
573 if (SS.isNotEmpty() && !SS.isInvalid()) {
574 SemanticContext = computeDeclContext(SS, true);
575 if (!SemanticContext) {
576 // FIXME: Produce a reasonable diagnostic here
577 return true;
578 }
Mike Stump11289f42009-09-09 15:08:12 +0000579
580 Previous = LookupQualifiedName(SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000581 true);
582 } else {
583 SemanticContext = CurContext;
584 Previous = LookupName(S, Name, LookupOrdinaryName, true);
585 }
Mike Stump11289f42009-09-09 15:08:12 +0000586
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000587 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
588 NamedDecl *PrevDecl = 0;
589 if (Previous.begin() != Previous.end())
590 PrevDecl = *Previous.begin();
591
Douglas Gregor9acb6902009-09-26 07:05:09 +0000592 if (PrevDecl && TUK == TUK_Friend) {
593 // C++ [namespace.memdef]p3:
594 // [...] When looking for a prior declaration of a class or a function
595 // declared as a friend, and when the name of the friend class or
596 // function is neither a qualified name nor a template-id, scopes outside
597 // the innermost enclosing namespace scope are not considered.
598 DeclContext *OutermostContext = CurContext;
599 while (!OutermostContext->isFileContext())
600 OutermostContext = OutermostContext->getLookupParent();
601
602 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
603 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
604 SemanticContext = PrevDecl->getDeclContext();
605 } else {
606 // Declarations in outer scopes don't matter. However, the outermost
607 // context we computed is the semntic context for our new
608 // declaration.
609 PrevDecl = 0;
610 SemanticContext = OutermostContext;
611 }
612 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000613 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000614
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000615 // If there is a previous declaration with the same name, check
616 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000617 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000618 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
619 if (PrevClassTemplate) {
620 // Ensure that the template parameter lists are compatible.
621 if (!TemplateParameterListsAreEqual(TemplateParams,
622 PrevClassTemplate->getTemplateParameters(),
623 /*Complain=*/true))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000624 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000625
626 // C++ [temp.class]p4:
627 // In a redeclaration, partial specialization, explicit
628 // specialization or explicit instantiation of a class template,
629 // the class-key shall agree in kind with the original class
630 // template declaration (7.1.5.3).
631 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000632 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000633 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000634 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000635 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000636 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000637 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000638 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000639 }
640
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000641 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000642 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000643 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
644 Diag(NameLoc, diag::err_redefinition) << Name;
645 Diag(Def->getLocation(), diag::note_previous_definition);
646 // FIXME: Would it make sense to try to "forget" the previous
647 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000648 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000649 }
650 }
651 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
652 // Maybe we will complain about the shadowed template parameter.
653 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
654 // Just pretend that we didn't see the previous declaration.
655 PrevDecl = 0;
656 } else if (PrevDecl) {
657 // C++ [temp]p5:
658 // A class template shall not have the same name as any other
659 // template, class, function, object, enumeration, enumerator,
660 // namespace, or type in the same scope (3.3), except as specified
661 // in (14.5.4).
662 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
663 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000664 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000665 }
666
Douglas Gregordba32632009-02-10 19:49:53 +0000667 // Check the template parameter list of this declaration, possibly
668 // merging in the template parameter list from the previous class
669 // template declaration.
670 if (CheckTemplateParameterList(TemplateParams,
671 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
672 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000673
Douglas Gregore362cea2009-05-10 22:57:19 +0000674 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000675 // declaration!
676
Mike Stump11289f42009-09-09 15:08:12 +0000677 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000678 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000679 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000680 PrevClassTemplate->getTemplatedDecl() : 0,
681 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000682
683 ClassTemplateDecl *NewTemplate
684 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
685 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000686 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000687 NewClass->setDescribedClassTemplate(NewTemplate);
688
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000689 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000690 QualType T =
691 Context.getTypeDeclType(NewClass,
692 PrevClassTemplate?
693 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000694 assert(T->isDependentType() && "Class template type is not dependent?");
695 (void)T;
696
Anders Carlsson137108d2009-03-26 01:24:28 +0000697 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000698 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000699 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000700
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000701 // Set the lexical context of these templates
702 NewClass->setLexicalDeclContext(CurContext);
703 NewTemplate->setLexicalDeclContext(CurContext);
704
John McCall9bb74a52009-07-31 02:45:11 +0000705 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000706 NewClass->startDefinition();
707
708 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000709 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000710
John McCall27b5c252009-09-14 21:59:20 +0000711 if (TUK != TUK_Friend)
712 PushOnScopeChains(NewTemplate, S);
713 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000714 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000715 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000716 NewClass->setAccess(PrevClassTemplate->getAccess());
717 }
John McCall27b5c252009-09-14 21:59:20 +0000718
Douglas Gregor3dad8422009-09-26 06:47:28 +0000719 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
720 PrevClassTemplate != NULL);
721
John McCall27b5c252009-09-14 21:59:20 +0000722 // Friend templates are visible in fairly strange ways.
723 if (!CurContext->isDependentContext()) {
724 DeclContext *DC = SemanticContext->getLookupContext();
725 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
726 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
727 PushOnScopeChains(NewTemplate, EnclosingScope,
728 /* AddToContext = */ false);
729 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000730
731 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
732 NewClass->getLocation(),
733 NewTemplate,
734 /*FIXME:*/NewClass->getLocation());
735 Friend->setAccess(AS_public);
736 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000737 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000738
Douglas Gregordba32632009-02-10 19:49:53 +0000739 if (Invalid) {
740 NewTemplate->setInvalidDecl();
741 NewClass->setInvalidDecl();
742 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000743 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000744}
745
Douglas Gregordba32632009-02-10 19:49:53 +0000746/// \brief Checks the validity of a template parameter list, possibly
747/// considering the template parameter list from a previous
748/// declaration.
749///
750/// If an "old" template parameter list is provided, it must be
751/// equivalent (per TemplateParameterListsAreEqual) to the "new"
752/// template parameter list.
753///
754/// \param NewParams Template parameter list for a new template
755/// declaration. This template parameter list will be updated with any
756/// default arguments that are carried through from the previous
757/// template parameter list.
758///
759/// \param OldParams If provided, template parameter list from a
760/// previous declaration of the same template. Default template
761/// arguments will be merged from the old template parameter list to
762/// the new template parameter list.
763///
764/// \returns true if an error occurred, false otherwise.
765bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
766 TemplateParameterList *OldParams) {
767 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000768
Douglas Gregordba32632009-02-10 19:49:53 +0000769 // C++ [temp.param]p10:
770 // The set of default template-arguments available for use with a
771 // template declaration or definition is obtained by merging the
772 // default arguments from the definition (if in scope) and all
773 // declarations in scope in the same way default function
774 // arguments are (8.3.6).
775 bool SawDefaultArgument = false;
776 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000777
Anders Carlsson327865d2009-06-12 23:20:15 +0000778 bool SawParameterPack = false;
779 SourceLocation ParameterPackLoc;
780
Mike Stumpc89c8e32009-02-11 23:03:27 +0000781 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000782 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000783 if (OldParams)
784 OldParam = OldParams->begin();
785
786 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
787 NewParamEnd = NewParams->end();
788 NewParam != NewParamEnd; ++NewParam) {
789 // Variables used to diagnose redundant default arguments
790 bool RedundantDefaultArg = false;
791 SourceLocation OldDefaultLoc;
792 SourceLocation NewDefaultLoc;
793
794 // Variables used to diagnose missing default arguments
795 bool MissingDefaultArg = false;
796
Anders Carlsson327865d2009-06-12 23:20:15 +0000797 // C++0x [temp.param]p11:
798 // If a template parameter of a class template is a template parameter pack,
799 // it must be the last template parameter.
800 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +0000801 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +0000802 diag::err_template_param_pack_must_be_last_template_parameter);
803 Invalid = true;
804 }
805
Douglas Gregordba32632009-02-10 19:49:53 +0000806 // Merge default arguments for template type parameters.
807 if (TemplateTypeParmDecl *NewTypeParm
808 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump11289f42009-09-09 15:08:12 +0000809 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000810 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000811
Anders Carlsson327865d2009-06-12 23:20:15 +0000812 if (NewTypeParm->isParameterPack()) {
813 assert(!NewTypeParm->hasDefaultArgument() &&
814 "Parameter packs can't have a default argument!");
815 SawParameterPack = true;
816 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000817 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000818 NewTypeParm->hasDefaultArgument()) {
819 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
820 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
821 SawDefaultArgument = true;
822 RedundantDefaultArg = true;
823 PreviousDefaultArgLoc = NewDefaultLoc;
824 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
825 // Merge the default argument from the old declaration to the
826 // new declaration.
827 SawDefaultArgument = true;
828 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
829 OldTypeParm->getDefaultArgumentLoc(),
830 true);
831 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
832 } else if (NewTypeParm->hasDefaultArgument()) {
833 SawDefaultArgument = true;
834 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
835 } else if (SawDefaultArgument)
836 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000837 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000838 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000839 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000840 NonTypeTemplateParmDecl *OldNonTypeParm
841 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000842 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000843 NewNonTypeParm->hasDefaultArgument()) {
844 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
845 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
846 SawDefaultArgument = true;
847 RedundantDefaultArg = true;
848 PreviousDefaultArgLoc = NewDefaultLoc;
849 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
850 // Merge the default argument from the old declaration to the
851 // new declaration.
852 SawDefaultArgument = true;
853 // FIXME: We need to create a new kind of "default argument"
854 // expression that points to a previous template template
855 // parameter.
856 NewNonTypeParm->setDefaultArgument(
857 OldNonTypeParm->getDefaultArgument());
858 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
859 } else if (NewNonTypeParm->hasDefaultArgument()) {
860 SawDefaultArgument = true;
861 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
862 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000863 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000864 } else {
Douglas Gregordba32632009-02-10 19:49:53 +0000865 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000866 TemplateTemplateParmDecl *NewTemplateParm
867 = cast<TemplateTemplateParmDecl>(*NewParam);
868 TemplateTemplateParmDecl *OldTemplateParm
869 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000870 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000871 NewTemplateParm->hasDefaultArgument()) {
872 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
873 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
874 SawDefaultArgument = true;
875 RedundantDefaultArg = true;
876 PreviousDefaultArgLoc = NewDefaultLoc;
877 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
878 // Merge the default argument from the old declaration to the
879 // new declaration.
880 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +0000881 // FIXME: We need to create a new kind of "default argument" expression
882 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +0000883 NewTemplateParm->setDefaultArgument(
884 OldTemplateParm->getDefaultArgument());
885 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
886 } else if (NewTemplateParm->hasDefaultArgument()) {
887 SawDefaultArgument = true;
888 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
889 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000890 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +0000891 }
892
893 if (RedundantDefaultArg) {
894 // C++ [temp.param]p12:
895 // A template-parameter shall not be given default arguments
896 // by two different declarations in the same scope.
897 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
898 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
899 Invalid = true;
900 } else if (MissingDefaultArg) {
901 // C++ [temp.param]p11:
902 // If a template-parameter has a default template-argument,
903 // all subsequent template-parameters shall have a default
904 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +0000905 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +0000906 diag::err_template_param_default_arg_missing);
907 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
908 Invalid = true;
909 }
910
911 // If we have an old template parameter list that we're merging
912 // in, move on to the next parameter.
913 if (OldParams)
914 ++OldParam;
915 }
916
917 return Invalid;
918}
Douglas Gregord32e0282009-02-09 23:23:08 +0000919
Mike Stump11289f42009-09-09 15:08:12 +0000920/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +0000921/// specifier, returning the template parameter list that applies to the
922/// name.
923///
924/// \param DeclStartLoc the start of the declaration that has a scope
925/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +0000926///
Douglas Gregord8d297c2009-07-21 23:53:31 +0000927/// \param SS the scope specifier that will be matched to the given template
928/// parameter lists. This scope specifier precedes a qualified name that is
929/// being declared.
930///
931/// \param ParamLists the template parameter lists, from the outermost to the
932/// innermost template parameter lists.
933///
934/// \param NumParamLists the number of template parameter lists in ParamLists.
935///
Mike Stump11289f42009-09-09 15:08:12 +0000936/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +0000937/// name that is preceded by the scope specifier @p SS. This template
938/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +0000939/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +0000940/// template specialization), or may be NULL (if we were's declaring isn't
941/// itself a template).
942TemplateParameterList *
943Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
944 const CXXScopeSpec &SS,
945 TemplateParameterList **ParamLists,
946 unsigned NumParamLists) {
Douglas Gregord8d297c2009-07-21 23:53:31 +0000947 // Find the template-ids that occur within the nested-name-specifier. These
948 // template-ids will match up with the template parameter lists.
949 llvm::SmallVector<const TemplateSpecializationType *, 4>
950 TemplateIdsInSpecifier;
951 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
952 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +0000953 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +0000954 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
955 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
956 if (!Template)
957 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +0000958
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000959 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +0000960 ClassTemplateSpecializationDecl *SpecDecl
961 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
962 // If the nested name specifier refers to an explicit specialization,
963 // we don't need a template<> header.
Douglas Gregor82e22862009-09-16 00:01:48 +0000964 // FIXME: revisit this approach once we cope with specializations
Douglas Gregor15301382009-07-30 17:40:51 +0000965 // properly.
Douglas Gregord8d297c2009-07-21 23:53:31 +0000966 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
967 continue;
968 }
Mike Stump11289f42009-09-09 15:08:12 +0000969
Douglas Gregord8d297c2009-07-21 23:53:31 +0000970 TemplateIdsInSpecifier.push_back(SpecType);
971 }
972 }
Mike Stump11289f42009-09-09 15:08:12 +0000973
Douglas Gregord8d297c2009-07-21 23:53:31 +0000974 // Reverse the list of template-ids in the scope specifier, so that we can
975 // more easily match up the template-ids and the template parameter lists.
976 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +0000977
Douglas Gregord8d297c2009-07-21 23:53:31 +0000978 SourceLocation FirstTemplateLoc = DeclStartLoc;
979 if (NumParamLists)
980 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000981
Douglas Gregord8d297c2009-07-21 23:53:31 +0000982 // Match the template-ids found in the specifier to the template parameter
983 // lists.
984 unsigned Idx = 0;
985 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
986 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +0000987 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
988 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +0000989 if (Idx >= NumParamLists) {
990 // We have a template-id without a corresponding template parameter
991 // list.
992 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +0000993 // FIXME: the location information here isn't great.
994 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +0000995 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +0000996 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +0000997 << SS.getRange();
998 } else {
999 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1000 << SS.getRange()
1001 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1002 "template<> ");
1003 }
1004 return 0;
1005 }
Mike Stump11289f42009-09-09 15:08:12 +00001006
Douglas Gregord8d297c2009-07-21 23:53:31 +00001007 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001008 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001009 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001010 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1011
Mike Stump11289f42009-09-09 15:08:12 +00001012 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001013 = dyn_cast<ClassTemplateDecl>(Template)) {
1014 TemplateParameterList *ExpectedTemplateParams = 0;
1015 // Is this template-id naming the primary template?
1016 if (Context.hasSameType(TemplateId,
1017 ClassTemplate->getInjectedClassNameType(Context)))
1018 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1019 // ... or a partial specialization?
1020 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1021 = ClassTemplate->findPartialSpecialization(TemplateId))
1022 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1023
1024 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001025 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001026 ExpectedTemplateParams,
1027 true);
Mike Stump11289f42009-09-09 15:08:12 +00001028 }
Douglas Gregor15301382009-07-30 17:40:51 +00001029 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001030 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001031 diag::err_template_param_list_matches_nontemplate)
1032 << TemplateId
1033 << ParamLists[Idx]->getSourceRange();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001034 }
Mike Stump11289f42009-09-09 15:08:12 +00001035
Douglas Gregord8d297c2009-07-21 23:53:31 +00001036 // If there were at least as many template-ids as there were template
1037 // parameter lists, then there are no template parameter lists remaining for
1038 // the declaration itself.
1039 if (Idx >= NumParamLists)
1040 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001041
Douglas Gregord8d297c2009-07-21 23:53:31 +00001042 // If there were too many template parameter lists, complain about that now.
1043 if (Idx != NumParamLists - 1) {
1044 while (Idx < NumParamLists - 1) {
Mike Stump11289f42009-09-09 15:08:12 +00001045 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001046 diag::err_template_spec_extra_headers)
1047 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1048 ParamLists[Idx]->getRAngleLoc());
1049 ++Idx;
1050 }
1051 }
Mike Stump11289f42009-09-09 15:08:12 +00001052
Douglas Gregord8d297c2009-07-21 23:53:31 +00001053 // Return the last template parameter list, which corresponds to the
1054 // entity being declared.
1055 return ParamLists[NumParamLists - 1];
1056}
1057
Douglas Gregorc40290e2009-03-09 23:48:35 +00001058/// \brief Translates template arguments as provided by the parser
1059/// into template arguments used by semantic analysis.
Douglas Gregor0e876e02009-09-25 23:53:26 +00001060void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
1061 SourceLocation *TemplateArgLocs,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001062 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
1063 TemplateArgs.reserve(TemplateArgsIn.size());
1064
1065 void **Args = TemplateArgsIn.getArgs();
1066 bool *ArgIsType = TemplateArgsIn.getArgIsType();
1067 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
1068 TemplateArgs.push_back(
1069 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001070 //FIXME: Preserve type source info.
1071 Sema::GetTypeFromParser(Args[Arg]))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001072 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
1073 }
1074}
1075
Douglas Gregordc572a32009-03-30 22:58:21 +00001076QualType Sema::CheckTemplateIdType(TemplateName Name,
1077 SourceLocation TemplateLoc,
1078 SourceLocation LAngleLoc,
1079 const TemplateArgument *TemplateArgs,
1080 unsigned NumTemplateArgs,
1081 SourceLocation RAngleLoc) {
1082 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001083 if (!Template) {
1084 // The template name does not resolve to a template, so we just
1085 // build a dependent template-id type.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001086 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001087 NumTemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001088 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001089
Douglas Gregorc40290e2009-03-09 23:48:35 +00001090 // Check that the template argument list is well-formed for this
1091 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001092 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1093 NumTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001094 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001095 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001096 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001097 return QualType();
1098
Mike Stump11289f42009-09-09 15:08:12 +00001099 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001100 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001101 "Converted template argument list is too short!");
1102
1103 QualType CanonType;
1104
Douglas Gregordc572a32009-03-30 22:58:21 +00001105 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorc40290e2009-03-09 23:48:35 +00001106 TemplateArgs,
1107 NumTemplateArgs)) {
1108 // This class template specialization is a dependent
1109 // type. Therefore, its canonical type is another class template
1110 // specialization type that contains all of the converted
1111 // arguments in canonical form. This ensures that, e.g., A<T> and
1112 // A<T, T> have identical types when A is declared as:
1113 //
1114 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001115 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001116 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001117 Converted.getFlatArguments(),
1118 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001119
Douglas Gregora8e02e72009-07-28 23:00:59 +00001120 // FIXME: CanonType is not actually the canonical type, and unfortunately
1121 // it is a TemplateTypeSpecializationType that we will never use again.
1122 // In the future, we need to teach getTemplateSpecializationType to only
1123 // build the canonical type and return that to us.
1124 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001125 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001126 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001127 // Find the class template specialization declaration that
1128 // corresponds to these arguments.
1129 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001130 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001131 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001132 Converted.flatSize(),
1133 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001134 void *InsertPos = 0;
1135 ClassTemplateSpecializationDecl *Decl
1136 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1137 if (!Decl) {
1138 // This is the first time we have referenced this class template
1139 // specialization. Create the canonical declaration and add it to
1140 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001141 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001142 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001143 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001144 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001145 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001146 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1147 Decl->setLexicalDeclContext(CurContext);
1148 }
1149
1150 CanonType = Context.getTypeDeclType(Decl);
1151 }
Mike Stump11289f42009-09-09 15:08:12 +00001152
Douglas Gregorc40290e2009-03-09 23:48:35 +00001153 // Build the fully-sugared type for this class template
1154 // specialization, which refers back to the class template
1155 // specialization we created or found.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001156 //FIXME: Preserve type source info.
Douglas Gregordc572a32009-03-30 22:58:21 +00001157 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1158 NumTemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001159}
1160
Douglas Gregor67a65642009-02-17 23:15:12 +00001161Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001162Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001163 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001164 ASTTemplateArgsPtr TemplateArgsIn,
1165 SourceLocation *TemplateArgLocs,
John McCalld8fe9af2009-09-08 17:47:29 +00001166 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001167 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001168
Douglas Gregorc40290e2009-03-09 23:48:35 +00001169 // Translate the parser's template argument list in our AST format.
1170 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1171 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001172
Douglas Gregordc572a32009-03-30 22:58:21 +00001173 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +00001174 TemplateArgs.data(),
1175 TemplateArgs.size(),
Douglas Gregordc572a32009-03-30 22:58:21 +00001176 RAngleLoc);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001177 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001178
1179 if (Result.isNull())
1180 return true;
1181
John McCalld8fe9af2009-09-08 17:47:29 +00001182 return Result.getAsOpaquePtr();
1183}
John McCall06f6fe8d2009-09-04 01:14:41 +00001184
John McCalld8fe9af2009-09-08 17:47:29 +00001185Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1186 TagUseKind TUK,
1187 DeclSpec::TST TagSpec,
1188 SourceLocation TagLoc) {
1189 if (TypeResult.isInvalid())
1190 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001191
John McCalld8fe9af2009-09-08 17:47:29 +00001192 QualType Type = QualType::getFromOpaquePtr(TypeResult.get());
John McCall06f6fe8d2009-09-04 01:14:41 +00001193
John McCalld8fe9af2009-09-08 17:47:29 +00001194 // Verify the tag specifier.
1195 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001196
John McCalld8fe9af2009-09-08 17:47:29 +00001197 if (const RecordType *RT = Type->getAs<RecordType>()) {
1198 RecordDecl *D = RT->getDecl();
1199
1200 IdentifierInfo *Id = D->getIdentifier();
1201 assert(Id && "templated class must have an identifier");
1202
1203 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1204 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001205 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001206 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1207 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001208 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001209 }
1210 }
1211
John McCalld8fe9af2009-09-08 17:47:29 +00001212 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1213
1214 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001215}
1216
Douglas Gregora727cb92009-06-30 22:34:41 +00001217Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1218 SourceLocation TemplateNameLoc,
1219 SourceLocation LAngleLoc,
1220 const TemplateArgument *TemplateArgs,
1221 unsigned NumTemplateArgs,
1222 SourceLocation RAngleLoc) {
1223 // FIXME: Can we do any checking at this point? I guess we could check the
1224 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001225 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001226 // though.
Mike Stump11289f42009-09-09 15:08:12 +00001227 return Owned(TemplateIdRefExpr::Create(Context,
Douglas Gregora727cb92009-06-30 22:34:41 +00001228 /*FIXME: New type?*/Context.OverloadTy,
1229 /*FIXME: Necessary?*/0,
1230 /*FIXME: Necessary?*/SourceRange(),
1231 Template, TemplateNameLoc, LAngleLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001232 TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001233 NumTemplateArgs, RAngleLoc));
1234}
1235
1236Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1237 SourceLocation TemplateNameLoc,
1238 SourceLocation LAngleLoc,
1239 ASTTemplateArgsPtr TemplateArgsIn,
1240 SourceLocation *TemplateArgLocs,
1241 SourceLocation RAngleLoc) {
1242 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001243
Douglas Gregora727cb92009-06-30 22:34:41 +00001244 // Translate the parser's template argument list in our AST format.
1245 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1246 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001247 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001248
Douglas Gregora727cb92009-06-30 22:34:41 +00001249 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1250 TemplateArgs.data(), TemplateArgs.size(),
1251 RAngleLoc);
1252}
1253
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001254Sema::OwningExprResult
1255Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base,
1256 SourceLocation OpLoc,
1257 tok::TokenKind OpKind,
1258 const CXXScopeSpec &SS,
1259 TemplateTy TemplateD,
1260 SourceLocation TemplateNameLoc,
1261 SourceLocation LAngleLoc,
1262 ASTTemplateArgsPtr TemplateArgsIn,
1263 SourceLocation *TemplateArgLocs,
1264 SourceLocation RAngleLoc) {
1265 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001266
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001267 // FIXME: We're going to end up looking up the template based on its name,
1268 // twice!
1269 DeclarationName Name;
1270 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
1271 Name = ActualTemplate->getDeclName();
1272 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
1273 Name = Ovl->getDeclName();
1274 else
Douglas Gregor308047d2009-09-09 00:23:06 +00001275 Name = Template.getAsDependentTemplateName()->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001276
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001277 // Translate the parser's template argument list in our AST format.
1278 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1279 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1280 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001281
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001282 // Do we have the save the actual template name? We might need it...
1283 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc,
1284 Name, true, LAngleLoc,
1285 TemplateArgs.data(), TemplateArgs.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001286 RAngleLoc, DeclPtrTy(), &SS);
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001287}
1288
Douglas Gregorb67535d2009-03-31 00:43:58 +00001289/// \brief Form a dependent template name.
1290///
1291/// This action forms a dependent template name given the template
1292/// name and its (presumably dependent) scope specifier. For
1293/// example, given "MetaFun::template apply", the scope specifier \p
1294/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1295/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001296Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001297Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1298 const IdentifierInfo &Name,
1299 SourceLocation NameLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001300 const CXXScopeSpec &SS,
1301 TypeTy *ObjectType) {
Mike Stump11289f42009-09-09 15:08:12 +00001302 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001303 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1304 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001305 // C++0x [temp.names]p5:
1306 // If a name prefixed by the keyword template is not the name of
1307 // a template, the program is ill-formed. [Note: the keyword
1308 // template may not be applied to non-template members of class
1309 // templates. -end note ] [ Note: as is the case with the
1310 // typename prefix, the template prefix is allowed in cases
1311 // where it is not strictly necessary; i.e., when the
1312 // nested-name-specifier or the expression on the left of the ->
1313 // or . is not dependent on a template-parameter, or the use
1314 // does not appear in the scope of a template. -end note]
1315 //
1316 // Note: C++03 was more strict here, because it banned the use of
1317 // the "template" keyword prior to a template-name that was not a
1318 // dependent name. C++ DR468 relaxed this requirement (the
1319 // "template" keyword is now permitted). We follow the C++0x
1320 // rules, even in C++03 mode, retroactively applying the DR.
1321 TemplateTy Template;
Mike Stump11289f42009-09-09 15:08:12 +00001322 TemplateNameKind TNK = isTemplateName(0, Name, NameLoc, &SS, ObjectType,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001323 false, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001324 if (TNK == TNK_Non_template) {
1325 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1326 << &Name;
1327 return TemplateTy();
1328 }
1329
1330 return Template;
1331 }
1332
Mike Stump11289f42009-09-09 15:08:12 +00001333 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001334 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorb67535d2009-03-31 00:43:58 +00001335 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1336}
1337
Mike Stump11289f42009-09-09 15:08:12 +00001338bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001339 const TemplateArgument &Arg,
1340 TemplateArgumentListBuilder &Converted) {
1341 // Check template type parameter.
1342 if (Arg.getKind() != TemplateArgument::Type) {
1343 // C++ [temp.arg.type]p1:
1344 // A template-argument for a template-parameter which is a
1345 // type shall be a type-id.
1346
1347 // We have a template type parameter but the template argument
1348 // is not a type.
1349 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1350 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001351
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001352 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001353 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001354
1355 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1356 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001357
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001358 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001359 Converted.Append(
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001360 TemplateArgument(Arg.getLocation(),
1361 Context.getCanonicalType(Arg.getAsType())));
1362 return false;
1363}
1364
Douglas Gregord32e0282009-02-09 23:23:08 +00001365/// \brief Check that the given template argument list is well-formed
1366/// for specializing the given template.
1367bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1368 SourceLocation TemplateLoc,
1369 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001370 const TemplateArgument *TemplateArgs,
1371 unsigned NumTemplateArgs,
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001372 SourceLocation RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001373 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001374 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001375 TemplateParameterList *Params = Template->getTemplateParameters();
1376 unsigned NumParams = Params->size();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001377 unsigned NumArgs = NumTemplateArgs;
Douglas Gregord32e0282009-02-09 23:23:08 +00001378 bool Invalid = false;
1379
Mike Stump11289f42009-09-09 15:08:12 +00001380 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001381 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001382
Anders Carlsson15201f12009-06-13 02:08:00 +00001383 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001384 (NumArgs < Params->getMinRequiredArguments() &&
1385 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001386 // FIXME: point at either the first arg beyond what we can handle,
1387 // or the '>', depending on whether we have too many or too few
1388 // arguments.
1389 SourceRange Range;
1390 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001391 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001392 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1393 << (NumArgs > NumParams)
1394 << (isa<ClassTemplateDecl>(Template)? 0 :
1395 isa<FunctionTemplateDecl>(Template)? 1 :
1396 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1397 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001398 Diag(Template->getLocation(), diag::note_template_decl_here)
1399 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001400 Invalid = true;
1401 }
Mike Stump11289f42009-09-09 15:08:12 +00001402
1403 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001404 // [...] The type and form of each template-argument specified in
1405 // a template-id shall match the type and form specified for the
1406 // corresponding parameter declared by the template in its
1407 // template-parameter-list.
1408 unsigned ArgIdx = 0;
1409 for (TemplateParameterList::iterator Param = Params->begin(),
1410 ParamEnd = Params->end();
1411 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001412 if (ArgIdx > NumArgs && PartialTemplateArgs)
1413 break;
Mike Stump11289f42009-09-09 15:08:12 +00001414
Douglas Gregord32e0282009-02-09 23:23:08 +00001415 // Decode the template argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001416 TemplateArgument Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00001417 if (ArgIdx >= NumArgs) {
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001418 // Retrieve the default template argument from the template
1419 // parameter.
1420 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001421 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001422 // We have an empty argument pack.
1423 Converted.BeginPack();
1424 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001425 break;
1426 }
Mike Stump11289f42009-09-09 15:08:12 +00001427
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001428 if (!TTP->hasDefaultArgument())
1429 break;
1430
Douglas Gregorc40290e2009-03-09 23:48:35 +00001431 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001432
1433 // If the argument type is dependent, instantiate it now based
1434 // on the previously-computed template arguments.
Douglas Gregor79cf6032009-03-10 20:44:00 +00001435 if (ArgType->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001436 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001437 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001438 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001439 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregord002c7b2009-05-11 23:53:27 +00001440
Anders Carlssonc8e71132009-06-05 04:47:51 +00001441 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001442 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001443 ArgType = SubstType(ArgType,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001444 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001445 TTP->getDefaultArgumentLoc(),
1446 TTP->getDeclName());
Douglas Gregor79cf6032009-03-10 20:44:00 +00001447 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001448
1449 if (ArgType.isNull())
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001450 return true;
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001451
Douglas Gregorc40290e2009-03-09 23:48:35 +00001452 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001453 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001454 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1455 if (!NTTP->hasDefaultArgument())
1456 break;
1457
Mike Stump11289f42009-09-09 15:08:12 +00001458 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001459 Template, Converted.getFlatArguments(),
Anders Carlsson40ed3442009-06-11 16:06:49 +00001460 Converted.flatSize(),
1461 SourceRange(TemplateLoc, RAngleLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001462
Anders Carlsson40ed3442009-06-11 16:06:49 +00001463 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001464 /*TakeArgs=*/false);
Anders Carlsson40ed3442009-06-11 16:06:49 +00001465
Mike Stump11289f42009-09-09 15:08:12 +00001466 Sema::OwningExprResult E
1467 = SubstExpr(NTTP->getDefaultArgument(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00001468 MultiLevelTemplateArgumentList(TemplateArgs));
Anders Carlsson40ed3442009-06-11 16:06:49 +00001469 if (E.isInvalid())
1470 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001471
Anders Carlsson40ed3442009-06-11 16:06:49 +00001472 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001473 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001474 TemplateTemplateParmDecl *TempParm
1475 = cast<TemplateTemplateParmDecl>(*Param);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001476
1477 if (!TempParm->hasDefaultArgument())
1478 break;
1479
John McCall76d824f2009-08-25 22:02:44 +00001480 // FIXME: Subst default argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001481 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001482 }
1483 } else {
1484 // Retrieve the template argument produced by the user.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001485 Arg = TemplateArgs[ArgIdx];
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001486 }
1487
Douglas Gregord32e0282009-02-09 23:23:08 +00001488
1489 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001490 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001491 Converted.BeginPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001492 // Check all the remaining arguments (if any).
1493 for (; ArgIdx < NumArgs; ++ArgIdx) {
1494 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1495 Invalid = true;
1496 }
Mike Stump11289f42009-09-09 15:08:12 +00001497
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001498 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001499 } else {
1500 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1501 Invalid = true;
1502 }
Mike Stump11289f42009-09-09 15:08:12 +00001503 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord32e0282009-02-09 23:23:08 +00001504 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1505 // Check non-type template parameters.
Douglas Gregor463421d2009-03-03 04:44:36 +00001506
John McCall76d824f2009-08-25 22:02:44 +00001507 // Do substitution on the type of the non-type template parameter
1508 // with the template arguments we've seen thus far.
Douglas Gregor463421d2009-03-03 04:44:36 +00001509 QualType NTTPType = NTTP->getType();
1510 if (NTTPType->isDependentType()) {
John McCall76d824f2009-08-25 22:02:44 +00001511 // Do substitution on the type of the non-type template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001512 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001513 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001514 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001515 SourceRange(TemplateLoc, RAngleLoc));
1516
Anders Carlssonc8e71132009-06-05 04:47:51 +00001517 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001518 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001519 NTTPType = SubstType(NTTPType,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00001520 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001521 NTTP->getLocation(),
1522 NTTP->getDeclName());
Douglas Gregor463421d2009-03-03 04:44:36 +00001523 // If that worked, check the non-type template parameter type
1524 // for validity.
1525 if (!NTTPType.isNull())
Mike Stump11289f42009-09-09 15:08:12 +00001526 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
Douglas Gregor463421d2009-03-03 04:44:36 +00001527 NTTP->getLocation());
Douglas Gregor463421d2009-03-03 04:44:36 +00001528 if (NTTPType.isNull()) {
1529 Invalid = true;
1530 break;
1531 }
1532 }
1533
Douglas Gregorc40290e2009-03-09 23:48:35 +00001534 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001535 case TemplateArgument::Null:
1536 assert(false && "Should never see a NULL template argument here");
1537 break;
Mike Stump11289f42009-09-09 15:08:12 +00001538
Douglas Gregorc40290e2009-03-09 23:48:35 +00001539 case TemplateArgument::Expression: {
1540 Expr *E = Arg.getAsExpr();
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001541 TemplateArgument Result;
1542 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregord32e0282009-02-09 23:23:08 +00001543 Invalid = true;
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001544 else
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001545 Converted.Append(Result);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001546 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001547 }
1548
Douglas Gregorc40290e2009-03-09 23:48:35 +00001549 case TemplateArgument::Declaration:
1550 case TemplateArgument::Integral:
1551 // We've already checked this template argument, so just copy
1552 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001553 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001554 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001555
Douglas Gregorc40290e2009-03-09 23:48:35 +00001556 case TemplateArgument::Type:
1557 // We have a non-type template parameter but the template
1558 // argument is a type.
Mike Stump11289f42009-09-09 15:08:12 +00001559
Douglas Gregorc40290e2009-03-09 23:48:35 +00001560 // C++ [temp.arg]p2:
1561 // In a template-argument, an ambiguity between a type-id and
1562 // an expression is resolved to a type-id, regardless of the
1563 // form of the corresponding template-parameter.
1564 //
1565 // We warn specifically about this case, since it can be rather
1566 // confusing for users.
1567 if (Arg.getAsType()->isFunctionType())
1568 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1569 << Arg.getAsType();
1570 else
1571 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1572 Diag((*Param)->getLocation(), diag::note_template_param_here);
1573 Invalid = true;
Anders Carlssonbc343912009-06-15 17:04:53 +00001574 break;
Mike Stump11289f42009-09-09 15:08:12 +00001575
Anders Carlssonbc343912009-06-15 17:04:53 +00001576 case TemplateArgument::Pack:
1577 assert(0 && "FIXME: Implement!");
1578 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001579 }
Mike Stump11289f42009-09-09 15:08:12 +00001580 } else {
Douglas Gregord32e0282009-02-09 23:23:08 +00001581 // Check template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001582 TemplateTemplateParmDecl *TempParm
Douglas Gregord32e0282009-02-09 23:23:08 +00001583 = cast<TemplateTemplateParmDecl>(*Param);
Mike Stump11289f42009-09-09 15:08:12 +00001584
Douglas Gregorc40290e2009-03-09 23:48:35 +00001585 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001586 case TemplateArgument::Null:
1587 assert(false && "Should never see a NULL template argument here");
1588 break;
Mike Stump11289f42009-09-09 15:08:12 +00001589
Douglas Gregorc40290e2009-03-09 23:48:35 +00001590 case TemplateArgument::Expression: {
1591 Expr *ArgExpr = Arg.getAsExpr();
1592 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1593 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1594 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1595 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001596
Douglas Gregorc40290e2009-03-09 23:48:35 +00001597 // Add the converted template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001598 Decl *D
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00001599 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001600 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorc40290e2009-03-09 23:48:35 +00001601 continue;
1602 }
1603 }
1604 // fall through
Mike Stump11289f42009-09-09 15:08:12 +00001605
Douglas Gregorc40290e2009-03-09 23:48:35 +00001606 case TemplateArgument::Type: {
1607 // We have a template template parameter but the template
1608 // argument does not refer to a template.
1609 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1610 Invalid = true;
1611 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001612 }
1613
Douglas Gregorc40290e2009-03-09 23:48:35 +00001614 case TemplateArgument::Declaration:
1615 // We've already checked this template argument, so just copy
1616 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001617 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001618 break;
Mike Stump11289f42009-09-09 15:08:12 +00001619
Douglas Gregorc40290e2009-03-09 23:48:35 +00001620 case TemplateArgument::Integral:
1621 assert(false && "Integral argument with template template parameter");
1622 break;
Mike Stump11289f42009-09-09 15:08:12 +00001623
Anders Carlssonbc343912009-06-15 17:04:53 +00001624 case TemplateArgument::Pack:
1625 assert(0 && "FIXME: Implement!");
1626 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001627 }
Douglas Gregord32e0282009-02-09 23:23:08 +00001628 }
1629 }
1630
1631 return Invalid;
1632}
1633
1634/// \brief Check a template argument against its corresponding
1635/// template type parameter.
1636///
1637/// This routine implements the semantics of C++ [temp.arg.type]. It
1638/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001639bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
Douglas Gregord32e0282009-02-09 23:23:08 +00001640 QualType Arg, SourceLocation ArgLoc) {
1641 // C++ [temp.arg.type]p2:
1642 // A local type, a type with no linkage, an unnamed type or a type
1643 // compounded from any of these types shall not be used as a
1644 // template-argument for a template type-parameter.
1645 //
1646 // FIXME: Perform the recursive and no-linkage type checks.
1647 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001648 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001649 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001650 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001651 Tag = RecordT;
1652 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1653 return Diag(ArgLoc, diag::err_template_arg_local_type)
1654 << QualType(Tag, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001655 else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001656 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001657 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1658 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1659 return true;
1660 }
1661
1662 return false;
1663}
1664
Douglas Gregorccb07762009-02-11 19:52:55 +00001665/// \brief Checks whether the given template argument is the address
1666/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001667bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1668 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001669 bool Invalid = false;
1670
1671 // See through any implicit casts we added to fix the type.
1672 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1673 Arg = Cast->getSubExpr();
1674
Sebastian Redl576fd422009-05-10 18:38:11 +00001675 // C++0x allows nullptr, and there's no further checking to be done for that.
1676 if (Arg->getType()->isNullPtrType())
1677 return false;
1678
Douglas Gregorccb07762009-02-11 19:52:55 +00001679 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001680 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001681 // A template-argument for a non-type, non-template
1682 // template-parameter shall be one of: [...]
1683 //
1684 // -- the address of an object or function with external
1685 // linkage, including function templates and function
1686 // template-ids but excluding non-static class members,
1687 // expressed as & id-expression where the & is optional if
1688 // the name refers to a function or array, or if the
1689 // corresponding template-parameter is a reference; or
1690 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001691
Douglas Gregorccb07762009-02-11 19:52:55 +00001692 // Ignore (and complain about) any excess parentheses.
1693 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1694 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001695 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001696 diag::err_template_arg_extra_parens)
1697 << Arg->getSourceRange();
1698 Invalid = true;
1699 }
1700
1701 Arg = Parens->getSubExpr();
1702 }
1703
1704 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1705 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1706 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1707 } else
1708 DRE = dyn_cast<DeclRefExpr>(Arg);
1709
1710 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00001711 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001712 diag::err_template_arg_not_object_or_func_form)
1713 << Arg->getSourceRange();
1714
1715 // Cannot refer to non-static data members
1716 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1717 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1718 << Field << Arg->getSourceRange();
1719
1720 // Cannot refer to non-static member functions
1721 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1722 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00001723 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001724 diag::err_template_arg_method)
1725 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001726
Douglas Gregorccb07762009-02-11 19:52:55 +00001727 // Functions must have external linkage.
1728 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1729 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00001730 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001731 diag::err_template_arg_function_not_extern)
1732 << Func << Arg->getSourceRange();
1733 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1734 << true;
1735 return true;
1736 }
1737
1738 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001739 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00001740 return Invalid;
1741 }
1742
1743 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1744 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00001745 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001746 diag::err_template_arg_object_not_extern)
1747 << Var << Arg->getSourceRange();
1748 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1749 << true;
1750 return true;
1751 }
1752
1753 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001754 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00001755 return Invalid;
1756 }
Mike Stump11289f42009-09-09 15:08:12 +00001757
Douglas Gregorccb07762009-02-11 19:52:55 +00001758 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001759 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001760 diag::err_template_arg_not_object_or_func)
1761 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001762 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001763 diag::note_template_arg_refers_here);
1764 return true;
1765}
1766
1767/// \brief Checks whether the given template argument is a pointer to
1768/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump11289f42009-09-09 15:08:12 +00001769bool
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001770Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001771 bool Invalid = false;
1772
1773 // See through any implicit casts we added to fix the type.
1774 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1775 Arg = Cast->getSubExpr();
1776
Sebastian Redl576fd422009-05-10 18:38:11 +00001777 // C++0x allows nullptr, and there's no further checking to be done for that.
1778 if (Arg->getType()->isNullPtrType())
1779 return false;
1780
Douglas Gregorccb07762009-02-11 19:52:55 +00001781 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001782 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001783 // A template-argument for a non-type, non-template
1784 // template-parameter shall be one of: [...]
1785 //
1786 // -- a pointer to member expressed as described in 5.3.1.
1787 QualifiedDeclRefExpr *DRE = 0;
1788
1789 // Ignore (and complain about) any excess parentheses.
1790 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1791 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001792 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001793 diag::err_template_arg_extra_parens)
1794 << Arg->getSourceRange();
1795 Invalid = true;
1796 }
1797
1798 Arg = Parens->getSubExpr();
1799 }
1800
1801 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1802 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1803 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1804
1805 if (!DRE)
1806 return Diag(Arg->getSourceRange().getBegin(),
1807 diag::err_template_arg_not_pointer_to_member_form)
1808 << Arg->getSourceRange();
1809
1810 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1811 assert((isa<FieldDecl>(DRE->getDecl()) ||
1812 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1813 "Only non-static member pointers can make it here");
1814
1815 // Okay: this is the address of a non-static member, and therefore
1816 // a member pointer constant.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001817 Member = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00001818 return Invalid;
1819 }
1820
1821 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001822 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001823 diag::err_template_arg_not_pointer_to_member_form)
1824 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001825 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001826 diag::note_template_arg_refers_here);
1827 return true;
1828}
1829
Douglas Gregord32e0282009-02-09 23:23:08 +00001830/// \brief Check a template argument against its corresponding
1831/// non-type template parameter.
1832///
Douglas Gregor463421d2009-03-03 04:44:36 +00001833/// This routine implements the semantics of C++ [temp.arg.nontype].
1834/// It returns true if an error occurred, and false otherwise. \p
1835/// InstantiatedParamType is the type of the non-type template
1836/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001837///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001838/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00001839bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00001840 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001841 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001842 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1843
Douglas Gregor86560402009-02-10 23:36:10 +00001844 // If either the parameter has a dependent type or the argument is
1845 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001846 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00001847 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1848 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001849 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00001850 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001851 }
Douglas Gregor86560402009-02-10 23:36:10 +00001852
1853 // C++ [temp.arg.nontype]p5:
1854 // The following conversions are performed on each expression used
1855 // as a non-type template-argument. If a non-type
1856 // template-argument cannot be converted to the type of the
1857 // corresponding template-parameter then the program is
1858 // ill-formed.
1859 //
1860 // -- for a non-type template-parameter of integral or
1861 // enumeration type, integral promotions (4.5) and integral
1862 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00001863 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001864 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00001865 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00001866 // C++ [temp.arg.nontype]p1:
1867 // A template-argument for a non-type, non-template
1868 // template-parameter shall be one of:
1869 //
1870 // -- an integral constant-expression of integral or enumeration
1871 // type; or
1872 // -- the name of a non-type template-parameter; or
1873 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001874 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00001875 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001876 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001877 diag::err_template_arg_not_integral_or_enumeral)
1878 << ArgType << Arg->getSourceRange();
1879 Diag(Param->getLocation(), diag::note_template_param_here);
1880 return true;
1881 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001882 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00001883 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1884 << ArgType << Arg->getSourceRange();
1885 return true;
1886 }
1887
1888 // FIXME: We need some way to more easily get the unqualified form
1889 // of the types without going all the way to the
1890 // canonical type.
1891 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1892 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1893 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1894 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1895
1896 // Try to convert the argument to the parameter's type.
1897 if (ParamType == ArgType) {
1898 // Okay: no conversion necessary
1899 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1900 !ParamType->isEnumeralType()) {
1901 // This is an integral promotion or conversion.
1902 ImpCastExprToType(Arg, ParamType);
1903 } else {
1904 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00001905 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001906 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00001907 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00001908 Diag(Param->getLocation(), diag::note_template_param_here);
1909 return true;
1910 }
1911
Douglas Gregor52aba872009-03-14 00:20:21 +00001912 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00001913 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001914 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00001915
1916 if (!Arg->isValueDependent()) {
1917 // Check that an unsigned parameter does not receive a negative
1918 // value.
1919 if (IntegerType->isUnsignedIntegerType()
1920 && (Value.isSigned() && Value.isNegative())) {
1921 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1922 << Value.toString(10) << Param->getType()
1923 << Arg->getSourceRange();
1924 Diag(Param->getLocation(), diag::note_template_param_here);
1925 return true;
1926 }
1927
1928 // Check that we don't overflow the template parameter type.
1929 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1930 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00001931 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00001932 diag::err_template_arg_too_large)
1933 << Value.toString(10) << Param->getType()
1934 << Arg->getSourceRange();
1935 Diag(Param->getLocation(), diag::note_template_param_here);
1936 return true;
1937 }
1938
1939 if (Value.getBitWidth() != AllowedBits)
1940 Value.extOrTrunc(AllowedBits);
1941 Value.setIsSigned(IntegerType->isSignedIntegerType());
1942 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001943
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001944 // Add the value of this argument to the list of converted
1945 // arguments. We use the bitwidth and signedness of the template
1946 // parameter.
1947 if (Arg->isValueDependent()) {
1948 // The argument is value-dependent. Create a new
1949 // TemplateArgument with the converted expression.
1950 Converted = TemplateArgument(Arg);
1951 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001952 }
1953
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001954 Converted = TemplateArgument(StartLoc, Value,
Mike Stump11289f42009-09-09 15:08:12 +00001955 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001956 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00001957 return false;
1958 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001959
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001960 // Handle pointer-to-function, reference-to-function, and
1961 // pointer-to-member-function all in (roughly) the same way.
1962 if (// -- For a non-type template-parameter of type pointer to
1963 // function, only the function-to-pointer conversion (4.3) is
1964 // applied. If the template-argument represents a set of
1965 // overloaded functions (or a pointer to such), the matching
1966 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00001967 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001968 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001969 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001970 // -- For a non-type template-parameter of type reference to
1971 // function, no conversions apply. If the template-argument
1972 // represents a set of overloaded functions, the matching
1973 // function is selected from the set (13.4).
1974 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001975 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001976 // -- For a non-type template-parameter of type pointer to
1977 // member function, no conversions apply. If the
1978 // template-argument represents a set of overloaded member
1979 // functions, the matching member function is selected from
1980 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00001981 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001982 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001983 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001984 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00001985 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00001986 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001987 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00001988 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1989 ParamType->isMemberPointerType())) {
1990 ArgType = ParamType;
1991 ImpCastExprToType(Arg, ParamType);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001992 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001993 ArgType = Context.getPointerType(ArgType);
1994 ImpCastExprToType(Arg, ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001995 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001996 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00001997 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1998 return true;
1999
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002000 FixOverloadedFunctionReference(Arg, Fn);
2001 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002002 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002003 ArgType = Context.getPointerType(Arg->getType());
2004 ImpCastExprToType(Arg, ArgType);
2005 }
2006 }
2007
Mike Stump11289f42009-09-09 15:08:12 +00002008 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002009 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002010 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002011 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002012 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002013 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002014 Diag(Param->getLocation(), diag::note_template_param_here);
2015 return true;
2016 }
Mike Stump11289f42009-09-09 15:08:12 +00002017
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002018 if (ParamType->isMemberPointerType()) {
2019 NamedDecl *Member = 0;
2020 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2021 return true;
2022
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002023 if (Member)
2024 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002025 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002026 return false;
2027 }
Mike Stump11289f42009-09-09 15:08:12 +00002028
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002029 NamedDecl *Entity = 0;
2030 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2031 return true;
2032
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002033 if (Entity)
2034 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002035 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002036 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002037 }
2038
Chris Lattner696197c2009-02-20 21:37:53 +00002039 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002040 // -- for a non-type template-parameter of type pointer to
2041 // object, qualification conversions (4.4) and the
2042 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002043 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002044 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002045 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002046
Sebastian Redl576fd422009-05-10 18:38:11 +00002047 if (ArgType->isNullPtrType()) {
2048 ArgType = ParamType;
2049 ImpCastExprToType(Arg, ParamType);
2050 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002051 ArgType = Context.getArrayDecayedType(ArgType);
2052 ImpCastExprToType(Arg, ArgType);
Douglas Gregora9faa442009-02-11 00:44:29 +00002053 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002054
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002055 if (IsQualificationConversion(ArgType, ParamType)) {
2056 ArgType = ParamType;
2057 ImpCastExprToType(Arg, ParamType);
2058 }
Mike Stump11289f42009-09-09 15:08:12 +00002059
Douglas Gregor1515f762009-02-11 18:22:40 +00002060 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002061 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002062 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002063 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002064 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002065 Diag(Param->getLocation(), diag::note_template_param_here);
2066 return true;
2067 }
Mike Stump11289f42009-09-09 15:08:12 +00002068
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002069 NamedDecl *Entity = 0;
2070 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2071 return true;
2072
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002073 if (Entity)
2074 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002075 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002076 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002077 }
Mike Stump11289f42009-09-09 15:08:12 +00002078
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002079 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002080 // -- For a non-type template-parameter of type reference to
2081 // object, no conversions apply. The type referred to by the
2082 // reference may be more cv-qualified than the (otherwise
2083 // identical) type of the template-argument. The
2084 // template-parameter is bound directly to the
2085 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002086 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002087 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002088
Douglas Gregor1515f762009-02-11 18:22:40 +00002089 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002090 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002091 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002092 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002093 << Arg->getSourceRange();
2094 Diag(Param->getLocation(), diag::note_template_param_here);
2095 return true;
2096 }
2097
Mike Stump11289f42009-09-09 15:08:12 +00002098 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002099 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2100 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002101
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002102 if ((ParamQuals | ArgQuals) != ParamQuals) {
2103 Diag(Arg->getSourceRange().getBegin(),
2104 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002105 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002106 << Arg->getSourceRange();
2107 Diag(Param->getLocation(), diag::note_template_param_here);
2108 return true;
2109 }
Mike Stump11289f42009-09-09 15:08:12 +00002110
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002111 NamedDecl *Entity = 0;
2112 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2113 return true;
2114
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002115 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002116 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002117 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002118 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002119
2120 // -- For a non-type template-parameter of type pointer to data
2121 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002122 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002123 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2124
Douglas Gregor1515f762009-02-11 18:22:40 +00002125 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002126 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002127 } else if (ArgType->isNullPtrType()) {
2128 ImpCastExprToType(Arg, ParamType);
Douglas Gregor0e558532009-02-11 16:16:59 +00002129 } else if (IsQualificationConversion(ArgType, ParamType)) {
2130 ImpCastExprToType(Arg, ParamType);
2131 } else {
2132 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002133 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002134 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002135 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002136 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002137 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002138 }
2139
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002140 NamedDecl *Member = 0;
2141 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2142 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002143
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002144 if (Member)
2145 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002146 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002147 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00002148}
2149
2150/// \brief Check a template argument against its corresponding
2151/// template template parameter.
2152///
2153/// This routine implements the semantics of C++ [temp.arg.template].
2154/// It returns true if an error occurred, and false otherwise.
2155bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2156 DeclRefExpr *Arg) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002157 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2158 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2159
2160 // C++ [temp.arg.template]p1:
2161 // A template-argument for a template template-parameter shall be
2162 // the name of a class template, expressed as id-expression. Only
2163 // primary class templates are considered when matching the
2164 // template template argument with the corresponding parameter;
2165 // partial specializations are not considered even if their
2166 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002167 //
2168 // Note that we also allow template template parameters here, which
2169 // will happen when we are dealing with, e.g., class template
2170 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002171 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002172 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002173 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002174 "Only function templates are possible here");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002175 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2176 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002177 << Template;
2178 }
2179
2180 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2181 Param->getTemplateParameters(),
2182 true, true,
2183 Arg->getSourceRange().getBegin());
Douglas Gregord32e0282009-02-09 23:23:08 +00002184}
2185
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002186/// \brief Determine whether the given template parameter lists are
2187/// equivalent.
2188///
Mike Stump11289f42009-09-09 15:08:12 +00002189/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002190/// source code as part of a new template declaration.
2191///
2192/// \param Old The old template parameter list, typically found via
2193/// name lookup of the template declared with this template parameter
2194/// list.
2195///
2196/// \param Complain If true, this routine will produce a diagnostic if
2197/// the template parameter lists are not equivalent.
2198///
Douglas Gregor85e0f662009-02-10 00:24:35 +00002199/// \param IsTemplateTemplateParm If true, this routine is being
2200/// called to compare the template parameter lists of a template
2201/// template parameter.
2202///
2203/// \param TemplateArgLoc If this source location is valid, then we
2204/// are actually checking the template parameter list of a template
2205/// argument (New) against the template parameter list of its
2206/// corresponding template template parameter (Old). We produce
2207/// slightly different diagnostics in this scenario.
2208///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002209/// \returns True if the template parameter lists are equal, false
2210/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002211bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002212Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2213 TemplateParameterList *Old,
2214 bool Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002215 bool IsTemplateTemplateParm,
2216 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002217 if (Old->size() != New->size()) {
2218 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002219 unsigned NextDiag = diag::err_template_param_list_different_arity;
2220 if (TemplateArgLoc.isValid()) {
2221 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2222 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002223 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002224 Diag(New->getTemplateLoc(), NextDiag)
2225 << (New->size() > Old->size())
2226 << IsTemplateTemplateParm
2227 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002228 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2229 << IsTemplateTemplateParm
2230 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2231 }
2232
2233 return false;
2234 }
2235
2236 for (TemplateParameterList::iterator OldParm = Old->begin(),
2237 OldParmEnd = Old->end(), NewParm = New->begin();
2238 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2239 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002240 if (Complain) {
2241 unsigned NextDiag = diag::err_template_param_different_kind;
2242 if (TemplateArgLoc.isValid()) {
2243 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2244 NextDiag = diag::note_template_param_different_kind;
2245 }
2246 Diag((*NewParm)->getLocation(), NextDiag)
2247 << IsTemplateTemplateParm;
2248 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2249 << IsTemplateTemplateParm;
Douglas Gregor85e0f662009-02-10 00:24:35 +00002250 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002251 return false;
2252 }
2253
2254 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2255 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002256 // know we're at the same index).
2257#if 0
Mike Stump87c57ac2009-05-16 07:39:55 +00002258 // FIXME: Enable this code in debug mode *after* we properly go through
2259 // and "instantiate" the template parameter lists of template template
2260 // parameters. It's only after this instantiation that (1) any dependent
2261 // types within the template parameter list of the template template
2262 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregor85e0f662009-02-10 00:24:35 +00002263 // will match up.
Mike Stump11289f42009-09-09 15:08:12 +00002264 QualType OldParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002265 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
Mike Stump11289f42009-09-09 15:08:12 +00002266 QualType NewParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002267 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
Mike Stump11289f42009-09-09 15:08:12 +00002268 assert(Context.getCanonicalType(OldParmType) ==
2269 Context.getCanonicalType(NewParmType) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002270 "type parameter mismatch?");
2271#endif
Mike Stump11289f42009-09-09 15:08:12 +00002272 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002273 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2274 // The types of non-type template parameters must agree.
2275 NonTypeTemplateParmDecl *NewNTTP
2276 = cast<NonTypeTemplateParmDecl>(*NewParm);
2277 if (Context.getCanonicalType(OldNTTP->getType()) !=
2278 Context.getCanonicalType(NewNTTP->getType())) {
2279 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002280 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2281 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002282 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002283 diag::err_template_arg_template_params_mismatch);
2284 NextDiag = diag::note_template_nontype_parm_different_type;
2285 }
2286 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002287 << NewNTTP->getType()
2288 << IsTemplateTemplateParm;
Mike Stump11289f42009-09-09 15:08:12 +00002289 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002290 diag::note_template_nontype_parm_prev_declaration)
2291 << OldNTTP->getType();
2292 }
2293 return false;
2294 }
2295 } else {
2296 // The template parameter lists of template template
2297 // parameters must agree.
2298 // FIXME: Could we perform a faster "type" comparison here?
Mike Stump11289f42009-09-09 15:08:12 +00002299 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002300 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002301 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002302 = cast<TemplateTemplateParmDecl>(*OldParm);
2303 TemplateTemplateParmDecl *NewTTP
2304 = cast<TemplateTemplateParmDecl>(*NewParm);
2305 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2306 OldTTP->getTemplateParameters(),
2307 Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002308 /*IsTemplateTemplateParm=*/true,
2309 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002310 return false;
2311 }
2312 }
2313
2314 return true;
2315}
2316
2317/// \brief Check whether a template can be declared within this scope.
2318///
2319/// If the template declaration is valid in this scope, returns
2320/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002321bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002322Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002323 // Find the nearest enclosing declaration scope.
2324 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2325 (S->getFlags() & Scope::TemplateParamScope) != 0)
2326 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002327
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002328 // C++ [temp]p2:
2329 // A template-declaration can appear only as a namespace scope or
2330 // class scope declaration.
2331 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002332 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2333 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002334 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002335 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002336
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002337 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002338 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002339
2340 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2341 return false;
2342
Mike Stump11289f42009-09-09 15:08:12 +00002343 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002344 diag::err_template_outside_namespace_or_class_scope)
2345 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002346}
Douglas Gregor67a65642009-02-17 23:15:12 +00002347
Douglas Gregor54888652009-10-07 00:13:32 +00002348/// \brief Determine what kind of template specialization the given declaration
2349/// is.
2350static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2351 if (!D)
2352 return TSK_Undeclared;
2353
2354 if (ClassTemplateSpecializationDecl *CTS
2355 = dyn_cast<ClassTemplateSpecializationDecl>(D))
2356 return CTS->getSpecializationKind();
2357 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2358 return Function->getTemplateSpecializationKind();
2359
2360 // FIXME: static data members!
2361 // FIXME: member classes of class templates!
2362 return TSK_Undeclared;
2363}
2364
2365/// \brief Check whether a specialization or explicit instantiation is
2366/// well-formed in the current context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002367///
Douglas Gregor54888652009-10-07 00:13:32 +00002368/// This routine determines whether a template specialization or
Mike Stump11289f42009-09-09 15:08:12 +00002369/// explicit instantiation can be declared in the current context
Douglas Gregor54888652009-10-07 00:13:32 +00002370/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2).
2371///
2372/// \param S the semantic analysis object for which this check is being
2373/// performed.
2374///
2375/// \param Specialized the entity being specialized or instantiated, which
2376/// may be a kind of template (class template, function template, etc.) or
2377/// a member of a class template (member function, static data member,
2378/// member class).
2379///
2380/// \param PrevDecl the previous declaration of this entity, if any.
2381///
2382/// \param Loc the location of the explicit specialization or instantiation of
2383/// this entity.
2384///
2385/// \param IsPartialSpecialization whether this is a partial specialization of
2386/// a class template.
2387///
2388/// \param TSK the kind of specialization or implicit instantiation being
2389/// performed.
2390///
2391/// \returns true if there was an error that we cannot recover from, false
2392/// otherwise.
2393static bool CheckTemplateSpecializationScope(Sema &S,
2394 NamedDecl *Specialized,
2395 NamedDecl *PrevDecl,
2396 SourceLocation Loc,
2397 bool IsPartialSpecialization,
2398 TemplateSpecializationKind TSK) {
2399 // Keep these "kind" numbers in sync with the %select statements in the
2400 // various diagnostics emitted by this routine.
2401 int EntityKind = 0;
2402 if (isa<ClassTemplateDecl>(Specialized))
2403 EntityKind = IsPartialSpecialization? 1 : 0;
2404 else if (isa<FunctionTemplateDecl>(Specialized))
2405 EntityKind = 2;
2406 else if (isa<CXXMethodDecl>(Specialized))
2407 EntityKind = 3;
2408 else if (isa<VarDecl>(Specialized))
2409 EntityKind = 4;
2410 else if (isa<RecordDecl>(Specialized))
2411 EntityKind = 5;
2412 else {
2413 S.Diag(Loc, diag::err_template_spec_unknown_kind) << TSK;
2414 S.Diag(Specialized->getLocation(), diag::note_specialized_entity) << TSK;
2415 return true;
2416 }
2417
Douglas Gregorf47b9112009-02-25 22:02:03 +00002418 // C++ [temp.expl.spec]p2:
2419 // An explicit specialization shall be declared in the namespace
2420 // of which the template is a member, or, for member templates, in
2421 // the namespace of which the enclosing class or enclosing class
2422 // template is a member. An explicit specialization of a member
2423 // function, member class or static data member of a class
2424 // template shall be declared in the namespace of which the class
2425 // template is a member. Such a declaration may also be a
2426 // definition. If the declaration is not a definition, the
2427 // specialization may be defined later in the name- space in which
2428 // the explicit specialization was declared, or in a namespace
2429 // that encloses the one in which the explicit specialization was
2430 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002431 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2432 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
2433 << TSK << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002434 return true;
2435 }
Douglas Gregor54888652009-10-07 00:13:32 +00002436
Douglas Gregore4b05162009-10-07 17:21:34 +00002437 // FIXME: For everything except class template partial specializations,
2438 // complain if the explicit specialization/instantiation occurs at class
2439 // scope.
2440
2441 // C++ [temp.class.spec]p6:
2442 // A class template partial specialization may be declared or redeclared
2443 // in any namespace scope in which its definition may be defined (14.5.1
2444 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002445 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002446 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002447 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002448 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor54888652009-10-07 00:13:32 +00002449 if (TSK == TSK_ExplicitSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002450 if ((!PrevDecl ||
2451 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2452 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2453 // There is no prior declaration of this entity, so this
2454 // specialization must be in the same context as the template
2455 // itself.
2456 if (!DC->Equals(SpecializedContext)) {
2457 if (isa<TranslationUnitDecl>(SpecializedContext))
2458 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2459 << EntityKind << Specialized;
2460 else if (isa<NamespaceDecl>(SpecializedContext))
2461 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2462 << EntityKind << Specialized
2463 << cast<NamedDecl>(SpecializedContext);
2464
2465 S.Diag(Specialized->getLocation(), diag::note_template_decl_here);
2466 ComplainedAboutScope = true;
2467 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002468 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002469 }
Douglas Gregor54888652009-10-07 00:13:32 +00002470
2471 // Make sure that this redeclaration (or definition) occurs in an enclosing
2472 // namespace. We perform this check for explicit specializations and, in
2473 // C++0x, for explicit instantiations as well (per DR275).
2474 // FIXME: -Wc++0x should make these warnings.
2475 // Note that HandleDeclarator() performs this check for explicit
2476 // specializations of function templates, static data members, and member
2477 // functions, so we skip the check here for those kinds of entities.
2478 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00002479 // Should we refactor that check, so that it occurs later?
2480 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor54888652009-10-07 00:13:32 +00002481 ((TSK == TSK_ExplicitSpecialization &&
2482 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2483 isa<FunctionDecl>(Specialized))) ||
2484 S.getLangOptions().CPlusPlus0x)) {
2485 if (isa<TranslationUnitDecl>(SpecializedContext))
2486 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2487 << EntityKind << Specialized;
2488 else if (isa<NamespaceDecl>(SpecializedContext))
2489 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2490 << EntityKind << Specialized
2491 << cast<NamedDecl>(SpecializedContext);
2492
2493 S.Diag(Specialized->getLocation(), diag::note_template_decl_here);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002494 }
Douglas Gregor54888652009-10-07 00:13:32 +00002495
2496 // FIXME: check for specialization-after-instantiation errors and such.
2497
Douglas Gregorf47b9112009-02-25 22:02:03 +00002498 return false;
2499}
Douglas Gregor54888652009-10-07 00:13:32 +00002500
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002501/// \brief Check the non-type template arguments of a class template
2502/// partial specialization according to C++ [temp.class.spec]p9.
2503///
Douglas Gregor09a30232009-06-12 22:08:06 +00002504/// \param TemplateParams the template parameters of the primary class
2505/// template.
2506///
2507/// \param TemplateArg the template arguments of the class template
2508/// partial specialization.
2509///
2510/// \param MirrorsPrimaryTemplate will be set true if the class
2511/// template partial specialization arguments are identical to the
2512/// implicit template arguments of the primary template. This is not
2513/// necessarily an error (C++0x), and it is left to the caller to diagnose
2514/// this condition when it is an error.
2515///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002516/// \returns true if there was an error, false otherwise.
2517bool Sema::CheckClassTemplatePartialSpecializationArgs(
2518 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002519 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002520 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002521 // FIXME: the interface to this function will have to change to
2522 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002523 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002524
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002525 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002526
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002527 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002528 // Determine whether the template argument list of the partial
2529 // specialization is identical to the implicit argument list of
2530 // the primary template. The caller may need to diagnostic this as
2531 // an error per C++ [temp.class.spec]p9b3.
2532 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002533 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002534 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2535 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002536 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002537 MirrorsPrimaryTemplate = false;
2538 } else if (TemplateTemplateParmDecl *TTP
2539 = dyn_cast<TemplateTemplateParmDecl>(
2540 TemplateParams->getParam(I))) {
2541 // FIXME: We should settle on either Declaration storage or
2542 // Expression storage for template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002543 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor09a30232009-06-12 22:08:06 +00002544 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson40c1d492009-06-13 18:20:51 +00002545 ArgList[I].getAsDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002546 if (!ArgDecl)
Mike Stump11289f42009-09-09 15:08:12 +00002547 if (DeclRefExpr *DRE
Anders Carlsson40c1d492009-06-13 18:20:51 +00002548 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002549 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2550
2551 if (!ArgDecl ||
2552 ArgDecl->getIndex() != TTP->getIndex() ||
2553 ArgDecl->getDepth() != TTP->getDepth())
2554 MirrorsPrimaryTemplate = false;
2555 }
2556 }
2557
Mike Stump11289f42009-09-09 15:08:12 +00002558 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002559 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002560 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002561 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002562 }
2563
Anders Carlsson40c1d492009-06-13 18:20:51 +00002564 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002565 if (!ArgExpr) {
2566 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002567 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002568 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002569
2570 // C++ [temp.class.spec]p8:
2571 // A non-type argument is non-specialized if it is the name of a
2572 // non-type parameter. All other non-type arguments are
2573 // specialized.
2574 //
2575 // Below, we check the two conditions that only apply to
2576 // specialized non-type arguments, so skip any non-specialized
2577 // arguments.
2578 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002579 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002580 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002581 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002582 (Param->getIndex() != NTTP->getIndex() ||
2583 Param->getDepth() != NTTP->getDepth()))
2584 MirrorsPrimaryTemplate = false;
2585
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002586 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002587 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002588
2589 // C++ [temp.class.spec]p9:
2590 // Within the argument list of a class template partial
2591 // specialization, the following restrictions apply:
2592 // -- A partially specialized non-type argument expression
2593 // shall not involve a template parameter of the partial
2594 // specialization except when the argument expression is a
2595 // simple identifier.
2596 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002597 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002598 diag::err_dependent_non_type_arg_in_partial_spec)
2599 << ArgExpr->getSourceRange();
2600 return true;
2601 }
2602
2603 // -- The type of a template parameter corresponding to a
2604 // specialized non-type argument shall not be dependent on a
2605 // parameter of the specialization.
2606 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002607 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002608 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2609 << Param->getType()
2610 << ArgExpr->getSourceRange();
2611 Diag(Param->getLocation(), diag::note_template_param_here);
2612 return true;
2613 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002614
2615 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002616 }
2617
2618 return false;
2619}
2620
Douglas Gregorc08f4892009-03-25 00:13:59 +00002621Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002622Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2623 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002624 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002625 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002626 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002627 SourceLocation TemplateNameLoc,
2628 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002629 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002630 SourceLocation *TemplateArgLocs,
2631 SourceLocation RAngleLoc,
2632 AttributeList *Attr,
2633 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00002634 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00002635
Douglas Gregor67a65642009-02-17 23:15:12 +00002636 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002637 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002638 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002639 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002640
Douglas Gregor2373c592009-05-31 09:31:02 +00002641 bool isPartialSpecialization = false;
2642
Douglas Gregorf47b9112009-02-25 22:02:03 +00002643 // Check the validity of the template headers that introduce this
2644 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00002645 // FIXME: We probably shouldn't complain about these headers for
2646 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002647 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002648 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2649 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002650 TemplateParameterLists.size());
2651 if (TemplateParams && TemplateParams->size() > 0) {
2652 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002653
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002654 // C++ [temp.class.spec]p10:
2655 // The template parameter list of a specialization shall not
2656 // contain default template argument values.
2657 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2658 Decl *Param = TemplateParams->getParam(I);
2659 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2660 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002661 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002662 diag::err_default_arg_in_partial_spec);
2663 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2664 }
2665 } else if (NonTypeTemplateParmDecl *NTTP
2666 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2667 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002668 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002669 diag::err_default_arg_in_partial_spec)
2670 << DefArg->getSourceRange();
2671 NTTP->setDefaultArgument(0);
2672 DefArg->Destroy(Context);
2673 }
2674 } else {
2675 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2676 if (Expr *DefArg = TTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002677 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002678 diag::err_default_arg_in_partial_spec)
2679 << DefArg->getSourceRange();
2680 TTP->setDefaultArgument(0);
2681 DefArg->Destroy(Context);
Douglas Gregord5222052009-06-12 19:43:02 +00002682 }
2683 }
2684 }
Douglas Gregor2208a292009-09-26 20:57:03 +00002685 } else if (!TemplateParams && TUK != TUK_Friend)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002686 Diag(KWLoc, diag::err_template_spec_needs_header)
2687 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregorf47b9112009-02-25 22:02:03 +00002688
Douglas Gregor67a65642009-02-17 23:15:12 +00002689 // Check that the specialization uses the same tag kind as the
2690 // original template.
2691 TagDecl::TagKind Kind;
2692 switch (TagSpec) {
2693 default: assert(0 && "Unknown tag type!");
2694 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2695 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2696 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2697 }
Douglas Gregord9034f02009-05-14 16:41:31 +00002698 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00002699 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00002700 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00002701 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00002702 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00002703 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00002704 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00002705 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00002706 diag::note_previous_use);
2707 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2708 }
2709
Douglas Gregorc40290e2009-03-09 23:48:35 +00002710 // Translate the parser's template argument list in our AST format.
2711 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2712 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2713
Douglas Gregor67a65642009-02-17 23:15:12 +00002714 // Check that the template argument list is well-formed for this
2715 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002716 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2717 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00002718 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002719 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00002720 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002721 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002722
Mike Stump11289f42009-09-09 15:08:12 +00002723 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00002724 ClassTemplate->getTemplateParameters()->size()) &&
2725 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00002726
Douglas Gregor2373c592009-05-31 09:31:02 +00002727 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00002728 // corresponds to these arguments.
2729 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00002730 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002731 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002732 if (CheckClassTemplatePartialSpecializationArgs(
2733 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002734 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002735 return true;
2736
Douglas Gregor09a30232009-06-12 22:08:06 +00002737 if (MirrorsPrimaryTemplate) {
2738 // C++ [temp.class.spec]p9b3:
2739 //
Mike Stump11289f42009-09-09 15:08:12 +00002740 // -- The argument list of the specialization shall not be identical
2741 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00002742 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00002743 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00002744 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00002745 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00002746 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00002747 ClassTemplate->getIdentifier(),
2748 TemplateNameLoc,
2749 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002750 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00002751 AS_none);
2752 }
2753
Douglas Gregor2208a292009-09-26 20:57:03 +00002754 // FIXME: Diagnose friend partial specializations
2755
Douglas Gregor2373c592009-05-31 09:31:02 +00002756 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00002757 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002758 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002759 Converted.flatSize(),
2760 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002761 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002762 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002763 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002764 Converted.flatSize(),
2765 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00002766 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002767 ClassTemplateSpecializationDecl *PrevDecl = 0;
2768
2769 if (isPartialSpecialization)
2770 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00002771 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00002772 InsertPos);
2773 else
2774 PrevDecl
2775 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00002776
2777 ClassTemplateSpecializationDecl *Specialization = 0;
2778
Douglas Gregorf47b9112009-02-25 22:02:03 +00002779 // Check whether we can declare a class template specialization in
2780 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00002781 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00002782 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
2783 TemplateNameLoc, isPartialSpecialization,
2784 TSK_ExplicitSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002785 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002786
Douglas Gregor15301382009-07-30 17:40:51 +00002787 // The canonical type
2788 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00002789 if (PrevDecl &&
2790 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
2791 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002792 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00002793 // arguments was referenced but not declared, or we're only
2794 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00002795 // declaration node as our own, updating its source location to
2796 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002797 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00002798 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00002799 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00002800 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00002801 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00002802 // Build the canonical type that describes the converted template
2803 // arguments of the class template partial specialization.
2804 CanonType = Context.getTemplateSpecializationType(
2805 TemplateName(ClassTemplate),
2806 Converted.getFlatArguments(),
2807 Converted.flatSize());
2808
Douglas Gregor2373c592009-05-31 09:31:02 +00002809 // Create a new class template partial specialization declaration node.
Mike Stump11289f42009-09-09 15:08:12 +00002810 TemplateParameterList *TemplateParams
Douglas Gregor2373c592009-05-31 09:31:02 +00002811 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2812 ClassTemplatePartialSpecializationDecl *PrevPartial
2813 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002814 ClassTemplatePartialSpecializationDecl *Partial
2815 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00002816 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002817 TemplateNameLoc,
2818 TemplateParams,
2819 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002820 Converted,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002821 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00002822
2823 if (PrevPartial) {
2824 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2825 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2826 } else {
2827 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2828 }
2829 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00002830
2831 // Check that all of the template parameters of the class template
2832 // partial specialization are deducible from the template
2833 // arguments. If not, this class template partial specialization
2834 // will never be used.
2835 llvm::SmallVector<bool, 8> DeducibleParams;
2836 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002837 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2838 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00002839 unsigned NumNonDeducible = 0;
2840 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2841 if (!DeducibleParams[I])
2842 ++NumNonDeducible;
2843
2844 if (NumNonDeducible) {
2845 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2846 << (NumNonDeducible > 1)
2847 << SourceRange(TemplateNameLoc, RAngleLoc);
2848 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2849 if (!DeducibleParams[I]) {
2850 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2851 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00002852 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002853 diag::note_partial_spec_unused_parameter)
2854 << Param->getDeclName();
2855 else
Mike Stump11289f42009-09-09 15:08:12 +00002856 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002857 diag::note_partial_spec_unused_parameter)
2858 << std::string("<anonymous>");
2859 }
2860 }
2861 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002862 } else {
2863 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00002864 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002865 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00002866 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00002867 ClassTemplate->getDeclContext(),
2868 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002869 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002870 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00002871 PrevDecl);
2872
2873 if (PrevDecl) {
2874 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2875 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2876 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002877 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00002878 InsertPos);
2879 }
Douglas Gregor15301382009-07-30 17:40:51 +00002880
2881 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002882 }
2883
Douglas Gregor2208a292009-09-26 20:57:03 +00002884 // If this is not a friend, note that this is an explicit specialization.
2885 if (TUK != TUK_Friend)
2886 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002887
2888 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002889 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002890 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002891 // FIXME: Should also handle explicit specialization after implicit
2892 // instantiation with a special diagnostic.
Douglas Gregor67a65642009-02-17 23:15:12 +00002893 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002894 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00002895 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00002896 Diag(Def->getLocation(), diag::note_previous_definition);
2897 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00002898 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002899 }
2900 }
2901
Douglas Gregord56a91e2009-02-26 22:19:44 +00002902 // Build the fully-sugared type for this class template
2903 // specialization as the user wrote in the specialization
2904 // itself. This means that we'll pretty-print the type retrieved
2905 // from the specialization's declaration the way that the user
2906 // actually wrote the specialization, rather than formatting the
2907 // name based on the "canonical" representation used to store the
2908 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002909 QualType WrittenTy
2910 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002911 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00002912 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00002913 CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00002914 if (TUK != TUK_Friend)
2915 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002916 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00002917
Douglas Gregor1e249f82009-02-25 22:18:32 +00002918 // C++ [temp.expl.spec]p9:
2919 // A template explicit specialization is in the scope of the
2920 // namespace in which the template was defined.
2921 //
2922 // We actually implement this paragraph where we set the semantic
2923 // context (in the creation of the ClassTemplateSpecializationDecl),
2924 // but we also maintain the lexical context where the actual
2925 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00002926 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00002927
Douglas Gregor67a65642009-02-17 23:15:12 +00002928 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002929 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00002930 Specialization->startDefinition();
2931
Douglas Gregor2208a292009-09-26 20:57:03 +00002932 if (TUK == TUK_Friend) {
2933 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
2934 TemplateNameLoc,
2935 WrittenTy.getTypePtr(),
2936 /*FIXME:*/KWLoc);
2937 Friend->setAccess(AS_public);
2938 CurContext->addDecl(Friend);
2939 } else {
2940 // Add the specialization into its lexical context, so that it can
2941 // be seen when iterating through the list of declarations in that
2942 // context. However, specializations are not found by name lookup.
2943 CurContext->addDecl(Specialization);
2944 }
Chris Lattner83f095c2009-03-28 19:18:32 +00002945 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002946}
Douglas Gregor333489b2009-03-27 23:10:48 +00002947
Mike Stump11289f42009-09-09 15:08:12 +00002948Sema::DeclPtrTy
2949Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002950 MultiTemplateParamsArg TemplateParameterLists,
2951 Declarator &D) {
2952 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2953}
2954
Mike Stump11289f42009-09-09 15:08:12 +00002955Sema::DeclPtrTy
2956Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002957 MultiTemplateParamsArg TemplateParameterLists,
2958 Declarator &D) {
2959 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2960 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2961 "Not a function declarator!");
2962 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00002963
Douglas Gregor17a7c122009-06-24 00:54:41 +00002964 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00002965 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00002966 }
Mike Stump11289f42009-09-09 15:08:12 +00002967
Douglas Gregor17a7c122009-06-24 00:54:41 +00002968 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002969
2970 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002971 move(TemplateParameterLists),
2972 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002973 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00002974 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00002975 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002976 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00002977 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2978 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002979 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00002980}
2981
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002982/// \brief Perform semantic analysis for the given function template
2983/// specialization.
2984///
2985/// This routine performs all of the semantic analysis required for an
2986/// explicit function template specialization. On successful completion,
2987/// the function declaration \p FD will become a function template
2988/// specialization.
2989///
2990/// \param FD the function declaration, which will be updated to become a
2991/// function template specialization.
2992///
2993/// \param HasExplicitTemplateArgs whether any template arguments were
2994/// explicitly provided.
2995///
2996/// \param LAngleLoc the location of the left angle bracket ('<'), if
2997/// template arguments were explicitly provided.
2998///
2999/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3000/// if any.
3001///
3002/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3003/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3004/// true as in, e.g., \c void sort<>(char*, char*);
3005///
3006/// \param RAngleLoc the location of the right angle bracket ('>'), if
3007/// template arguments were explicitly provided.
3008///
3009/// \param PrevDecl the set of declarations that
3010bool
3011Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3012 bool HasExplicitTemplateArgs,
3013 SourceLocation LAngleLoc,
3014 const TemplateArgument *ExplicitTemplateArgs,
3015 unsigned NumExplicitTemplateArgs,
3016 SourceLocation RAngleLoc,
3017 NamedDecl *&PrevDecl) {
3018 // The set of function template specializations that could match this
3019 // explicit function template specialization.
3020 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3021 CandidateSet Candidates;
3022
3023 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3024 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3025 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3026 // Only consider templates found within the same semantic lookup scope as
3027 // FD.
3028 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3029 continue;
3030
3031 // C++ [temp.expl.spec]p11:
3032 // A trailing template-argument can be left unspecified in the
3033 // template-id naming an explicit function template specialization
3034 // provided it can be deduced from the function argument type.
3035 // Perform template argument deduction to determine whether we may be
3036 // specializing this template.
3037 // FIXME: It is somewhat wasteful to build
3038 TemplateDeductionInfo Info(Context);
3039 FunctionDecl *Specialization = 0;
3040 if (TemplateDeductionResult TDK
3041 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3042 ExplicitTemplateArgs,
3043 NumExplicitTemplateArgs,
3044 FD->getType(),
3045 Specialization,
3046 Info)) {
3047 // FIXME: Template argument deduction failed; record why it failed, so
3048 // that we can provide nifty diagnostics.
3049 (void)TDK;
3050 continue;
3051 }
3052
3053 // Record this candidate.
3054 Candidates.push_back(Specialization);
3055 }
3056 }
3057
Douglas Gregor5de279c2009-09-26 03:41:46 +00003058 // Find the most specialized function template.
3059 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3060 Candidates.size(),
3061 TPOC_Other,
3062 FD->getLocation(),
3063 PartialDiagnostic(diag::err_function_template_spec_no_match)
3064 << FD->getDeclName(),
3065 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3066 << FD->getDeclName() << HasExplicitTemplateArgs,
3067 PartialDiagnostic(diag::note_function_template_spec_matched));
3068 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003069 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003070
3071 // FIXME: Check if the prior specialization has a point of instantiation.
3072 // If so, we have run afoul of C++ [temp.expl.spec]p6.
3073
Douglas Gregor54888652009-10-07 00:13:32 +00003074 // Check the scope of this explicit specialization.
3075 if (CheckTemplateSpecializationScope(*this,
3076 Specialization->getPrimaryTemplate(),
3077 Specialization, FD->getLocation(),
3078 false, TSK_ExplicitSpecialization))
3079 return true;
3080
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003081 // Mark the prior declaration as an explicit specialization, so that later
3082 // clients know that this is an explicit specialization.
3083 // FIXME: Check for prior explicit instantiations?
3084 Specialization->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
3085
3086 // Turn the given function declaration into a function template
3087 // specialization, with the template arguments from the previous
3088 // specialization.
3089 FD->setFunctionTemplateSpecialization(Context,
3090 Specialization->getPrimaryTemplate(),
3091 new (Context) TemplateArgumentList(
3092 *Specialization->getTemplateSpecializationArgs()),
3093 /*InsertPos=*/0,
3094 TSK_ExplicitSpecialization);
3095
3096 // The "previous declaration" for this function template specialization is
3097 // the prior function template specialization.
3098 PrevDecl = Specialization;
3099 return false;
3100}
3101
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003102// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003103// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003104Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003105Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003106 SourceLocation ExternLoc,
3107 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003108 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003109 SourceLocation KWLoc,
3110 const CXXScopeSpec &SS,
3111 TemplateTy TemplateD,
3112 SourceLocation TemplateNameLoc,
3113 SourceLocation LAngleLoc,
3114 ASTTemplateArgsPtr TemplateArgsIn,
3115 SourceLocation *TemplateArgLocs,
3116 SourceLocation RAngleLoc,
3117 AttributeList *Attr) {
3118 // Find the class template we're specializing
3119 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003120 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003121 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3122
3123 // Check that the specialization uses the same tag kind as the
3124 // original template.
3125 TagDecl::TagKind Kind;
3126 switch (TagSpec) {
3127 default: assert(0 && "Unknown tag type!");
3128 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3129 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3130 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3131 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003132 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003133 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003134 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003135 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003136 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003137 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003138 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003139 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003140 diag::note_previous_use);
3141 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3142 }
3143
Douglas Gregor54888652009-10-07 00:13:32 +00003144 TemplateSpecializationKind TSK
3145 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3146 : TSK_ExplicitInstantiationDeclaration;
3147
Douglas Gregora1f49972009-05-13 00:25:59 +00003148 // Translate the parser's template argument list in our AST format.
3149 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3150 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3151
3152 // Check that the template argument list is well-formed for this
3153 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003154 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3155 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003156 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003157 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003158 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003159 return true;
3160
Mike Stump11289f42009-09-09 15:08:12 +00003161 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003162 ClassTemplate->getTemplateParameters()->size()) &&
3163 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003164
Douglas Gregora1f49972009-05-13 00:25:59 +00003165 // Find the class template specialization declaration that
3166 // corresponds to these arguments.
3167 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003168 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003169 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003170 Converted.flatSize(),
3171 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003172 void *InsertPos = 0;
3173 ClassTemplateSpecializationDecl *PrevDecl
3174 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3175
Douglas Gregor54888652009-10-07 00:13:32 +00003176 // C++0x [temp.explicit]p2:
3177 // [...] An explicit instantiation shall appear in an enclosing
3178 // namespace of its template. [...]
3179 //
3180 // This is C++ DR 275.
3181 if (CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
3182 TemplateNameLoc, false,
3183 TSK))
3184 return true;
3185
Douglas Gregora1f49972009-05-13 00:25:59 +00003186 ClassTemplateSpecializationDecl *Specialization = 0;
3187
Douglas Gregorf61eca92009-05-13 18:28:20 +00003188 bool SpecializationRequiresInstantiation = true;
Douglas Gregora1f49972009-05-13 00:25:59 +00003189 if (PrevDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003190 if (PrevDecl->getSpecializationKind()
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003191 == TSK_ExplicitInstantiationDefinition) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003192 // This particular specialization has already been declared or
3193 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorf61eca92009-05-13 18:28:20 +00003194 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
3195 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003196 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003197 diag::note_previous_explicit_instantiation);
Douglas Gregora1f49972009-05-13 00:25:59 +00003198 return DeclPtrTy::make(PrevDecl);
3199 }
3200
Douglas Gregorf61eca92009-05-13 18:28:20 +00003201 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003202 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorf61eca92009-05-13 18:28:20 +00003203 // For a given set of template parameters, if an explicit
3204 // instantiation of a template appears after a declaration of
3205 // an explicit specialization for that template, the explicit
3206 // instantiation has no effect.
3207 if (!getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00003208 Diag(TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003209 diag::ext_explicit_instantiation_after_specialization)
3210 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003211 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003212 diag::note_previous_template_specialization);
3213 }
3214
3215 // Create a new class template specialization declaration node
3216 // for this explicit specialization. This node is only used to
3217 // record the existence of this explicit instantiation for
3218 // accurate reproduction of the source code; we don't actually
3219 // use it for anything, since it is semantically irrelevant.
3220 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003221 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003222 ClassTemplate->getDeclContext(),
3223 TemplateNameLoc,
3224 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003225 Converted, 0);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003226 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003227 CurContext->addDecl(Specialization);
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003228 return DeclPtrTy::make(PrevDecl);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003229 }
3230
3231 // If we have already (implicitly) instantiated this
3232 // specialization, there is less work to do.
3233 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
3234 SpecializationRequiresInstantiation = false;
3235
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003236 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3237 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3238 // Since the only prior class template specialization with these
3239 // arguments was referenced but not declared, reuse that
3240 // declaration node as our own, updating its source location to
3241 // reflect our new declaration.
3242 Specialization = PrevDecl;
3243 Specialization->setLocation(TemplateNameLoc);
3244 PrevDecl = 0;
3245 }
3246 }
3247
3248 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003249 // Create a new class template specialization declaration node for
3250 // this explicit specialization.
3251 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003252 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003253 ClassTemplate->getDeclContext(),
3254 TemplateNameLoc,
3255 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003256 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003257
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003258 if (PrevDecl) {
3259 // Remove the previous declaration from the folding set, since we want
3260 // to introduce a new declaration.
3261 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3262 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3263 }
3264
3265 // Insert the new specialization.
3266 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003267 }
3268
3269 // Build the fully-sugared type for this explicit instantiation as
3270 // the user wrote in the explicit instantiation itself. This means
3271 // that we'll pretty-print the type retrieved from the
3272 // specialization's declaration the way that the user actually wrote
3273 // the explicit instantiation, rather than formatting the name based
3274 // on the "canonical" representation used to store the template
3275 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003276 QualType WrittenTy
3277 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003278 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003279 TemplateArgs.size(),
3280 Context.getTypeDeclType(Specialization));
3281 Specialization->setTypeAsWritten(WrittenTy);
3282 TemplateArgsIn.release();
3283
3284 // Add the explicit instantiation into its lexical context. However,
3285 // since explicit instantiations are never found by name lookup, we
3286 // just put it into the declaration context directly.
3287 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003288 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003289
John McCall1806c272009-09-11 07:25:08 +00003290 Specialization->setPointOfInstantiation(TemplateNameLoc);
3291
Douglas Gregora1f49972009-05-13 00:25:59 +00003292 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003293 // A definition of a class template or class member template
3294 // shall be in scope at the point of the explicit instantiation of
3295 // the class template or class member template.
3296 //
3297 // This check comes when we actually try to perform the
3298 // instantiation.
Douglas Gregor67da0d92009-05-15 17:59:04 +00003299 if (SpecializationRequiresInstantiation)
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003300 InstantiateClassTemplateSpecialization(Specialization, TSK);
Douglas Gregor85673582009-05-18 17:01:57 +00003301 else // Instantiate the members of this class template specialization.
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003302 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization,
3303 TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003304
3305 return DeclPtrTy::make(Specialization);
3306}
3307
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003308// Explicit instantiation of a member class of a class template.
3309Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003310Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003311 SourceLocation ExternLoc,
3312 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003313 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003314 SourceLocation KWLoc,
3315 const CXXScopeSpec &SS,
3316 IdentifierInfo *Name,
3317 SourceLocation NameLoc,
3318 AttributeList *Attr) {
3319
Douglas Gregord6ab8742009-05-28 23:31:59 +00003320 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003321 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00003322 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00003323 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00003324 MultiTemplateParamsArg(*this, 0, 0),
3325 Owned, IsDependent);
3326 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3327
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003328 if (!TagD)
3329 return true;
3330
3331 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3332 if (Tag->isEnum()) {
3333 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3334 << Context.getTypeDeclType(Tag);
3335 return true;
3336 }
3337
Douglas Gregorb8006faf2009-05-27 17:30:49 +00003338 if (Tag->isInvalidDecl())
3339 return true;
3340
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003341 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3342 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3343 if (!Pattern) {
3344 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3345 << Context.getTypeDeclType(Record);
3346 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3347 return true;
3348 }
3349
3350 // C++0x [temp.explicit]p2:
3351 // [...] An explicit instantiation shall appear in an enclosing
3352 // namespace of its template. [...]
3353 //
3354 // This is C++ DR 275.
3355 if (getLangOptions().CPlusPlus0x) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003356 // FIXME: In C++98, we would like to turn these errors into warnings,
3357 // dependent on a -Wc++0x flag.
Mike Stump11289f42009-09-09 15:08:12 +00003358 DeclContext *PatternContext
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003359 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
3360 if (!CurContext->Encloses(PatternContext)) {
3361 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
3362 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
3363 Diag(Pattern->getLocation(), diag::note_previous_declaration);
3364 }
3365 }
3366
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003367 TemplateSpecializationKind TSK
Mike Stump11289f42009-09-09 15:08:12 +00003368 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003369 : TSK_ExplicitInstantiationDeclaration;
Mike Stump11289f42009-09-09 15:08:12 +00003370
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003371 if (!Record->getDefinition(Context)) {
3372 // If the class has a definition, instantiate it (and all of its
3373 // members, recursively).
3374 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
Mike Stump11289f42009-09-09 15:08:12 +00003375 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregorb4850462009-05-14 23:26:13 +00003376 getTemplateInstantiationArgs(Record),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003377 TSK))
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003378 return true;
John McCall76d824f2009-08-25 22:02:44 +00003379 } else // Instantiate all of the members of the class.
Mike Stump11289f42009-09-09 15:08:12 +00003380 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003381 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003382
Mike Stump87c57ac2009-05-16 07:39:55 +00003383 // FIXME: We don't have any representation for explicit instantiations of
3384 // member classes. Such a representation is not needed for compilation, but it
3385 // should be available for clients that want to see all of the declarations in
3386 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003387 return TagD;
3388}
3389
Douglas Gregor450f00842009-09-25 18:43:00 +00003390Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
3391 SourceLocation ExternLoc,
3392 SourceLocation TemplateLoc,
3393 Declarator &D) {
3394 // Explicit instantiations always require a name.
3395 DeclarationName Name = GetNameForDeclarator(D);
3396 if (!Name) {
3397 if (!D.isInvalidType())
3398 Diag(D.getDeclSpec().getSourceRange().getBegin(),
3399 diag::err_explicit_instantiation_requires_name)
3400 << D.getDeclSpec().getSourceRange()
3401 << D.getSourceRange();
3402
3403 return true;
3404 }
3405
3406 // The scope passed in may not be a decl scope. Zip up the scope tree until
3407 // we find one that is.
3408 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3409 (S->getFlags() & Scope::TemplateParamScope) != 0)
3410 S = S->getParent();
3411
3412 // Determine the type of the declaration.
3413 QualType R = GetTypeForDeclarator(D, S, 0);
3414 if (R.isNull())
3415 return true;
3416
3417 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3418 // Cannot explicitly instantiate a typedef.
3419 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
3420 << Name;
3421 return true;
3422 }
3423
3424 // Determine what kind of explicit instantiation we have.
3425 TemplateSpecializationKind TSK
3426 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3427 : TSK_ExplicitInstantiationDeclaration;
3428
3429 LookupResult Previous = LookupParsedName(S, &D.getCXXScopeSpec(),
3430 Name, LookupOrdinaryName);
3431
3432 if (!R->isFunctionType()) {
3433 // C++ [temp.explicit]p1:
3434 // A [...] static data member of a class template can be explicitly
3435 // instantiated from the member definition associated with its class
3436 // template.
3437 if (Previous.isAmbiguous()) {
3438 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
3439 D.getSourceRange());
3440 }
3441
3442 VarDecl *Prev = dyn_cast_or_null<VarDecl>(Previous.getAsDecl());
3443 if (!Prev || !Prev->isStaticDataMember()) {
3444 // We expect to see a data data member here.
3445 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
3446 << Name;
3447 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3448 P != PEnd; ++P)
3449 Diag(P->getLocation(), diag::note_explicit_instantiation_here);
3450 return true;
3451 }
3452
3453 if (!Prev->getInstantiatedFromStaticDataMember()) {
3454 // FIXME: Check for explicit specialization?
3455 Diag(D.getIdentifierLoc(),
3456 diag::err_explicit_instantiation_data_member_not_instantiated)
3457 << Prev;
3458 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
3459 // FIXME: Can we provide a note showing where this was declared?
3460 return true;
3461 }
3462
3463 // Instantiate static data member.
3464 // FIXME: Note that this is an explicit instantiation.
3465 if (TSK == TSK_ExplicitInstantiationDefinition)
3466 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false);
3467
3468 // FIXME: Create an ExplicitInstantiation node?
3469 return DeclPtrTy();
3470 }
3471
Douglas Gregor0e876e02009-09-25 23:53:26 +00003472 // If the declarator is a template-id, translate the parser's template
3473 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00003474 bool HasExplicitTemplateArgs = false;
3475 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3476 if (D.getKind() == Declarator::DK_TemplateId) {
3477 TemplateIdAnnotation *TemplateId = D.getTemplateId();
3478 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3479 TemplateId->getTemplateArgs(),
3480 TemplateId->getTemplateArgIsType(),
3481 TemplateId->NumArgs);
3482 translateTemplateArguments(TemplateArgsPtr,
3483 TemplateId->getTemplateArgLocations(),
3484 TemplateArgs);
3485 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00003486 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00003487 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00003488
Douglas Gregor450f00842009-09-25 18:43:00 +00003489 // C++ [temp.explicit]p1:
3490 // A [...] function [...] can be explicitly instantiated from its template.
3491 // A member function [...] of a class template can be explicitly
3492 // instantiated from the member definition associated with its class
3493 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00003494 llvm::SmallVector<FunctionDecl *, 8> Matches;
3495 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3496 P != PEnd; ++P) {
3497 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00003498 if (!HasExplicitTemplateArgs) {
3499 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
3500 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
3501 Matches.clear();
3502 Matches.push_back(Method);
3503 break;
3504 }
Douglas Gregor450f00842009-09-25 18:43:00 +00003505 }
3506 }
3507
3508 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
3509 if (!FunTmpl)
3510 continue;
3511
3512 TemplateDeductionInfo Info(Context);
3513 FunctionDecl *Specialization = 0;
3514 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00003515 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3516 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00003517 R, Specialization, Info)) {
3518 // FIXME: Keep track of almost-matches?
3519 (void)TDK;
3520 continue;
3521 }
3522
3523 Matches.push_back(Specialization);
3524 }
3525
3526 // Find the most specialized function template specialization.
3527 FunctionDecl *Specialization
3528 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
3529 D.getIdentifierLoc(),
3530 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
3531 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
3532 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
3533
3534 if (!Specialization)
3535 return true;
3536
3537 switch (Specialization->getTemplateSpecializationKind()) {
3538 case TSK_Undeclared:
3539 Diag(D.getIdentifierLoc(),
3540 diag::err_explicit_instantiation_member_function_not_instantiated)
3541 << Specialization
3542 << (Specialization->getTemplateSpecializationKind() ==
3543 TSK_ExplicitSpecialization);
3544 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
3545 return true;
3546
3547 case TSK_ExplicitSpecialization:
3548 // C++ [temp.explicit]p4:
3549 // For a given set of template parameters, if an explicit instantiation
3550 // of a template appears after a declaration of an explicit
3551 // specialization for that template, the explicit instantiation has no
3552 // effect.
3553 break;
3554
3555 case TSK_ExplicitInstantiationDefinition:
3556 // FIXME: Check that we aren't trying to perform an explicit instantiation
3557 // declaration now.
3558 // Fall through
3559
3560 case TSK_ImplicitInstantiation:
3561 case TSK_ExplicitInstantiationDeclaration:
3562 // Instantiate the function, if this is an explicit instantiation
3563 // definition.
3564 if (TSK == TSK_ExplicitInstantiationDefinition)
3565 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
3566 false);
3567
3568 // FIXME: setTemplateSpecializationKind doesn't (yet) work for
3569 // non-templated member functions.
3570 if (!Specialization->getPrimaryTemplate())
3571 break;
3572
3573 Specialization->setTemplateSpecializationKind(TSK);
3574 break;
3575 }
3576
3577 // FIXME: Create some kind of ExplicitInstantiationDecl here.
3578 return DeclPtrTy();
3579}
3580
Douglas Gregor333489b2009-03-27 23:10:48 +00003581Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00003582Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3583 const CXXScopeSpec &SS, IdentifierInfo *Name,
3584 SourceLocation TagLoc, SourceLocation NameLoc) {
3585 // This has to hold, because SS is expected to be defined.
3586 assert(Name && "Expected a name in a dependent tag");
3587
3588 NestedNameSpecifier *NNS
3589 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3590 if (!NNS)
3591 return true;
3592
3593 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
3594 if (T.isNull())
3595 return true;
3596
3597 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
3598 QualType ElabType = Context.getElaboratedType(T, TagKind);
3599
3600 return ElabType.getAsOpaquePtr();
3601}
3602
3603Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00003604Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3605 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00003606 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00003607 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3608 if (!NNS)
3609 return true;
3610
3611 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003612 if (T.isNull())
3613 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00003614 return T.getAsOpaquePtr();
3615}
3616
Douglas Gregordce2b622009-04-01 00:28:59 +00003617Sema::TypeResult
3618Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3619 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003620 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003621 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00003622 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00003623 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00003624 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00003625 assert(TemplateId && "Expected a template specialization type");
3626
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003627 if (computeDeclContext(SS, false)) {
3628 // If we can compute a declaration context, then the "typename"
3629 // keyword was superfluous. Just build a QualifiedNameType to keep
3630 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00003631
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003632 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
3633 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
3634 }
Mike Stump11289f42009-09-09 15:08:12 +00003635
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003636 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00003637}
3638
Douglas Gregor333489b2009-03-27 23:10:48 +00003639/// \brief Build the type that describes a C++ typename specifier,
3640/// e.g., "typename T::type".
3641QualType
3642Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
3643 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003644 CXXRecordDecl *CurrentInstantiation = 0;
3645 if (NNS->isDependent()) {
3646 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00003647
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003648 // If the nested-name-specifier does not refer to the current
3649 // instantiation, then build a typename type.
3650 if (!CurrentInstantiation)
3651 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00003652
Douglas Gregorc707da62009-09-02 13:12:51 +00003653 // The nested-name-specifier refers to the current instantiation, so the
3654 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00003655 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00003656 // extraneous "typename" keywords, and we retroactively apply this DR to
3657 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003658 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003659
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003660 DeclContext *Ctx = 0;
3661
3662 if (CurrentInstantiation)
3663 Ctx = CurrentInstantiation;
3664 else {
3665 CXXScopeSpec SS;
3666 SS.setScopeRep(NNS);
3667 SS.setRange(Range);
3668 if (RequireCompleteDeclContext(SS))
3669 return QualType();
3670
3671 Ctx = computeDeclContext(SS);
3672 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003673 assert(Ctx && "No declaration context?");
3674
3675 DeclarationName Name(&II);
Mike Stump11289f42009-09-09 15:08:12 +00003676 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
Douglas Gregor333489b2009-03-27 23:10:48 +00003677 false);
3678 unsigned DiagID = 0;
3679 Decl *Referenced = 0;
3680 switch (Result.getKind()) {
3681 case LookupResult::NotFound:
3682 if (Ctx->isTranslationUnit())
3683 DiagID = diag::err_typename_nested_not_found_global;
3684 else
3685 DiagID = diag::err_typename_nested_not_found;
3686 break;
3687
3688 case LookupResult::Found:
3689 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3690 // We found a type. Build a QualifiedNameType, since the
3691 // typename-specifier was just sugar. FIXME: Tell
3692 // QualifiedNameType that it has a "typename" prefix.
3693 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3694 }
3695
3696 DiagID = diag::err_typename_nested_not_type;
3697 Referenced = Result.getAsDecl();
3698 break;
3699
3700 case LookupResult::FoundOverloaded:
3701 DiagID = diag::err_typename_nested_not_type;
3702 Referenced = *Result.begin();
3703 break;
3704
3705 case LookupResult::AmbiguousBaseSubobjectTypes:
3706 case LookupResult::AmbiguousBaseSubobjects:
3707 case LookupResult::AmbiguousReference:
3708 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3709 return QualType();
3710 }
3711
3712 // If we get here, it's because name lookup did not find a
3713 // type. Emit an appropriate diagnostic and return an error.
3714 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3715 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3716 else
3717 Diag(Range.getEnd(), DiagID) << Range << Name;
3718 if (Referenced)
3719 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3720 << Name;
3721 return QualType();
3722}
Douglas Gregor15acfb92009-08-06 16:20:37 +00003723
3724namespace {
3725 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00003726 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3727 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00003728 SourceLocation Loc;
3729 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00003730
Douglas Gregor15acfb92009-08-06 16:20:37 +00003731 public:
Mike Stump11289f42009-09-09 15:08:12 +00003732 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00003733 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003734 DeclarationName Entity)
3735 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00003736 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00003737
3738 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00003739 /// transformed.
3740 ///
3741 /// For the purposes of type reconstruction, a type has already been
3742 /// transformed if it is NULL or if it is not dependent.
3743 bool AlreadyTransformed(QualType T) {
3744 return T.isNull() || !T->isDependentType();
3745 }
Mike Stump11289f42009-09-09 15:08:12 +00003746
3747 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00003748 /// rebuilt.
3749 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00003750
Douglas Gregor15acfb92009-08-06 16:20:37 +00003751 /// \brief Returns the name of the entity whose type is being rebuilt.
3752 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00003753
Douglas Gregor15acfb92009-08-06 16:20:37 +00003754 /// \brief Transforms an expression by returning the expression itself
3755 /// (an identity function).
3756 ///
3757 /// FIXME: This is completely unsafe; we will need to actually clone the
3758 /// expressions.
3759 Sema::OwningExprResult TransformExpr(Expr *E) {
3760 return getSema().Owned(E);
3761 }
Mike Stump11289f42009-09-09 15:08:12 +00003762
Douglas Gregor15acfb92009-08-06 16:20:37 +00003763 /// \brief Transforms a typename type by determining whether the type now
3764 /// refers to a member of the current instantiation, and then
3765 /// type-checking and building a QualifiedNameType (when possible).
3766 QualType TransformTypenameType(const TypenameType *T);
3767 };
3768}
3769
Mike Stump11289f42009-09-09 15:08:12 +00003770QualType
Douglas Gregor15acfb92009-08-06 16:20:37 +00003771CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3772 NestedNameSpecifier *NNS
3773 = TransformNestedNameSpecifier(T->getQualifier(),
3774 /*FIXME:*/SourceRange(getBaseLocation()));
3775 if (!NNS)
3776 return QualType();
3777
3778 // If the nested-name-specifier did not change, and we cannot compute the
3779 // context corresponding to the nested-name-specifier, then this
3780 // typename type will not change; exit early.
3781 CXXScopeSpec SS;
3782 SS.setRange(SourceRange(getBaseLocation()));
3783 SS.setScopeRep(NNS);
3784 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3785 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003786
3787 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00003788 // QualifiedNameType.
3789 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00003790 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00003791 = TransformType(QualType(TemplateId, 0));
3792 if (NewTemplateId.isNull())
3793 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003794
Douglas Gregor15acfb92009-08-06 16:20:37 +00003795 if (NNS == T->getQualifier() &&
3796 NewTemplateId == QualType(TemplateId, 0))
3797 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003798
Douglas Gregor15acfb92009-08-06 16:20:37 +00003799 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3800 }
Mike Stump11289f42009-09-09 15:08:12 +00003801
Douglas Gregor15acfb92009-08-06 16:20:37 +00003802 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3803}
3804
3805/// \brief Rebuilds a type within the context of the current instantiation.
3806///
Mike Stump11289f42009-09-09 15:08:12 +00003807/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00003808/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00003809/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00003810/// partial specialization thereof). This routine will rebuild that type now
3811/// that we have entered the declarator's scope, which may produce different
3812/// canonical types, e.g.,
3813///
3814/// \code
3815/// template<typename T>
3816/// struct X {
3817/// typedef T* pointer;
3818/// pointer data();
3819/// };
3820///
3821/// template<typename T>
3822/// typename X<T>::pointer X<T>::data() { ... }
3823/// \endcode
3824///
3825/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3826/// since we do not know that we can look into X<T> when we parsed the type.
3827/// This function will rebuild the type, performing the lookup of "pointer"
3828/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3829/// as the canonical type of T*, allowing the return types of the out-of-line
3830/// definition and the declaration to match.
3831QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3832 DeclarationName Name) {
3833 if (T.isNull() || !T->isDependentType())
3834 return T;
Mike Stump11289f42009-09-09 15:08:12 +00003835
Douglas Gregor15acfb92009-08-06 16:20:37 +00003836 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3837 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00003838}
Douglas Gregorbe999392009-09-15 16:23:51 +00003839
3840/// \brief Produces a formatted string that describes the binding of
3841/// template parameters to template arguments.
3842std::string
3843Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3844 const TemplateArgumentList &Args) {
3845 std::string Result;
3846
3847 if (!Params || Params->size() == 0)
3848 return Result;
3849
3850 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3851 if (I == 0)
3852 Result += "[with ";
3853 else
3854 Result += ", ";
3855
3856 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
3857 Result += Id->getName();
3858 } else {
3859 Result += '$';
3860 Result += llvm::utostr(I);
3861 }
3862
3863 Result += " = ";
3864
3865 switch (Args[I].getKind()) {
3866 case TemplateArgument::Null:
3867 Result += "<no value>";
3868 break;
3869
3870 case TemplateArgument::Type: {
3871 std::string TypeStr;
3872 Args[I].getAsType().getAsStringInternal(TypeStr,
3873 Context.PrintingPolicy);
3874 Result += TypeStr;
3875 break;
3876 }
3877
3878 case TemplateArgument::Declaration: {
3879 bool Unnamed = true;
3880 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
3881 if (ND->getDeclName()) {
3882 Unnamed = false;
3883 Result += ND->getNameAsString();
3884 }
3885 }
3886
3887 if (Unnamed) {
3888 Result += "<anonymous>";
3889 }
3890 break;
3891 }
3892
3893 case TemplateArgument::Integral: {
3894 Result += Args[I].getAsIntegral()->toString(10);
3895 break;
3896 }
3897
3898 case TemplateArgument::Expression: {
3899 assert(false && "No expressions in deduced template arguments!");
3900 Result += "<expression>";
3901 break;
3902 }
3903
3904 case TemplateArgument::Pack:
3905 // FIXME: Format template argument packs
3906 Result += "<template argument pack>";
3907 break;
3908 }
3909 }
3910
3911 Result += ']';
3912 return Result;
3913}