blob: d12ec9318af903fb53b5af168d2272d38e37c773 [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) {
260 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
261 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 Gregorf61eca92009-05-13 18:28:20 +00002348/// \brief Check whether a class template specialization or explicit
2349/// instantiation in the current context is well-formed.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002350///
Douglas Gregorf61eca92009-05-13 18:28:20 +00002351/// This routine determines whether a class template specialization or
Mike Stump11289f42009-09-09 15:08:12 +00002352/// explicit instantiation can be declared in the current context
2353/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2354/// appropriate diagnostics if there was an error. It returns true if
Douglas Gregorf61eca92009-05-13 18:28:20 +00002355// there was an error that we cannot recover from, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002356bool
Douglas Gregorf47b9112009-02-25 22:02:03 +00002357Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2358 ClassTemplateSpecializationDecl *PrevDecl,
2359 SourceLocation TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002360 SourceRange ScopeSpecifierRange,
Douglas Gregor30b01972009-06-12 22:21:45 +00002361 bool PartialSpecialization,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002362 bool ExplicitInstantiation) {
Douglas Gregorf47b9112009-02-25 22:02:03 +00002363 // C++ [temp.expl.spec]p2:
2364 // An explicit specialization shall be declared in the namespace
2365 // of which the template is a member, or, for member templates, in
2366 // the namespace of which the enclosing class or enclosing class
2367 // template is a member. An explicit specialization of a member
2368 // function, member class or static data member of a class
2369 // template shall be declared in the namespace of which the class
2370 // template is a member. Such a declaration may also be a
2371 // definition. If the declaration is not a definition, the
2372 // specialization may be defined later in the name- space in which
2373 // the explicit specialization was declared, or in a namespace
2374 // that encloses the one in which the explicit specialization was
2375 // declared.
2376 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor30b01972009-06-12 22:21:45 +00002377 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002378 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002379 << Kind << ClassTemplate;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002380 return true;
2381 }
2382
2383 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00002384 DeclContext *TemplateContext
Douglas Gregorf47b9112009-02-25 22:02:03 +00002385 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorf61eca92009-05-13 18:28:20 +00002386 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2387 !ExplicitInstantiation) {
Douglas Gregorf47b9112009-02-25 22:02:03 +00002388 // There is no prior declaration of this entity, so this
2389 // specialization must be in the same context as the template
2390 // itself.
2391 if (DC != TemplateContext) {
2392 if (isa<TranslationUnitDecl>(TemplateContext))
2393 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor30b01972009-06-12 22:21:45 +00002394 << PartialSpecialization
Douglas Gregorf47b9112009-02-25 22:02:03 +00002395 << ClassTemplate << ScopeSpecifierRange;
2396 else if (isa<NamespaceDecl>(TemplateContext))
2397 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Mike Stump11289f42009-09-09 15:08:12 +00002398 << PartialSpecialization << ClassTemplate
Douglas Gregor30b01972009-06-12 22:21:45 +00002399 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002400
2401 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2402 }
2403
2404 return false;
2405 }
2406
2407 // We have a previous declaration of this entity. Make sure that
2408 // this redeclaration (or definition) occurs in an enclosing namespace.
2409 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002410 // FIXME: In C++98, we would like to turn these errors into warnings,
2411 // dependent on a -Wc++0x flag.
Douglas Gregorf61eca92009-05-13 18:28:20 +00002412 bool SuppressedDiag = false;
Douglas Gregor30b01972009-06-12 22:21:45 +00002413 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorf61eca92009-05-13 18:28:20 +00002414 if (isa<TranslationUnitDecl>(TemplateContext)) {
2415 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2416 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002417 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorf61eca92009-05-13 18:28:20 +00002418 else
2419 SuppressedDiag = true;
2420 } else if (isa<NamespaceDecl>(TemplateContext)) {
2421 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2422 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002423 << Kind << ClassTemplate
Douglas Gregorf61eca92009-05-13 18:28:20 +00002424 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Mike Stump11289f42009-09-09 15:08:12 +00002425 else
Douglas Gregorf61eca92009-05-13 18:28:20 +00002426 SuppressedDiag = true;
2427 }
Mike Stump11289f42009-09-09 15:08:12 +00002428
Douglas Gregorf61eca92009-05-13 18:28:20 +00002429 if (!SuppressedDiag)
2430 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002431 }
2432
2433 return false;
2434}
2435
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002436/// \brief Check the non-type template arguments of a class template
2437/// partial specialization according to C++ [temp.class.spec]p9.
2438///
Douglas Gregor09a30232009-06-12 22:08:06 +00002439/// \param TemplateParams the template parameters of the primary class
2440/// template.
2441///
2442/// \param TemplateArg the template arguments of the class template
2443/// partial specialization.
2444///
2445/// \param MirrorsPrimaryTemplate will be set true if the class
2446/// template partial specialization arguments are identical to the
2447/// implicit template arguments of the primary template. This is not
2448/// necessarily an error (C++0x), and it is left to the caller to diagnose
2449/// this condition when it is an error.
2450///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002451/// \returns true if there was an error, false otherwise.
2452bool Sema::CheckClassTemplatePartialSpecializationArgs(
2453 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002454 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002455 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002456 // FIXME: the interface to this function will have to change to
2457 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002458 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002459
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002460 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002461
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002462 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002463 // Determine whether the template argument list of the partial
2464 // specialization is identical to the implicit argument list of
2465 // the primary template. The caller may need to diagnostic this as
2466 // an error per C++ [temp.class.spec]p9b3.
2467 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002468 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002469 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2470 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002471 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002472 MirrorsPrimaryTemplate = false;
2473 } else if (TemplateTemplateParmDecl *TTP
2474 = dyn_cast<TemplateTemplateParmDecl>(
2475 TemplateParams->getParam(I))) {
2476 // FIXME: We should settle on either Declaration storage or
2477 // Expression storage for template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002478 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor09a30232009-06-12 22:08:06 +00002479 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson40c1d492009-06-13 18:20:51 +00002480 ArgList[I].getAsDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002481 if (!ArgDecl)
Mike Stump11289f42009-09-09 15:08:12 +00002482 if (DeclRefExpr *DRE
Anders Carlsson40c1d492009-06-13 18:20:51 +00002483 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002484 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2485
2486 if (!ArgDecl ||
2487 ArgDecl->getIndex() != TTP->getIndex() ||
2488 ArgDecl->getDepth() != TTP->getDepth())
2489 MirrorsPrimaryTemplate = false;
2490 }
2491 }
2492
Mike Stump11289f42009-09-09 15:08:12 +00002493 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002494 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002495 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002496 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002497 }
2498
Anders Carlsson40c1d492009-06-13 18:20:51 +00002499 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002500 if (!ArgExpr) {
2501 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002502 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002503 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002504
2505 // C++ [temp.class.spec]p8:
2506 // A non-type argument is non-specialized if it is the name of a
2507 // non-type parameter. All other non-type arguments are
2508 // specialized.
2509 //
2510 // Below, we check the two conditions that only apply to
2511 // specialized non-type arguments, so skip any non-specialized
2512 // arguments.
2513 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002514 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002515 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002516 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002517 (Param->getIndex() != NTTP->getIndex() ||
2518 Param->getDepth() != NTTP->getDepth()))
2519 MirrorsPrimaryTemplate = false;
2520
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002521 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002522 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002523
2524 // C++ [temp.class.spec]p9:
2525 // Within the argument list of a class template partial
2526 // specialization, the following restrictions apply:
2527 // -- A partially specialized non-type argument expression
2528 // shall not involve a template parameter of the partial
2529 // specialization except when the argument expression is a
2530 // simple identifier.
2531 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002532 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002533 diag::err_dependent_non_type_arg_in_partial_spec)
2534 << ArgExpr->getSourceRange();
2535 return true;
2536 }
2537
2538 // -- The type of a template parameter corresponding to a
2539 // specialized non-type argument shall not be dependent on a
2540 // parameter of the specialization.
2541 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002542 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002543 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2544 << Param->getType()
2545 << ArgExpr->getSourceRange();
2546 Diag(Param->getLocation(), diag::note_template_param_here);
2547 return true;
2548 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002549
2550 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002551 }
2552
2553 return false;
2554}
2555
Douglas Gregorc08f4892009-03-25 00:13:59 +00002556Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002557Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2558 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002559 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002560 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002561 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002562 SourceLocation TemplateNameLoc,
2563 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002564 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002565 SourceLocation *TemplateArgLocs,
2566 SourceLocation RAngleLoc,
2567 AttributeList *Attr,
2568 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00002569 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00002570
Douglas Gregor67a65642009-02-17 23:15:12 +00002571 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002572 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002573 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002574 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002575
Douglas Gregor2373c592009-05-31 09:31:02 +00002576 bool isPartialSpecialization = false;
2577
Douglas Gregorf47b9112009-02-25 22:02:03 +00002578 // Check the validity of the template headers that introduce this
2579 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00002580 // FIXME: We probably shouldn't complain about these headers for
2581 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002582 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002583 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2584 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002585 TemplateParameterLists.size());
2586 if (TemplateParams && TemplateParams->size() > 0) {
2587 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002588
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002589 // C++ [temp.class.spec]p10:
2590 // The template parameter list of a specialization shall not
2591 // contain default template argument values.
2592 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2593 Decl *Param = TemplateParams->getParam(I);
2594 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2595 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002596 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002597 diag::err_default_arg_in_partial_spec);
2598 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2599 }
2600 } else if (NonTypeTemplateParmDecl *NTTP
2601 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2602 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002603 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002604 diag::err_default_arg_in_partial_spec)
2605 << DefArg->getSourceRange();
2606 NTTP->setDefaultArgument(0);
2607 DefArg->Destroy(Context);
2608 }
2609 } else {
2610 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2611 if (Expr *DefArg = TTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002612 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002613 diag::err_default_arg_in_partial_spec)
2614 << DefArg->getSourceRange();
2615 TTP->setDefaultArgument(0);
2616 DefArg->Destroy(Context);
Douglas Gregord5222052009-06-12 19:43:02 +00002617 }
2618 }
2619 }
Douglas Gregor2208a292009-09-26 20:57:03 +00002620 } else if (!TemplateParams && TUK != TUK_Friend)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002621 Diag(KWLoc, diag::err_template_spec_needs_header)
2622 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregorf47b9112009-02-25 22:02:03 +00002623
Douglas Gregor67a65642009-02-17 23:15:12 +00002624 // Check that the specialization uses the same tag kind as the
2625 // original template.
2626 TagDecl::TagKind Kind;
2627 switch (TagSpec) {
2628 default: assert(0 && "Unknown tag type!");
2629 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2630 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2631 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2632 }
Douglas Gregord9034f02009-05-14 16:41:31 +00002633 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00002634 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00002635 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00002636 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00002637 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00002638 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00002639 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00002640 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00002641 diag::note_previous_use);
2642 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2643 }
2644
Douglas Gregorc40290e2009-03-09 23:48:35 +00002645 // Translate the parser's template argument list in our AST format.
2646 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2647 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2648
Douglas Gregor67a65642009-02-17 23:15:12 +00002649 // Check that the template argument list is well-formed for this
2650 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002651 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2652 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00002653 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002654 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00002655 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002656 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002657
Mike Stump11289f42009-09-09 15:08:12 +00002658 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00002659 ClassTemplate->getTemplateParameters()->size()) &&
2660 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00002661
Douglas Gregor2373c592009-05-31 09:31:02 +00002662 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00002663 // corresponds to these arguments.
2664 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00002665 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002666 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002667 if (CheckClassTemplatePartialSpecializationArgs(
2668 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002669 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002670 return true;
2671
Douglas Gregor09a30232009-06-12 22:08:06 +00002672 if (MirrorsPrimaryTemplate) {
2673 // C++ [temp.class.spec]p9b3:
2674 //
Mike Stump11289f42009-09-09 15:08:12 +00002675 // -- The argument list of the specialization shall not be identical
2676 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00002677 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00002678 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00002679 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00002680 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00002681 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00002682 ClassTemplate->getIdentifier(),
2683 TemplateNameLoc,
2684 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002685 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00002686 AS_none);
2687 }
2688
Douglas Gregor2208a292009-09-26 20:57:03 +00002689 // FIXME: Diagnose friend partial specializations
2690
Douglas Gregor2373c592009-05-31 09:31:02 +00002691 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00002692 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002693 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002694 Converted.flatSize(),
2695 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002696 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002697 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002698 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002699 Converted.flatSize(),
2700 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00002701 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002702 ClassTemplateSpecializationDecl *PrevDecl = 0;
2703
2704 if (isPartialSpecialization)
2705 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00002706 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00002707 InsertPos);
2708 else
2709 PrevDecl
2710 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00002711
2712 ClassTemplateSpecializationDecl *Specialization = 0;
2713
Douglas Gregorf47b9112009-02-25 22:02:03 +00002714 // Check whether we can declare a class template specialization in
2715 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00002716 if (TUK != TUK_Friend &&
2717 CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002718 TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002719 SS.getRange(),
Douglas Gregor30b01972009-06-12 22:21:45 +00002720 isPartialSpecialization,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002721 /*ExplicitInstantiation=*/false))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002722 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002723
Douglas Gregor15301382009-07-30 17:40:51 +00002724 // The canonical type
2725 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00002726 if (PrevDecl &&
2727 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
2728 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002729 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00002730 // arguments was referenced but not declared, or we're only
2731 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00002732 // declaration node as our own, updating its source location to
2733 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002734 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00002735 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00002736 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00002737 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00002738 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00002739 // Build the canonical type that describes the converted template
2740 // arguments of the class template partial specialization.
2741 CanonType = Context.getTemplateSpecializationType(
2742 TemplateName(ClassTemplate),
2743 Converted.getFlatArguments(),
2744 Converted.flatSize());
2745
Douglas Gregor2373c592009-05-31 09:31:02 +00002746 // Create a new class template partial specialization declaration node.
Mike Stump11289f42009-09-09 15:08:12 +00002747 TemplateParameterList *TemplateParams
Douglas Gregor2373c592009-05-31 09:31:02 +00002748 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2749 ClassTemplatePartialSpecializationDecl *PrevPartial
2750 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002751 ClassTemplatePartialSpecializationDecl *Partial
2752 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00002753 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002754 TemplateNameLoc,
2755 TemplateParams,
2756 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002757 Converted,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002758 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00002759
2760 if (PrevPartial) {
2761 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2762 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2763 } else {
2764 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2765 }
2766 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00002767
2768 // Check that all of the template parameters of the class template
2769 // partial specialization are deducible from the template
2770 // arguments. If not, this class template partial specialization
2771 // will never be used.
2772 llvm::SmallVector<bool, 8> DeducibleParams;
2773 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002774 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2775 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00002776 unsigned NumNonDeducible = 0;
2777 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2778 if (!DeducibleParams[I])
2779 ++NumNonDeducible;
2780
2781 if (NumNonDeducible) {
2782 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2783 << (NumNonDeducible > 1)
2784 << SourceRange(TemplateNameLoc, RAngleLoc);
2785 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2786 if (!DeducibleParams[I]) {
2787 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2788 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00002789 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002790 diag::note_partial_spec_unused_parameter)
2791 << Param->getDeclName();
2792 else
Mike Stump11289f42009-09-09 15:08:12 +00002793 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002794 diag::note_partial_spec_unused_parameter)
2795 << std::string("<anonymous>");
2796 }
2797 }
2798 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002799 } else {
2800 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00002801 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002802 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00002803 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00002804 ClassTemplate->getDeclContext(),
2805 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002806 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002807 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00002808 PrevDecl);
2809
2810 if (PrevDecl) {
2811 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2812 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2813 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002814 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00002815 InsertPos);
2816 }
Douglas Gregor15301382009-07-30 17:40:51 +00002817
2818 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002819 }
2820
Douglas Gregor2208a292009-09-26 20:57:03 +00002821 // If this is not a friend, note that this is an explicit specialization.
2822 if (TUK != TUK_Friend)
2823 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002824
2825 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002826 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002827 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002828 // FIXME: Should also handle explicit specialization after implicit
2829 // instantiation with a special diagnostic.
Douglas Gregor67a65642009-02-17 23:15:12 +00002830 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002831 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00002832 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00002833 Diag(Def->getLocation(), diag::note_previous_definition);
2834 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00002835 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002836 }
2837 }
2838
Douglas Gregord56a91e2009-02-26 22:19:44 +00002839 // Build the fully-sugared type for this class template
2840 // specialization as the user wrote in the specialization
2841 // itself. This means that we'll pretty-print the type retrieved
2842 // from the specialization's declaration the way that the user
2843 // actually wrote the specialization, rather than formatting the
2844 // name based on the "canonical" representation used to store the
2845 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002846 QualType WrittenTy
2847 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002848 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00002849 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00002850 CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00002851 if (TUK != TUK_Friend)
2852 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002853 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00002854
Douglas Gregor1e249f82009-02-25 22:18:32 +00002855 // C++ [temp.expl.spec]p9:
2856 // A template explicit specialization is in the scope of the
2857 // namespace in which the template was defined.
2858 //
2859 // We actually implement this paragraph where we set the semantic
2860 // context (in the creation of the ClassTemplateSpecializationDecl),
2861 // but we also maintain the lexical context where the actual
2862 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00002863 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00002864
Douglas Gregor67a65642009-02-17 23:15:12 +00002865 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002866 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00002867 Specialization->startDefinition();
2868
Douglas Gregor2208a292009-09-26 20:57:03 +00002869 if (TUK == TUK_Friend) {
2870 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
2871 TemplateNameLoc,
2872 WrittenTy.getTypePtr(),
2873 /*FIXME:*/KWLoc);
2874 Friend->setAccess(AS_public);
2875 CurContext->addDecl(Friend);
2876 } else {
2877 // Add the specialization into its lexical context, so that it can
2878 // be seen when iterating through the list of declarations in that
2879 // context. However, specializations are not found by name lookup.
2880 CurContext->addDecl(Specialization);
2881 }
Chris Lattner83f095c2009-03-28 19:18:32 +00002882 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002883}
Douglas Gregor333489b2009-03-27 23:10:48 +00002884
Mike Stump11289f42009-09-09 15:08:12 +00002885Sema::DeclPtrTy
2886Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002887 MultiTemplateParamsArg TemplateParameterLists,
2888 Declarator &D) {
2889 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2890}
2891
Mike Stump11289f42009-09-09 15:08:12 +00002892Sema::DeclPtrTy
2893Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002894 MultiTemplateParamsArg TemplateParameterLists,
2895 Declarator &D) {
2896 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2897 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2898 "Not a function declarator!");
2899 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00002900
Douglas Gregor17a7c122009-06-24 00:54:41 +00002901 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00002902 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00002903 }
Mike Stump11289f42009-09-09 15:08:12 +00002904
Douglas Gregor17a7c122009-06-24 00:54:41 +00002905 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002906
2907 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002908 move(TemplateParameterLists),
2909 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002910 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00002911 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00002912 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002913 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00002914 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2915 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002916 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00002917}
2918
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002919/// \brief Perform semantic analysis for the given function template
2920/// specialization.
2921///
2922/// This routine performs all of the semantic analysis required for an
2923/// explicit function template specialization. On successful completion,
2924/// the function declaration \p FD will become a function template
2925/// specialization.
2926///
2927/// \param FD the function declaration, which will be updated to become a
2928/// function template specialization.
2929///
2930/// \param HasExplicitTemplateArgs whether any template arguments were
2931/// explicitly provided.
2932///
2933/// \param LAngleLoc the location of the left angle bracket ('<'), if
2934/// template arguments were explicitly provided.
2935///
2936/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
2937/// if any.
2938///
2939/// \param NumExplicitTemplateArgs the number of explicitly-provided template
2940/// arguments. This number may be zero even when HasExplicitTemplateArgs is
2941/// true as in, e.g., \c void sort<>(char*, char*);
2942///
2943/// \param RAngleLoc the location of the right angle bracket ('>'), if
2944/// template arguments were explicitly provided.
2945///
2946/// \param PrevDecl the set of declarations that
2947bool
2948Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
2949 bool HasExplicitTemplateArgs,
2950 SourceLocation LAngleLoc,
2951 const TemplateArgument *ExplicitTemplateArgs,
2952 unsigned NumExplicitTemplateArgs,
2953 SourceLocation RAngleLoc,
2954 NamedDecl *&PrevDecl) {
2955 // The set of function template specializations that could match this
2956 // explicit function template specialization.
2957 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
2958 CandidateSet Candidates;
2959
2960 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
2961 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2962 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
2963 // Only consider templates found within the same semantic lookup scope as
2964 // FD.
2965 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
2966 continue;
2967
2968 // C++ [temp.expl.spec]p11:
2969 // A trailing template-argument can be left unspecified in the
2970 // template-id naming an explicit function template specialization
2971 // provided it can be deduced from the function argument type.
2972 // Perform template argument deduction to determine whether we may be
2973 // specializing this template.
2974 // FIXME: It is somewhat wasteful to build
2975 TemplateDeductionInfo Info(Context);
2976 FunctionDecl *Specialization = 0;
2977 if (TemplateDeductionResult TDK
2978 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
2979 ExplicitTemplateArgs,
2980 NumExplicitTemplateArgs,
2981 FD->getType(),
2982 Specialization,
2983 Info)) {
2984 // FIXME: Template argument deduction failed; record why it failed, so
2985 // that we can provide nifty diagnostics.
2986 (void)TDK;
2987 continue;
2988 }
2989
2990 // Record this candidate.
2991 Candidates.push_back(Specialization);
2992 }
2993 }
2994
Douglas Gregor5de279c2009-09-26 03:41:46 +00002995 // Find the most specialized function template.
2996 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
2997 Candidates.size(),
2998 TPOC_Other,
2999 FD->getLocation(),
3000 PartialDiagnostic(diag::err_function_template_spec_no_match)
3001 << FD->getDeclName(),
3002 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3003 << FD->getDeclName() << HasExplicitTemplateArgs,
3004 PartialDiagnostic(diag::note_function_template_spec_matched));
3005 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003006 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003007
3008 // FIXME: Check if the prior specialization has a point of instantiation.
3009 // If so, we have run afoul of C++ [temp.expl.spec]p6.
3010
3011 // Mark the prior declaration as an explicit specialization, so that later
3012 // clients know that this is an explicit specialization.
3013 // FIXME: Check for prior explicit instantiations?
3014 Specialization->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
3015
3016 // Turn the given function declaration into a function template
3017 // specialization, with the template arguments from the previous
3018 // specialization.
3019 FD->setFunctionTemplateSpecialization(Context,
3020 Specialization->getPrimaryTemplate(),
3021 new (Context) TemplateArgumentList(
3022 *Specialization->getTemplateSpecializationArgs()),
3023 /*InsertPos=*/0,
3024 TSK_ExplicitSpecialization);
3025
3026 // The "previous declaration" for this function template specialization is
3027 // the prior function template specialization.
3028 PrevDecl = Specialization;
3029 return false;
3030}
3031
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003032// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003033// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003034Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003035Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003036 SourceLocation ExternLoc,
3037 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003038 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003039 SourceLocation KWLoc,
3040 const CXXScopeSpec &SS,
3041 TemplateTy TemplateD,
3042 SourceLocation TemplateNameLoc,
3043 SourceLocation LAngleLoc,
3044 ASTTemplateArgsPtr TemplateArgsIn,
3045 SourceLocation *TemplateArgLocs,
3046 SourceLocation RAngleLoc,
3047 AttributeList *Attr) {
3048 // Find the class template we're specializing
3049 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003050 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003051 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3052
3053 // Check that the specialization uses the same tag kind as the
3054 // original template.
3055 TagDecl::TagKind Kind;
3056 switch (TagSpec) {
3057 default: assert(0 && "Unknown tag type!");
3058 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3059 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3060 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3061 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003062 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003063 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003064 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003065 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003066 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003067 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003068 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003069 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003070 diag::note_previous_use);
3071 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3072 }
3073
Douglas Gregorf61eca92009-05-13 18:28:20 +00003074 // C++0x [temp.explicit]p2:
3075 // [...] An explicit instantiation shall appear in an enclosing
3076 // namespace of its template. [...]
3077 //
3078 // This is C++ DR 275.
3079 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
Mike Stump11289f42009-09-09 15:08:12 +00003080 TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003081 SS.getRange(),
Douglas Gregor30b01972009-06-12 22:21:45 +00003082 /*PartialSpecialization=*/false,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003083 /*ExplicitInstantiation=*/true))
3084 return true;
3085
Douglas Gregora1f49972009-05-13 00:25:59 +00003086 // Translate the parser's template argument list in our AST format.
3087 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3088 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3089
3090 // Check that the template argument list is well-formed for this
3091 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003092 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3093 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003094 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003095 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003096 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003097 return true;
3098
Mike Stump11289f42009-09-09 15:08:12 +00003099 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003100 ClassTemplate->getTemplateParameters()->size()) &&
3101 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003102
Douglas Gregora1f49972009-05-13 00:25:59 +00003103 // Find the class template specialization declaration that
3104 // corresponds to these arguments.
3105 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003106 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003107 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003108 Converted.flatSize(),
3109 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003110 void *InsertPos = 0;
3111 ClassTemplateSpecializationDecl *PrevDecl
3112 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3113
3114 ClassTemplateSpecializationDecl *Specialization = 0;
3115
Douglas Gregorf61eca92009-05-13 18:28:20 +00003116 bool SpecializationRequiresInstantiation = true;
Douglas Gregora1f49972009-05-13 00:25:59 +00003117 if (PrevDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003118 if (PrevDecl->getSpecializationKind()
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003119 == TSK_ExplicitInstantiationDefinition) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003120 // This particular specialization has already been declared or
3121 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorf61eca92009-05-13 18:28:20 +00003122 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
3123 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003124 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003125 diag::note_previous_explicit_instantiation);
Douglas Gregora1f49972009-05-13 00:25:59 +00003126 return DeclPtrTy::make(PrevDecl);
3127 }
3128
Douglas Gregorf61eca92009-05-13 18:28:20 +00003129 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003130 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorf61eca92009-05-13 18:28:20 +00003131 // For a given set of template parameters, if an explicit
3132 // instantiation of a template appears after a declaration of
3133 // an explicit specialization for that template, the explicit
3134 // instantiation has no effect.
3135 if (!getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00003136 Diag(TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003137 diag::ext_explicit_instantiation_after_specialization)
3138 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003139 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003140 diag::note_previous_template_specialization);
3141 }
3142
3143 // Create a new class template specialization declaration node
3144 // for this explicit specialization. This node is only used to
3145 // record the existence of this explicit instantiation for
3146 // accurate reproduction of the source code; we don't actually
3147 // use it for anything, since it is semantically irrelevant.
3148 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003149 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003150 ClassTemplate->getDeclContext(),
3151 TemplateNameLoc,
3152 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003153 Converted, 0);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003154 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003155 CurContext->addDecl(Specialization);
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003156 return DeclPtrTy::make(PrevDecl);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003157 }
3158
3159 // If we have already (implicitly) instantiated this
3160 // specialization, there is less work to do.
3161 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
3162 SpecializationRequiresInstantiation = false;
3163
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003164 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3165 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3166 // Since the only prior class template specialization with these
3167 // arguments was referenced but not declared, reuse that
3168 // declaration node as our own, updating its source location to
3169 // reflect our new declaration.
3170 Specialization = PrevDecl;
3171 Specialization->setLocation(TemplateNameLoc);
3172 PrevDecl = 0;
3173 }
3174 }
3175
3176 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003177 // Create a new class template specialization declaration node for
3178 // this explicit specialization.
3179 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003180 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003181 ClassTemplate->getDeclContext(),
3182 TemplateNameLoc,
3183 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003184 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003185
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003186 if (PrevDecl) {
3187 // Remove the previous declaration from the folding set, since we want
3188 // to introduce a new declaration.
3189 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3190 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3191 }
3192
3193 // Insert the new specialization.
3194 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003195 }
3196
3197 // Build the fully-sugared type for this explicit instantiation as
3198 // the user wrote in the explicit instantiation itself. This means
3199 // that we'll pretty-print the type retrieved from the
3200 // specialization's declaration the way that the user actually wrote
3201 // the explicit instantiation, rather than formatting the name based
3202 // on the "canonical" representation used to store the template
3203 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003204 QualType WrittenTy
3205 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003206 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003207 TemplateArgs.size(),
3208 Context.getTypeDeclType(Specialization));
3209 Specialization->setTypeAsWritten(WrittenTy);
3210 TemplateArgsIn.release();
3211
3212 // Add the explicit instantiation into its lexical context. However,
3213 // since explicit instantiations are never found by name lookup, we
3214 // just put it into the declaration context directly.
3215 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003216 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003217
John McCall1806c272009-09-11 07:25:08 +00003218 Specialization->setPointOfInstantiation(TemplateNameLoc);
3219
Douglas Gregora1f49972009-05-13 00:25:59 +00003220 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003221 // A definition of a class template or class member template
3222 // shall be in scope at the point of the explicit instantiation of
3223 // the class template or class member template.
3224 //
3225 // This check comes when we actually try to perform the
3226 // instantiation.
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003227 TemplateSpecializationKind TSK
Mike Stump11289f42009-09-09 15:08:12 +00003228 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003229 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor67da0d92009-05-15 17:59:04 +00003230 if (SpecializationRequiresInstantiation)
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003231 InstantiateClassTemplateSpecialization(Specialization, TSK);
Douglas Gregor85673582009-05-18 17:01:57 +00003232 else // Instantiate the members of this class template specialization.
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003233 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization,
3234 TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003235
3236 return DeclPtrTy::make(Specialization);
3237}
3238
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003239// Explicit instantiation of a member class of a class template.
3240Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003241Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003242 SourceLocation ExternLoc,
3243 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003244 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003245 SourceLocation KWLoc,
3246 const CXXScopeSpec &SS,
3247 IdentifierInfo *Name,
3248 SourceLocation NameLoc,
3249 AttributeList *Attr) {
3250
Douglas Gregord6ab8742009-05-28 23:31:59 +00003251 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003252 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00003253 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00003254 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00003255 MultiTemplateParamsArg(*this, 0, 0),
3256 Owned, IsDependent);
3257 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3258
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003259 if (!TagD)
3260 return true;
3261
3262 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3263 if (Tag->isEnum()) {
3264 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3265 << Context.getTypeDeclType(Tag);
3266 return true;
3267 }
3268
Douglas Gregorb8006faf2009-05-27 17:30:49 +00003269 if (Tag->isInvalidDecl())
3270 return true;
3271
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003272 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3273 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3274 if (!Pattern) {
3275 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3276 << Context.getTypeDeclType(Record);
3277 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3278 return true;
3279 }
3280
3281 // C++0x [temp.explicit]p2:
3282 // [...] An explicit instantiation shall appear in an enclosing
3283 // namespace of its template. [...]
3284 //
3285 // This is C++ DR 275.
3286 if (getLangOptions().CPlusPlus0x) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003287 // FIXME: In C++98, we would like to turn these errors into warnings,
3288 // dependent on a -Wc++0x flag.
Mike Stump11289f42009-09-09 15:08:12 +00003289 DeclContext *PatternContext
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003290 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
3291 if (!CurContext->Encloses(PatternContext)) {
3292 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
3293 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
3294 Diag(Pattern->getLocation(), diag::note_previous_declaration);
3295 }
3296 }
3297
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003298 TemplateSpecializationKind TSK
Mike Stump11289f42009-09-09 15:08:12 +00003299 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003300 : TSK_ExplicitInstantiationDeclaration;
Mike Stump11289f42009-09-09 15:08:12 +00003301
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003302 if (!Record->getDefinition(Context)) {
3303 // If the class has a definition, instantiate it (and all of its
3304 // members, recursively).
3305 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
Mike Stump11289f42009-09-09 15:08:12 +00003306 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregorb4850462009-05-14 23:26:13 +00003307 getTemplateInstantiationArgs(Record),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003308 TSK))
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003309 return true;
John McCall76d824f2009-08-25 22:02:44 +00003310 } else // Instantiate all of the members of the class.
Mike Stump11289f42009-09-09 15:08:12 +00003311 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003312 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003313
Mike Stump87c57ac2009-05-16 07:39:55 +00003314 // FIXME: We don't have any representation for explicit instantiations of
3315 // member classes. Such a representation is not needed for compilation, but it
3316 // should be available for clients that want to see all of the declarations in
3317 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003318 return TagD;
3319}
3320
Douglas Gregor450f00842009-09-25 18:43:00 +00003321Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
3322 SourceLocation ExternLoc,
3323 SourceLocation TemplateLoc,
3324 Declarator &D) {
3325 // Explicit instantiations always require a name.
3326 DeclarationName Name = GetNameForDeclarator(D);
3327 if (!Name) {
3328 if (!D.isInvalidType())
3329 Diag(D.getDeclSpec().getSourceRange().getBegin(),
3330 diag::err_explicit_instantiation_requires_name)
3331 << D.getDeclSpec().getSourceRange()
3332 << D.getSourceRange();
3333
3334 return true;
3335 }
3336
3337 // The scope passed in may not be a decl scope. Zip up the scope tree until
3338 // we find one that is.
3339 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3340 (S->getFlags() & Scope::TemplateParamScope) != 0)
3341 S = S->getParent();
3342
3343 // Determine the type of the declaration.
3344 QualType R = GetTypeForDeclarator(D, S, 0);
3345 if (R.isNull())
3346 return true;
3347
3348 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3349 // Cannot explicitly instantiate a typedef.
3350 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
3351 << Name;
3352 return true;
3353 }
3354
3355 // Determine what kind of explicit instantiation we have.
3356 TemplateSpecializationKind TSK
3357 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3358 : TSK_ExplicitInstantiationDeclaration;
3359
3360 LookupResult Previous = LookupParsedName(S, &D.getCXXScopeSpec(),
3361 Name, LookupOrdinaryName);
3362
3363 if (!R->isFunctionType()) {
3364 // C++ [temp.explicit]p1:
3365 // A [...] static data member of a class template can be explicitly
3366 // instantiated from the member definition associated with its class
3367 // template.
3368 if (Previous.isAmbiguous()) {
3369 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
3370 D.getSourceRange());
3371 }
3372
3373 VarDecl *Prev = dyn_cast_or_null<VarDecl>(Previous.getAsDecl());
3374 if (!Prev || !Prev->isStaticDataMember()) {
3375 // We expect to see a data data member here.
3376 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
3377 << Name;
3378 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3379 P != PEnd; ++P)
3380 Diag(P->getLocation(), diag::note_explicit_instantiation_here);
3381 return true;
3382 }
3383
3384 if (!Prev->getInstantiatedFromStaticDataMember()) {
3385 // FIXME: Check for explicit specialization?
3386 Diag(D.getIdentifierLoc(),
3387 diag::err_explicit_instantiation_data_member_not_instantiated)
3388 << Prev;
3389 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
3390 // FIXME: Can we provide a note showing where this was declared?
3391 return true;
3392 }
3393
3394 // Instantiate static data member.
3395 // FIXME: Note that this is an explicit instantiation.
3396 if (TSK == TSK_ExplicitInstantiationDefinition)
3397 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false);
3398
3399 // FIXME: Create an ExplicitInstantiation node?
3400 return DeclPtrTy();
3401 }
3402
Douglas Gregor0e876e02009-09-25 23:53:26 +00003403 // If the declarator is a template-id, translate the parser's template
3404 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00003405 bool HasExplicitTemplateArgs = false;
3406 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3407 if (D.getKind() == Declarator::DK_TemplateId) {
3408 TemplateIdAnnotation *TemplateId = D.getTemplateId();
3409 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3410 TemplateId->getTemplateArgs(),
3411 TemplateId->getTemplateArgIsType(),
3412 TemplateId->NumArgs);
3413 translateTemplateArguments(TemplateArgsPtr,
3414 TemplateId->getTemplateArgLocations(),
3415 TemplateArgs);
3416 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00003417 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00003418 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00003419
Douglas Gregor450f00842009-09-25 18:43:00 +00003420 // C++ [temp.explicit]p1:
3421 // A [...] function [...] can be explicitly instantiated from its template.
3422 // A member function [...] of a class template can be explicitly
3423 // instantiated from the member definition associated with its class
3424 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00003425 llvm::SmallVector<FunctionDecl *, 8> Matches;
3426 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3427 P != PEnd; ++P) {
3428 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00003429 if (!HasExplicitTemplateArgs) {
3430 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
3431 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
3432 Matches.clear();
3433 Matches.push_back(Method);
3434 break;
3435 }
Douglas Gregor450f00842009-09-25 18:43:00 +00003436 }
3437 }
3438
3439 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
3440 if (!FunTmpl)
3441 continue;
3442
3443 TemplateDeductionInfo Info(Context);
3444 FunctionDecl *Specialization = 0;
3445 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00003446 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3447 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00003448 R, Specialization, Info)) {
3449 // FIXME: Keep track of almost-matches?
3450 (void)TDK;
3451 continue;
3452 }
3453
3454 Matches.push_back(Specialization);
3455 }
3456
3457 // Find the most specialized function template specialization.
3458 FunctionDecl *Specialization
3459 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
3460 D.getIdentifierLoc(),
3461 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
3462 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
3463 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
3464
3465 if (!Specialization)
3466 return true;
3467
3468 switch (Specialization->getTemplateSpecializationKind()) {
3469 case TSK_Undeclared:
3470 Diag(D.getIdentifierLoc(),
3471 diag::err_explicit_instantiation_member_function_not_instantiated)
3472 << Specialization
3473 << (Specialization->getTemplateSpecializationKind() ==
3474 TSK_ExplicitSpecialization);
3475 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
3476 return true;
3477
3478 case TSK_ExplicitSpecialization:
3479 // C++ [temp.explicit]p4:
3480 // For a given set of template parameters, if an explicit instantiation
3481 // of a template appears after a declaration of an explicit
3482 // specialization for that template, the explicit instantiation has no
3483 // effect.
3484 break;
3485
3486 case TSK_ExplicitInstantiationDefinition:
3487 // FIXME: Check that we aren't trying to perform an explicit instantiation
3488 // declaration now.
3489 // Fall through
3490
3491 case TSK_ImplicitInstantiation:
3492 case TSK_ExplicitInstantiationDeclaration:
3493 // Instantiate the function, if this is an explicit instantiation
3494 // definition.
3495 if (TSK == TSK_ExplicitInstantiationDefinition)
3496 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
3497 false);
3498
3499 // FIXME: setTemplateSpecializationKind doesn't (yet) work for
3500 // non-templated member functions.
3501 if (!Specialization->getPrimaryTemplate())
3502 break;
3503
3504 Specialization->setTemplateSpecializationKind(TSK);
3505 break;
3506 }
3507
3508 // FIXME: Create some kind of ExplicitInstantiationDecl here.
3509 return DeclPtrTy();
3510}
3511
Douglas Gregor333489b2009-03-27 23:10:48 +00003512Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00003513Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3514 const CXXScopeSpec &SS, IdentifierInfo *Name,
3515 SourceLocation TagLoc, SourceLocation NameLoc) {
3516 // This has to hold, because SS is expected to be defined.
3517 assert(Name && "Expected a name in a dependent tag");
3518
3519 NestedNameSpecifier *NNS
3520 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3521 if (!NNS)
3522 return true;
3523
3524 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
3525 if (T.isNull())
3526 return true;
3527
3528 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
3529 QualType ElabType = Context.getElaboratedType(T, TagKind);
3530
3531 return ElabType.getAsOpaquePtr();
3532}
3533
3534Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00003535Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3536 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00003537 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00003538 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3539 if (!NNS)
3540 return true;
3541
3542 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003543 if (T.isNull())
3544 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00003545 return T.getAsOpaquePtr();
3546}
3547
Douglas Gregordce2b622009-04-01 00:28:59 +00003548Sema::TypeResult
3549Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3550 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003551 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003552 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00003553 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00003554 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00003555 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00003556 assert(TemplateId && "Expected a template specialization type");
3557
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003558 if (computeDeclContext(SS, false)) {
3559 // If we can compute a declaration context, then the "typename"
3560 // keyword was superfluous. Just build a QualifiedNameType to keep
3561 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00003562
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003563 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
3564 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
3565 }
Mike Stump11289f42009-09-09 15:08:12 +00003566
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003567 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00003568}
3569
Douglas Gregor333489b2009-03-27 23:10:48 +00003570/// \brief Build the type that describes a C++ typename specifier,
3571/// e.g., "typename T::type".
3572QualType
3573Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
3574 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003575 CXXRecordDecl *CurrentInstantiation = 0;
3576 if (NNS->isDependent()) {
3577 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00003578
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003579 // If the nested-name-specifier does not refer to the current
3580 // instantiation, then build a typename type.
3581 if (!CurrentInstantiation)
3582 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00003583
Douglas Gregorc707da62009-09-02 13:12:51 +00003584 // The nested-name-specifier refers to the current instantiation, so the
3585 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00003586 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00003587 // extraneous "typename" keywords, and we retroactively apply this DR to
3588 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003589 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003590
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003591 DeclContext *Ctx = 0;
3592
3593 if (CurrentInstantiation)
3594 Ctx = CurrentInstantiation;
3595 else {
3596 CXXScopeSpec SS;
3597 SS.setScopeRep(NNS);
3598 SS.setRange(Range);
3599 if (RequireCompleteDeclContext(SS))
3600 return QualType();
3601
3602 Ctx = computeDeclContext(SS);
3603 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003604 assert(Ctx && "No declaration context?");
3605
3606 DeclarationName Name(&II);
Mike Stump11289f42009-09-09 15:08:12 +00003607 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
Douglas Gregor333489b2009-03-27 23:10:48 +00003608 false);
3609 unsigned DiagID = 0;
3610 Decl *Referenced = 0;
3611 switch (Result.getKind()) {
3612 case LookupResult::NotFound:
3613 if (Ctx->isTranslationUnit())
3614 DiagID = diag::err_typename_nested_not_found_global;
3615 else
3616 DiagID = diag::err_typename_nested_not_found;
3617 break;
3618
3619 case LookupResult::Found:
3620 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3621 // We found a type. Build a QualifiedNameType, since the
3622 // typename-specifier was just sugar. FIXME: Tell
3623 // QualifiedNameType that it has a "typename" prefix.
3624 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3625 }
3626
3627 DiagID = diag::err_typename_nested_not_type;
3628 Referenced = Result.getAsDecl();
3629 break;
3630
3631 case LookupResult::FoundOverloaded:
3632 DiagID = diag::err_typename_nested_not_type;
3633 Referenced = *Result.begin();
3634 break;
3635
3636 case LookupResult::AmbiguousBaseSubobjectTypes:
3637 case LookupResult::AmbiguousBaseSubobjects:
3638 case LookupResult::AmbiguousReference:
3639 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3640 return QualType();
3641 }
3642
3643 // If we get here, it's because name lookup did not find a
3644 // type. Emit an appropriate diagnostic and return an error.
3645 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3646 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3647 else
3648 Diag(Range.getEnd(), DiagID) << Range << Name;
3649 if (Referenced)
3650 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3651 << Name;
3652 return QualType();
3653}
Douglas Gregor15acfb92009-08-06 16:20:37 +00003654
3655namespace {
3656 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00003657 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3658 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00003659 SourceLocation Loc;
3660 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00003661
Douglas Gregor15acfb92009-08-06 16:20:37 +00003662 public:
Mike Stump11289f42009-09-09 15:08:12 +00003663 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00003664 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003665 DeclarationName Entity)
3666 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00003667 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00003668
3669 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00003670 /// transformed.
3671 ///
3672 /// For the purposes of type reconstruction, a type has already been
3673 /// transformed if it is NULL or if it is not dependent.
3674 bool AlreadyTransformed(QualType T) {
3675 return T.isNull() || !T->isDependentType();
3676 }
Mike Stump11289f42009-09-09 15:08:12 +00003677
3678 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00003679 /// rebuilt.
3680 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00003681
Douglas Gregor15acfb92009-08-06 16:20:37 +00003682 /// \brief Returns the name of the entity whose type is being rebuilt.
3683 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00003684
Douglas Gregor15acfb92009-08-06 16:20:37 +00003685 /// \brief Transforms an expression by returning the expression itself
3686 /// (an identity function).
3687 ///
3688 /// FIXME: This is completely unsafe; we will need to actually clone the
3689 /// expressions.
3690 Sema::OwningExprResult TransformExpr(Expr *E) {
3691 return getSema().Owned(E);
3692 }
Mike Stump11289f42009-09-09 15:08:12 +00003693
Douglas Gregor15acfb92009-08-06 16:20:37 +00003694 /// \brief Transforms a typename type by determining whether the type now
3695 /// refers to a member of the current instantiation, and then
3696 /// type-checking and building a QualifiedNameType (when possible).
3697 QualType TransformTypenameType(const TypenameType *T);
3698 };
3699}
3700
Mike Stump11289f42009-09-09 15:08:12 +00003701QualType
Douglas Gregor15acfb92009-08-06 16:20:37 +00003702CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3703 NestedNameSpecifier *NNS
3704 = TransformNestedNameSpecifier(T->getQualifier(),
3705 /*FIXME:*/SourceRange(getBaseLocation()));
3706 if (!NNS)
3707 return QualType();
3708
3709 // If the nested-name-specifier did not change, and we cannot compute the
3710 // context corresponding to the nested-name-specifier, then this
3711 // typename type will not change; exit early.
3712 CXXScopeSpec SS;
3713 SS.setRange(SourceRange(getBaseLocation()));
3714 SS.setScopeRep(NNS);
3715 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3716 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003717
3718 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00003719 // QualifiedNameType.
3720 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00003721 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00003722 = TransformType(QualType(TemplateId, 0));
3723 if (NewTemplateId.isNull())
3724 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003725
Douglas Gregor15acfb92009-08-06 16:20:37 +00003726 if (NNS == T->getQualifier() &&
3727 NewTemplateId == QualType(TemplateId, 0))
3728 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003729
Douglas Gregor15acfb92009-08-06 16:20:37 +00003730 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3731 }
Mike Stump11289f42009-09-09 15:08:12 +00003732
Douglas Gregor15acfb92009-08-06 16:20:37 +00003733 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3734}
3735
3736/// \brief Rebuilds a type within the context of the current instantiation.
3737///
Mike Stump11289f42009-09-09 15:08:12 +00003738/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00003739/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00003740/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00003741/// partial specialization thereof). This routine will rebuild that type now
3742/// that we have entered the declarator's scope, which may produce different
3743/// canonical types, e.g.,
3744///
3745/// \code
3746/// template<typename T>
3747/// struct X {
3748/// typedef T* pointer;
3749/// pointer data();
3750/// };
3751///
3752/// template<typename T>
3753/// typename X<T>::pointer X<T>::data() { ... }
3754/// \endcode
3755///
3756/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3757/// since we do not know that we can look into X<T> when we parsed the type.
3758/// This function will rebuild the type, performing the lookup of "pointer"
3759/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3760/// as the canonical type of T*, allowing the return types of the out-of-line
3761/// definition and the declaration to match.
3762QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3763 DeclarationName Name) {
3764 if (T.isNull() || !T->isDependentType())
3765 return T;
Mike Stump11289f42009-09-09 15:08:12 +00003766
Douglas Gregor15acfb92009-08-06 16:20:37 +00003767 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3768 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00003769}
Douglas Gregorbe999392009-09-15 16:23:51 +00003770
3771/// \brief Produces a formatted string that describes the binding of
3772/// template parameters to template arguments.
3773std::string
3774Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3775 const TemplateArgumentList &Args) {
3776 std::string Result;
3777
3778 if (!Params || Params->size() == 0)
3779 return Result;
3780
3781 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3782 if (I == 0)
3783 Result += "[with ";
3784 else
3785 Result += ", ";
3786
3787 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
3788 Result += Id->getName();
3789 } else {
3790 Result += '$';
3791 Result += llvm::utostr(I);
3792 }
3793
3794 Result += " = ";
3795
3796 switch (Args[I].getKind()) {
3797 case TemplateArgument::Null:
3798 Result += "<no value>";
3799 break;
3800
3801 case TemplateArgument::Type: {
3802 std::string TypeStr;
3803 Args[I].getAsType().getAsStringInternal(TypeStr,
3804 Context.PrintingPolicy);
3805 Result += TypeStr;
3806 break;
3807 }
3808
3809 case TemplateArgument::Declaration: {
3810 bool Unnamed = true;
3811 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
3812 if (ND->getDeclName()) {
3813 Unnamed = false;
3814 Result += ND->getNameAsString();
3815 }
3816 }
3817
3818 if (Unnamed) {
3819 Result += "<anonymous>";
3820 }
3821 break;
3822 }
3823
3824 case TemplateArgument::Integral: {
3825 Result += Args[I].getAsIntegral()->toString(10);
3826 break;
3827 }
3828
3829 case TemplateArgument::Expression: {
3830 assert(false && "No expressions in deduced template arguments!");
3831 Result += "<expression>";
3832 break;
3833 }
3834
3835 case TemplateArgument::Pack:
3836 // FIXME: Format template argument packs
3837 Result += "<template argument pack>";
3838 break;
3839 }
3840 }
3841
3842 Result += ']';
3843 return Result;
3844}