blob: 5c6ec0004af22c8a45e548796aaca852fa1522ce [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000020#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000021#include "llvm/Support/Compiler.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000022#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000023using namespace clang;
24
Douglas Gregorb7bfe792009-09-02 22:59:36 +000025/// \brief Determine whether the declaration found is acceptable as the name
26/// of a template and, if so, return that template declaration. Otherwise,
27/// returns NULL.
28static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
29 if (!D)
30 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000031
Douglas Gregorb7bfe792009-09-02 22:59:36 +000032 if (isa<TemplateDecl>(D))
33 return D;
Mike Stump11289f42009-09-09 15:08:12 +000034
Douglas Gregorb7bfe792009-09-02 22:59:36 +000035 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
36 // C++ [temp.local]p1:
37 // Like normal (non-template) classes, class templates have an
38 // injected-class-name (Clause 9). The injected-class-name
39 // can be used with or without a template-argument-list. When
40 // it is used without a template-argument-list, it is
41 // equivalent to the injected-class-name followed by the
42 // template-parameters of the class template enclosed in
43 // <>. When it is used with a template-argument-list, it
44 // refers to the specified class template specialization,
45 // which could be the current specialization or another
46 // specialization.
47 if (Record->isInjectedClassName()) {
48 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
49 if (Record->getDescribedClassTemplate())
50 return Record->getDescribedClassTemplate();
51
52 if (ClassTemplateSpecializationDecl *Spec
53 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
54 return Spec->getSpecializedTemplate();
55 }
Mike Stump11289f42009-09-09 15:08:12 +000056
Douglas Gregorb7bfe792009-09-02 22:59:36 +000057 return 0;
58 }
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregorb7bfe792009-09-02 22:59:36 +000060 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
61 if (!Ovl)
62 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000063
Douglas Gregorb7bfe792009-09-02 22:59:36 +000064 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
65 FEnd = Ovl->function_end();
66 F != FEnd; ++F) {
67 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
68 // We've found a function template. Determine whether there are
69 // any other function templates we need to bundle together in an
70 // OverloadedFunctionDecl
71 for (++F; F != FEnd; ++F) {
72 if (isa<FunctionTemplateDecl>(*F))
73 break;
74 }
Mike Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregorb7bfe792009-09-02 22:59:36 +000076 if (F != FEnd) {
77 // Build an overloaded function decl containing only the
78 // function templates in Ovl.
Mike Stump11289f42009-09-09 15:08:12 +000079 OverloadedFunctionDecl *OvlTemplate
Douglas Gregorb7bfe792009-09-02 22:59:36 +000080 = OverloadedFunctionDecl::Create(Context,
81 Ovl->getDeclContext(),
82 Ovl->getDeclName());
83 OvlTemplate->addOverload(FuncTmpl);
84 OvlTemplate->addOverload(*F);
85 for (++F; F != FEnd; ++F) {
86 if (isa<FunctionTemplateDecl>(*F))
87 OvlTemplate->addOverload(*F);
88 }
Mike Stump11289f42009-09-09 15:08:12 +000089
Douglas Gregorb7bfe792009-09-02 22:59:36 +000090 return OvlTemplate;
91 }
92
93 return FuncTmpl;
94 }
95 }
Mike Stump11289f42009-09-09 15:08:12 +000096
Douglas Gregorb7bfe792009-09-02 22:59:36 +000097 return 0;
98}
99
100TemplateNameKind Sema::isTemplateName(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +0000101 const IdentifierInfo &II,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000102 SourceLocation IdLoc,
Douglas Gregore861bac2009-08-25 22:51:20 +0000103 const CXXScopeSpec *SS,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000104 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000105 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000106 TemplateTy &TemplateResult) {
107 // Determine where to perform name lookup
108 DeclContext *LookupCtx = 0;
109 bool isDependent = false;
110 if (ObjectTypePtr) {
111 // This nested-name-specifier occurs in a member access expression, e.g.,
112 // x->B::f, and we are looking into the type of the object.
Mike Stump11289f42009-09-09 15:08:12 +0000113 assert((!SS || !SS->isSet()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000114 "ObjectType and scope specifier cannot coexist");
115 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
116 LookupCtx = computeDeclContext(ObjectType);
117 isDependent = ObjectType->isDependentType();
118 } else if (SS && SS->isSet()) {
119 // This nested-name-specifier occurs after another nested-name-specifier,
120 // so long into the context associated with the prior nested-name-specifier.
121
122 LookupCtx = computeDeclContext(*SS, EnteringContext);
123 isDependent = isDependentScopeSpecifier(*SS);
124 }
Mike Stump11289f42009-09-09 15:08:12 +0000125
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000126 LookupResult Found;
127 bool ObjectTypeSearchedInScope = false;
128 if (LookupCtx) {
129 // Perform "qualified" name lookup into the declaration context we
130 // computed, which is either the type of the base of a member access
Mike Stump11289f42009-09-09 15:08:12 +0000131 // expression or the declaration context associated with a prior
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000132 // nested-name-specifier.
133
134 // The declaration context must be complete.
135 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
136 return TNK_Non_template;
Mike Stump11289f42009-09-09 15:08:12 +0000137
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000138 Found = LookupQualifiedName(LookupCtx, &II, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +0000139
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000140 if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
141 // C++ [basic.lookup.classref]p1:
142 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump11289f42009-09-09 15:08:12 +0000143 // immediately followed by an identifier followed by a <, the
144 // identifier must be looked up to determine whether the < is the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000145 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump11289f42009-09-09 15:08:12 +0000146 // The identifier is first looked up in the class of the object
147 // expression. If the identifier is not found, it is then looked up in
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000148 // the context of the entire postfix-expression and shall name a class
149 // or function template.
150 //
151 // FIXME: When we're instantiating a template, do we actually have to
152 // look in the scope of the template? Seems fishy...
153 Found = LookupName(S, &II, LookupOrdinaryName);
154 ObjectTypeSearchedInScope = true;
155 }
156 } else if (isDependent) {
Mike Stump11289f42009-09-09 15:08:12 +0000157 // We cannot look into a dependent object type or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158 return TNK_Non_template;
159 } else {
160 // Perform unqualified name lookup in the current scope.
161 Found = LookupName(S, &II, LookupOrdinaryName);
162 }
Mike Stump11289f42009-09-09 15:08:12 +0000163
Douglas Gregore861bac2009-08-25 22:51:20 +0000164 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump11289f42009-09-09 15:08:12 +0000165 assert(!Found.isAmbiguous() &&
Douglas Gregore861bac2009-08-25 22:51:20 +0000166 "Cannot handle template name-lookup ambiguities");
Douglas Gregordc572a32009-03-30 22:58:21 +0000167
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000168 NamedDecl *Template = isAcceptableTemplateName(Context, Found);
169 if (!Template)
170 return TNK_Non_template;
171
172 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
173 // C++ [basic.lookup.classref]p1:
Mike Stump11289f42009-09-09 15:08:12 +0000174 // [...] If the lookup in the class of the object expression finds a
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000175 // template, the name is also looked up in the context of the entire
176 // postfix-expression and [...]
177 //
178 LookupResult FoundOuter = LookupName(S, &II, LookupOrdinaryName);
179 // FIXME: Handle ambiguities in this lookup better
180 NamedDecl *OuterTemplate = isAcceptableTemplateName(Context, FoundOuter);
Mike Stump11289f42009-09-09 15:08:12 +0000181
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000182 if (!OuterTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +0000183 // - if the name is not found, the name found in the class of the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000184 // object expression is used, otherwise
185 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump11289f42009-09-09 15:08:12 +0000186 // - if the name is found in the context of the entire
187 // postfix-expression and does not name a class template, the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000188 // found in the class of the object expression is used, otherwise
189 } else {
190 // - if the name found is a class template, it must refer to the same
Mike Stump11289f42009-09-09 15:08:12 +0000191 // entity as the one found in the class of the object expression,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000192 // otherwise the program is ill-formed.
193 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
194 Diag(IdLoc, diag::err_nested_name_member_ref_lookup_ambiguous)
195 << &II;
196 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
197 << QualType::getFromOpaquePtr(ObjectTypePtr);
198 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump11289f42009-09-09 15:08:12 +0000199
200 // Recover by taking the template that we found in the object
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000201 // expression's type.
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000202 }
Mike Stump11289f42009-09-09 15:08:12 +0000203 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000204 }
Mike Stump11289f42009-09-09 15:08:12 +0000205
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000206 if (SS && SS->isSet() && !SS->isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000207 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000208 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000209 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000210 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000211 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000212 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
213 Ovl));
214 else
Mike Stump11289f42009-09-09 15:08:12 +0000215 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000216 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000217 cast<TemplateDecl>(Template)));
218 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000219 = dyn_cast<OverloadedFunctionDecl>(Template)) {
220 TemplateResult = TemplateTy::make(TemplateName(Ovl));
221 } else {
222 TemplateResult = TemplateTy::make(
223 TemplateName(cast<TemplateDecl>(Template)));
224 }
Mike Stump11289f42009-09-09 15:08:12 +0000225
226 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000227 isa<TemplateTemplateParmDecl>(Template))
228 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000229
230 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000231 isa<OverloadedFunctionDecl>(Template)) &&
232 "Unhandled template kind in Sema::isTemplateName");
233 return TNK_Function_template;
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000234}
235
Douglas Gregor5101c242008-12-05 18:15:24 +0000236/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
237/// that the template parameter 'PrevDecl' is being shadowed by a new
238/// declaration at location Loc. Returns true to indicate that this is
239/// an error, and false otherwise.
240bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000241 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000242
243 // Microsoft Visual C++ permits template parameters to be shadowed.
244 if (getLangOptions().Microsoft)
245 return false;
246
247 // C++ [temp.local]p4:
248 // A template-parameter shall not be redeclared within its
249 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000250 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000251 << cast<NamedDecl>(PrevDecl)->getDeclName();
252 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
253 return true;
254}
255
Douglas Gregor463421d2009-03-03 04:44:36 +0000256/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000257/// the parameter D to reference the templated declaration and return a pointer
258/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000259TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000260 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000261 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000262 return Temp;
263 }
264 return 0;
265}
266
Douglas Gregor5101c242008-12-05 18:15:24 +0000267/// ActOnTypeParameter - Called when a C++ template type parameter
268/// (e.g., "typename T") has been parsed. Typename specifies whether
269/// the keyword "typename" was used to declare the type parameter
270/// (otherwise, "class" was used), and KeyLoc is the location of the
271/// "class" or "typename" keyword. ParamName is the name of the
272/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000273/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000274/// If the type parameter has a default argument, it will be added
275/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000276Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000277 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000278 SourceLocation KeyLoc,
279 IdentifierInfo *ParamName,
280 SourceLocation ParamNameLoc,
281 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000282 assert(S->isTemplateParamScope() &&
283 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000284 bool Invalid = false;
285
286 if (ParamName) {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000287 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000288 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000289 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000290 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000291 }
292
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000293 SourceLocation Loc = ParamNameLoc;
294 if (!ParamName)
295 Loc = KeyLoc;
296
Douglas Gregor5101c242008-12-05 18:15:24 +0000297 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000298 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
299 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000300 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000301 if (Invalid)
302 Param->setInvalidDecl();
303
304 if (ParamName) {
305 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000306 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000307 IdResolver.AddDecl(Param);
308 }
309
Chris Lattner83f095c2009-03-28 19:18:32 +0000310 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000311}
312
Douglas Gregordba32632009-02-10 19:49:53 +0000313/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000314/// Default) to the given template type parameter (TypeParam).
315void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000316 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000317 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000318 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000319 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000320 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000321 // FIXME: Preserve type source info.
322 QualType Default = GetTypeFromParser(DefaultT);
Douglas Gregordba32632009-02-10 19:49:53 +0000323
Anders Carlssond3824352009-06-12 22:30:13 +0000324 // C++0x [temp.param]p9:
325 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000326 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000327 if (Parm->isParameterPack()) {
328 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000329 return;
330 }
Mike Stump11289f42009-09-09 15:08:12 +0000331
Douglas Gregordba32632009-02-10 19:49:53 +0000332 // C++ [temp.param]p14:
333 // A template-parameter shall not be used in its own default argument.
334 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000335
Douglas Gregordba32632009-02-10 19:49:53 +0000336 // Check the template argument itself.
337 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
338 Parm->setInvalidDecl();
339 return;
340 }
341
342 Parm->setDefaultArgument(Default, DefaultLoc, false);
343}
344
Douglas Gregor463421d2009-03-03 04:44:36 +0000345/// \brief Check that the type of a non-type template parameter is
346/// well-formed.
347///
348/// \returns the (possibly-promoted) parameter type if valid;
349/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000350QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000351Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
352 // C++ [temp.param]p4:
353 //
354 // A non-type template-parameter shall have one of the following
355 // (optionally cv-qualified) types:
356 //
357 // -- integral or enumeration type,
358 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000359 // -- pointer to object or pointer to function,
360 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000361 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
362 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000363 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000364 T->isReferenceType() ||
365 // -- pointer to member.
366 T->isMemberPointerType() ||
367 // If T is a dependent type, we can't do the check now, so we
368 // assume that it is well-formed.
369 T->isDependentType())
370 return T;
371 // C++ [temp.param]p8:
372 //
373 // A non-type template-parameter of type "array of T" or
374 // "function returning T" is adjusted to be of type "pointer to
375 // T" or "pointer to function returning T", respectively.
376 else if (T->isArrayType())
377 // FIXME: Keep the type prior to promotion?
378 return Context.getArrayDecayedType(T);
379 else if (T->isFunctionType())
380 // FIXME: Keep the type prior to promotion?
381 return Context.getPointerType(T);
382
383 Diag(Loc, diag::err_template_nontype_parm_bad_type)
384 << T;
385
386 return QualType();
387}
388
Douglas Gregor5101c242008-12-05 18:15:24 +0000389/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
390/// template parameter (e.g., "int Size" in "template<int Size>
391/// class Array") has been parsed. S is the current scope and D is
392/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000393Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000394 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000395 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000396 DeclaratorInfo *DInfo = 0;
397 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000398
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000399 assert(S->isTemplateParamScope() &&
400 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000401 bool Invalid = false;
402
403 IdentifierInfo *ParamName = D.getIdentifier();
404 if (ParamName) {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000405 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000406 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000407 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000408 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000409 }
410
Douglas Gregor463421d2009-03-03 04:44:36 +0000411 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000412 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000413 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000414 Invalid = true;
415 }
Douglas Gregor81338792009-02-10 17:43:50 +0000416
Douglas Gregor5101c242008-12-05 18:15:24 +0000417 NonTypeTemplateParmDecl *Param
418 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000419 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000420 if (Invalid)
421 Param->setInvalidDecl();
422
423 if (D.getIdentifier()) {
424 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000425 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000426 IdResolver.AddDecl(Param);
427 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000428 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000429}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000430
Douglas Gregordba32632009-02-10 19:49:53 +0000431/// \brief Adds a default argument to the given non-type template
432/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000433void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000434 SourceLocation EqualLoc,
435 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000436 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000437 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000438 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000439
Douglas Gregordba32632009-02-10 19:49:53 +0000440 // C++ [temp.param]p14:
441 // A template-parameter shall not be used in its own default argument.
442 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000443
Douglas Gregordba32632009-02-10 19:49:53 +0000444 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000445 TemplateArgument Converted;
446 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
447 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000448 TemplateParm->setInvalidDecl();
449 return;
450 }
451
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000452 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000453}
454
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000455
456/// ActOnTemplateTemplateParameter - Called when a C++ template template
457/// parameter (e.g. T in template <template <typename> class T> class array)
458/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000459Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
460 SourceLocation TmpLoc,
461 TemplateParamsTy *Params,
462 IdentifierInfo *Name,
463 SourceLocation NameLoc,
464 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000465 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000466 assert(S->isTemplateParamScope() &&
467 "Template template parameter not in template parameter scope!");
468
469 // Construct the parameter object.
470 TemplateTemplateParmDecl *Param =
471 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
472 Position, Name,
473 (TemplateParameterList*)Params);
474
475 // Make sure the parameter is valid.
476 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
477 // do anything yet. However, if the template parameter list or (eventual)
478 // default value is ever invalidated, that will propagate here.
479 bool Invalid = false;
480 if (Invalid) {
481 Param->setInvalidDecl();
482 }
483
484 // If the tt-param has a name, then link the identifier into the scope
485 // and lookup mechanisms.
486 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000487 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000488 IdResolver.AddDecl(Param);
489 }
490
Chris Lattner83f095c2009-03-28 19:18:32 +0000491 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000492}
493
Douglas Gregordba32632009-02-10 19:49:53 +0000494/// \brief Adds a default argument to the given template template
495/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000496void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000497 SourceLocation EqualLoc,
498 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000499 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000500 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000501
502 // Since a template-template parameter's default argument is an
503 // id-expression, it must be a DeclRefExpr.
Mike Stump11289f42009-09-09 15:08:12 +0000504 DeclRefExpr *Default
Douglas Gregordba32632009-02-10 19:49:53 +0000505 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
506
507 // C++ [temp.param]p14:
508 // A template-parameter shall not be used in its own default argument.
509 // FIXME: Implement this check! Needs a recursive walk over the types.
510
511 // Check the well-formedness of the template argument.
512 if (!isa<TemplateDecl>(Default->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +0000513 Diag(Default->getSourceRange().getBegin(),
Douglas Gregordba32632009-02-10 19:49:53 +0000514 diag::err_template_arg_must_be_template)
515 << Default->getSourceRange();
516 TemplateParm->setInvalidDecl();
517 return;
Mike Stump11289f42009-09-09 15:08:12 +0000518 }
Douglas Gregordba32632009-02-10 19:49:53 +0000519 if (CheckTemplateArgument(TemplateParm, Default)) {
520 TemplateParm->setInvalidDecl();
521 return;
522 }
523
524 DefaultE.release();
525 TemplateParm->setDefaultArgument(Default);
526}
527
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000528/// ActOnTemplateParameterList - Builds a TemplateParameterList that
529/// contains the template parameters in Params/NumParams.
530Sema::TemplateParamsTy *
531Sema::ActOnTemplateParameterList(unsigned Depth,
532 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000533 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000534 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000535 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000536 SourceLocation RAngleLoc) {
537 if (ExportLoc.isValid())
538 Diag(ExportLoc, diag::note_template_export_unsupported);
539
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000540 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000541 (NamedDecl**)Params, NumParams,
542 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000543}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000544
Douglas Gregorc08f4892009-03-25 00:13:59 +0000545Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000546Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000547 SourceLocation KWLoc, const CXXScopeSpec &SS,
548 IdentifierInfo *Name, SourceLocation NameLoc,
549 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000550 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000551 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000552 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000553 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000554 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000555 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000556
557 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000558 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000559 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000560
John McCall27b5c252009-09-14 21:59:20 +0000561 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
562 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000563
564 // There is no such thing as an unnamed class template.
565 if (!Name) {
566 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000567 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000568 }
569
570 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000571 DeclContext *SemanticContext;
572 LookupResult Previous;
573 if (SS.isNotEmpty() && !SS.isInvalid()) {
574 SemanticContext = computeDeclContext(SS, true);
575 if (!SemanticContext) {
576 // FIXME: Produce a reasonable diagnostic here
577 return true;
578 }
Mike Stump11289f42009-09-09 15:08:12 +0000579
580 Previous = LookupQualifiedName(SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000581 true);
582 } else {
583 SemanticContext = CurContext;
584 Previous = LookupName(S, Name, LookupOrdinaryName, true);
585 }
Mike Stump11289f42009-09-09 15:08:12 +0000586
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000587 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
588 NamedDecl *PrevDecl = 0;
589 if (Previous.begin() != Previous.end())
590 PrevDecl = *Previous.begin();
591
Douglas Gregor9acb6902009-09-26 07:05:09 +0000592 if (PrevDecl && TUK == TUK_Friend) {
593 // C++ [namespace.memdef]p3:
594 // [...] When looking for a prior declaration of a class or a function
595 // declared as a friend, and when the name of the friend class or
596 // function is neither a qualified name nor a template-id, scopes outside
597 // the innermost enclosing namespace scope are not considered.
598 DeclContext *OutermostContext = CurContext;
599 while (!OutermostContext->isFileContext())
600 OutermostContext = OutermostContext->getLookupParent();
601
602 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
603 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
604 SemanticContext = PrevDecl->getDeclContext();
605 } else {
606 // Declarations in outer scopes don't matter. However, the outermost
607 // context we computed is the semntic context for our new
608 // declaration.
609 PrevDecl = 0;
610 SemanticContext = OutermostContext;
611 }
612 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000613 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000614
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000615 // If there is a previous declaration with the same name, check
616 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000617 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000618 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
619 if (PrevClassTemplate) {
620 // Ensure that the template parameter lists are compatible.
621 if (!TemplateParameterListsAreEqual(TemplateParams,
622 PrevClassTemplate->getTemplateParameters(),
623 /*Complain=*/true))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000624 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000625
626 // C++ [temp.class]p4:
627 // In a redeclaration, partial specialization, explicit
628 // specialization or explicit instantiation of a class template,
629 // the class-key shall agree in kind with the original class
630 // template declaration (7.1.5.3).
631 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000632 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000633 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000634 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000635 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000636 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000637 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000638 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000639 }
640
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000641 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000642 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000643 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
644 Diag(NameLoc, diag::err_redefinition) << Name;
645 Diag(Def->getLocation(), diag::note_previous_definition);
646 // FIXME: Would it make sense to try to "forget" the previous
647 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000648 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000649 }
650 }
651 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
652 // Maybe we will complain about the shadowed template parameter.
653 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
654 // Just pretend that we didn't see the previous declaration.
655 PrevDecl = 0;
656 } else if (PrevDecl) {
657 // C++ [temp]p5:
658 // A class template shall not have the same name as any other
659 // template, class, function, object, enumeration, enumerator,
660 // namespace, or type in the same scope (3.3), except as specified
661 // in (14.5.4).
662 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
663 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000664 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000665 }
666
Douglas Gregordba32632009-02-10 19:49:53 +0000667 // Check the template parameter list of this declaration, possibly
668 // merging in the template parameter list from the previous class
669 // template declaration.
670 if (CheckTemplateParameterList(TemplateParams,
671 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
672 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000673
Douglas Gregore362cea2009-05-10 22:57:19 +0000674 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000675 // declaration!
676
Mike Stump11289f42009-09-09 15:08:12 +0000677 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000678 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000679 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000680 PrevClassTemplate->getTemplatedDecl() : 0,
681 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000682
683 ClassTemplateDecl *NewTemplate
684 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
685 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000686 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000687 NewClass->setDescribedClassTemplate(NewTemplate);
688
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000689 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000690 QualType T =
691 Context.getTypeDeclType(NewClass,
692 PrevClassTemplate?
693 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000694 assert(T->isDependentType() && "Class template type is not dependent?");
695 (void)T;
696
Anders Carlsson137108d2009-03-26 01:24:28 +0000697 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000698 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000699 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000700
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000701 // Set the lexical context of these templates
702 NewClass->setLexicalDeclContext(CurContext);
703 NewTemplate->setLexicalDeclContext(CurContext);
704
John McCall9bb74a52009-07-31 02:45:11 +0000705 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000706 NewClass->startDefinition();
707
708 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000709 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000710
John McCall27b5c252009-09-14 21:59:20 +0000711 if (TUK != TUK_Friend)
712 PushOnScopeChains(NewTemplate, S);
713 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000714 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000715 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000716 NewClass->setAccess(PrevClassTemplate->getAccess());
717 }
John McCall27b5c252009-09-14 21:59:20 +0000718
Douglas Gregor3dad8422009-09-26 06:47:28 +0000719 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
720 PrevClassTemplate != NULL);
721
John McCall27b5c252009-09-14 21:59:20 +0000722 // Friend templates are visible in fairly strange ways.
723 if (!CurContext->isDependentContext()) {
724 DeclContext *DC = SemanticContext->getLookupContext();
725 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
726 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
727 PushOnScopeChains(NewTemplate, EnclosingScope,
728 /* AddToContext = */ false);
729 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000730
731 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
732 NewClass->getLocation(),
733 NewTemplate,
734 /*FIXME:*/NewClass->getLocation());
735 Friend->setAccess(AS_public);
736 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000737 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000738
Douglas Gregordba32632009-02-10 19:49:53 +0000739 if (Invalid) {
740 NewTemplate->setInvalidDecl();
741 NewClass->setInvalidDecl();
742 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000743 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000744}
745
Douglas Gregordba32632009-02-10 19:49:53 +0000746/// \brief Checks the validity of a template parameter list, possibly
747/// considering the template parameter list from a previous
748/// declaration.
749///
750/// If an "old" template parameter list is provided, it must be
751/// equivalent (per TemplateParameterListsAreEqual) to the "new"
752/// template parameter list.
753///
754/// \param NewParams Template parameter list for a new template
755/// declaration. This template parameter list will be updated with any
756/// default arguments that are carried through from the previous
757/// template parameter list.
758///
759/// \param OldParams If provided, template parameter list from a
760/// previous declaration of the same template. Default template
761/// arguments will be merged from the old template parameter list to
762/// the new template parameter list.
763///
764/// \returns true if an error occurred, false otherwise.
765bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
766 TemplateParameterList *OldParams) {
767 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000768
Douglas Gregordba32632009-02-10 19:49:53 +0000769 // C++ [temp.param]p10:
770 // The set of default template-arguments available for use with a
771 // template declaration or definition is obtained by merging the
772 // default arguments from the definition (if in scope) and all
773 // declarations in scope in the same way default function
774 // arguments are (8.3.6).
775 bool SawDefaultArgument = false;
776 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000777
Anders Carlsson327865d2009-06-12 23:20:15 +0000778 bool SawParameterPack = false;
779 SourceLocation ParameterPackLoc;
780
Mike Stumpc89c8e32009-02-11 23:03:27 +0000781 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000782 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000783 if (OldParams)
784 OldParam = OldParams->begin();
785
786 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
787 NewParamEnd = NewParams->end();
788 NewParam != NewParamEnd; ++NewParam) {
789 // Variables used to diagnose redundant default arguments
790 bool RedundantDefaultArg = false;
791 SourceLocation OldDefaultLoc;
792 SourceLocation NewDefaultLoc;
793
794 // Variables used to diagnose missing default arguments
795 bool MissingDefaultArg = false;
796
Anders Carlsson327865d2009-06-12 23:20:15 +0000797 // C++0x [temp.param]p11:
798 // If a template parameter of a class template is a template parameter pack,
799 // it must be the last template parameter.
800 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +0000801 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +0000802 diag::err_template_param_pack_must_be_last_template_parameter);
803 Invalid = true;
804 }
805
Douglas Gregordba32632009-02-10 19:49:53 +0000806 // Merge default arguments for template type parameters.
807 if (TemplateTypeParmDecl *NewTypeParm
808 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump11289f42009-09-09 15:08:12 +0000809 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000810 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000811
Anders Carlsson327865d2009-06-12 23:20:15 +0000812 if (NewTypeParm->isParameterPack()) {
813 assert(!NewTypeParm->hasDefaultArgument() &&
814 "Parameter packs can't have a default argument!");
815 SawParameterPack = true;
816 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000817 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000818 NewTypeParm->hasDefaultArgument()) {
819 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
820 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
821 SawDefaultArgument = true;
822 RedundantDefaultArg = true;
823 PreviousDefaultArgLoc = NewDefaultLoc;
824 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
825 // Merge the default argument from the old declaration to the
826 // new declaration.
827 SawDefaultArgument = true;
828 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
829 OldTypeParm->getDefaultArgumentLoc(),
830 true);
831 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
832 } else if (NewTypeParm->hasDefaultArgument()) {
833 SawDefaultArgument = true;
834 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
835 } else if (SawDefaultArgument)
836 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000837 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000838 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000839 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000840 NonTypeTemplateParmDecl *OldNonTypeParm
841 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000842 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000843 NewNonTypeParm->hasDefaultArgument()) {
844 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
845 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
846 SawDefaultArgument = true;
847 RedundantDefaultArg = true;
848 PreviousDefaultArgLoc = NewDefaultLoc;
849 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
850 // Merge the default argument from the old declaration to the
851 // new declaration.
852 SawDefaultArgument = true;
853 // FIXME: We need to create a new kind of "default argument"
854 // expression that points to a previous template template
855 // parameter.
856 NewNonTypeParm->setDefaultArgument(
857 OldNonTypeParm->getDefaultArgument());
858 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
859 } else if (NewNonTypeParm->hasDefaultArgument()) {
860 SawDefaultArgument = true;
861 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
862 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000863 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000864 } else {
Douglas Gregordba32632009-02-10 19:49:53 +0000865 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000866 TemplateTemplateParmDecl *NewTemplateParm
867 = cast<TemplateTemplateParmDecl>(*NewParam);
868 TemplateTemplateParmDecl *OldTemplateParm
869 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000870 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000871 NewTemplateParm->hasDefaultArgument()) {
872 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
873 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
874 SawDefaultArgument = true;
875 RedundantDefaultArg = true;
876 PreviousDefaultArgLoc = NewDefaultLoc;
877 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
878 // Merge the default argument from the old declaration to the
879 // new declaration.
880 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +0000881 // FIXME: We need to create a new kind of "default argument" expression
882 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +0000883 NewTemplateParm->setDefaultArgument(
884 OldTemplateParm->getDefaultArgument());
885 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
886 } else if (NewTemplateParm->hasDefaultArgument()) {
887 SawDefaultArgument = true;
888 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
889 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000890 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +0000891 }
892
893 if (RedundantDefaultArg) {
894 // C++ [temp.param]p12:
895 // A template-parameter shall not be given default arguments
896 // by two different declarations in the same scope.
897 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
898 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
899 Invalid = true;
900 } else if (MissingDefaultArg) {
901 // C++ [temp.param]p11:
902 // If a template-parameter has a default template-argument,
903 // all subsequent template-parameters shall have a default
904 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +0000905 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +0000906 diag::err_template_param_default_arg_missing);
907 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
908 Invalid = true;
909 }
910
911 // If we have an old template parameter list that we're merging
912 // in, move on to the next parameter.
913 if (OldParams)
914 ++OldParam;
915 }
916
917 return Invalid;
918}
Douglas Gregord32e0282009-02-09 23:23:08 +0000919
Mike Stump11289f42009-09-09 15:08:12 +0000920/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +0000921/// specifier, returning the template parameter list that applies to the
922/// name.
923///
924/// \param DeclStartLoc the start of the declaration that has a scope
925/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +0000926///
Douglas Gregord8d297c2009-07-21 23:53:31 +0000927/// \param SS the scope specifier that will be matched to the given template
928/// parameter lists. This scope specifier precedes a qualified name that is
929/// being declared.
930///
931/// \param ParamLists the template parameter lists, from the outermost to the
932/// innermost template parameter lists.
933///
934/// \param NumParamLists the number of template parameter lists in ParamLists.
935///
Douglas Gregor5c0405d2009-10-07 22:35:40 +0000936/// \param IsExplicitSpecialization will be set true if the entity being
937/// declared is an explicit specialization, false otherwise.
938///
Mike Stump11289f42009-09-09 15:08:12 +0000939/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +0000940/// name that is preceded by the scope specifier @p SS. This template
941/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +0000942/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +0000943/// template specialization), or may be NULL (if we were's declaring isn't
944/// itself a template).
945TemplateParameterList *
946Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
947 const CXXScopeSpec &SS,
948 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +0000949 unsigned NumParamLists,
950 bool &IsExplicitSpecialization) {
951 IsExplicitSpecialization = false;
952
Douglas Gregord8d297c2009-07-21 23:53:31 +0000953 // Find the template-ids that occur within the nested-name-specifier. These
954 // template-ids will match up with the template parameter lists.
955 llvm::SmallVector<const TemplateSpecializationType *, 4>
956 TemplateIdsInSpecifier;
957 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
958 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +0000959 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +0000960 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
961 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
962 if (!Template)
963 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +0000964
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000965 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +0000966 ClassTemplateSpecializationDecl *SpecDecl
967 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
968 // If the nested name specifier refers to an explicit specialization,
969 // we don't need a template<> header.
Douglas Gregor82e22862009-09-16 00:01:48 +0000970 // FIXME: revisit this approach once we cope with specializations
Douglas Gregor15301382009-07-30 17:40:51 +0000971 // properly.
Douglas Gregord8d297c2009-07-21 23:53:31 +0000972 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
973 continue;
974 }
Mike Stump11289f42009-09-09 15:08:12 +0000975
Douglas Gregord8d297c2009-07-21 23:53:31 +0000976 TemplateIdsInSpecifier.push_back(SpecType);
977 }
978 }
Mike Stump11289f42009-09-09 15:08:12 +0000979
Douglas Gregord8d297c2009-07-21 23:53:31 +0000980 // Reverse the list of template-ids in the scope specifier, so that we can
981 // more easily match up the template-ids and the template parameter lists.
982 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +0000983
Douglas Gregord8d297c2009-07-21 23:53:31 +0000984 SourceLocation FirstTemplateLoc = DeclStartLoc;
985 if (NumParamLists)
986 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000987
Douglas Gregord8d297c2009-07-21 23:53:31 +0000988 // Match the template-ids found in the specifier to the template parameter
989 // lists.
990 unsigned Idx = 0;
991 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
992 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +0000993 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
994 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +0000995 if (Idx >= NumParamLists) {
996 // We have a template-id without a corresponding template parameter
997 // list.
998 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +0000999 // FIXME: the location information here isn't great.
1000 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001001 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001002 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001003 << SS.getRange();
1004 } else {
1005 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1006 << SS.getRange()
1007 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1008 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001009 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001010 }
1011 return 0;
1012 }
Mike Stump11289f42009-09-09 15:08:12 +00001013
Douglas Gregord8d297c2009-07-21 23:53:31 +00001014 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001015 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001016 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001017 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1018
Mike Stump11289f42009-09-09 15:08:12 +00001019 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001020 = dyn_cast<ClassTemplateDecl>(Template)) {
1021 TemplateParameterList *ExpectedTemplateParams = 0;
1022 // Is this template-id naming the primary template?
1023 if (Context.hasSameType(TemplateId,
1024 ClassTemplate->getInjectedClassNameType(Context)))
1025 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1026 // ... or a partial specialization?
1027 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1028 = ClassTemplate->findPartialSpecialization(TemplateId))
1029 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1030
1031 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001032 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001033 ExpectedTemplateParams,
1034 true);
Mike Stump11289f42009-09-09 15:08:12 +00001035 }
Douglas Gregor15301382009-07-30 17:40:51 +00001036 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001037 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001038 diag::err_template_param_list_matches_nontemplate)
1039 << TemplateId
1040 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001041 else
1042 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001043 }
Mike Stump11289f42009-09-09 15:08:12 +00001044
Douglas Gregord8d297c2009-07-21 23:53:31 +00001045 // If there were at least as many template-ids as there were template
1046 // parameter lists, then there are no template parameter lists remaining for
1047 // the declaration itself.
1048 if (Idx >= NumParamLists)
1049 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001050
Douglas Gregord8d297c2009-07-21 23:53:31 +00001051 // If there were too many template parameter lists, complain about that now.
1052 if (Idx != NumParamLists - 1) {
1053 while (Idx < NumParamLists - 1) {
Mike Stump11289f42009-09-09 15:08:12 +00001054 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001055 diag::err_template_spec_extra_headers)
1056 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1057 ParamLists[Idx]->getRAngleLoc());
1058 ++Idx;
1059 }
1060 }
Mike Stump11289f42009-09-09 15:08:12 +00001061
Douglas Gregord8d297c2009-07-21 23:53:31 +00001062 // Return the last template parameter list, which corresponds to the
1063 // entity being declared.
1064 return ParamLists[NumParamLists - 1];
1065}
1066
Douglas Gregorc40290e2009-03-09 23:48:35 +00001067/// \brief Translates template arguments as provided by the parser
1068/// into template arguments used by semantic analysis.
Douglas Gregor0e876e02009-09-25 23:53:26 +00001069void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
1070 SourceLocation *TemplateArgLocs,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001071 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
1072 TemplateArgs.reserve(TemplateArgsIn.size());
1073
1074 void **Args = TemplateArgsIn.getArgs();
1075 bool *ArgIsType = TemplateArgsIn.getArgIsType();
1076 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
1077 TemplateArgs.push_back(
1078 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001079 //FIXME: Preserve type source info.
1080 Sema::GetTypeFromParser(Args[Arg]))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001081 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
1082 }
1083}
1084
Douglas Gregordc572a32009-03-30 22:58:21 +00001085QualType Sema::CheckTemplateIdType(TemplateName Name,
1086 SourceLocation TemplateLoc,
1087 SourceLocation LAngleLoc,
1088 const TemplateArgument *TemplateArgs,
1089 unsigned NumTemplateArgs,
1090 SourceLocation RAngleLoc) {
1091 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001092 if (!Template) {
1093 // The template name does not resolve to a template, so we just
1094 // build a dependent template-id type.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001095 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001096 NumTemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001097 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001098
Douglas Gregorc40290e2009-03-09 23:48:35 +00001099 // Check that the template argument list is well-formed for this
1100 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001101 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1102 NumTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001103 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001104 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001105 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001106 return QualType();
1107
Mike Stump11289f42009-09-09 15:08:12 +00001108 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001109 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001110 "Converted template argument list is too short!");
1111
1112 QualType CanonType;
1113
Douglas Gregordc572a32009-03-30 22:58:21 +00001114 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorc40290e2009-03-09 23:48:35 +00001115 TemplateArgs,
1116 NumTemplateArgs)) {
1117 // This class template specialization is a dependent
1118 // type. Therefore, its canonical type is another class template
1119 // specialization type that contains all of the converted
1120 // arguments in canonical form. This ensures that, e.g., A<T> and
1121 // A<T, T> have identical types when A is declared as:
1122 //
1123 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001124 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001125 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001126 Converted.getFlatArguments(),
1127 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001128
Douglas Gregora8e02e72009-07-28 23:00:59 +00001129 // FIXME: CanonType is not actually the canonical type, and unfortunately
1130 // it is a TemplateTypeSpecializationType that we will never use again.
1131 // In the future, we need to teach getTemplateSpecializationType to only
1132 // build the canonical type and return that to us.
1133 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001134 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001135 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001136 // Find the class template specialization declaration that
1137 // corresponds to these arguments.
1138 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001139 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001140 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001141 Converted.flatSize(),
1142 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001143 void *InsertPos = 0;
1144 ClassTemplateSpecializationDecl *Decl
1145 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1146 if (!Decl) {
1147 // This is the first time we have referenced this class template
1148 // specialization. Create the canonical declaration and add it to
1149 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001150 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001151 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001152 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001153 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001154 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001155 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1156 Decl->setLexicalDeclContext(CurContext);
1157 }
1158
1159 CanonType = Context.getTypeDeclType(Decl);
1160 }
Mike Stump11289f42009-09-09 15:08:12 +00001161
Douglas Gregorc40290e2009-03-09 23:48:35 +00001162 // Build the fully-sugared type for this class template
1163 // specialization, which refers back to the class template
1164 // specialization we created or found.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001165 //FIXME: Preserve type source info.
Douglas Gregordc572a32009-03-30 22:58:21 +00001166 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1167 NumTemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001168}
1169
Douglas Gregor67a65642009-02-17 23:15:12 +00001170Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001171Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001172 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001173 ASTTemplateArgsPtr TemplateArgsIn,
1174 SourceLocation *TemplateArgLocs,
John McCalld8fe9af2009-09-08 17:47:29 +00001175 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001176 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001177
Douglas Gregorc40290e2009-03-09 23:48:35 +00001178 // Translate the parser's template argument list in our AST format.
1179 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1180 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001181
Douglas Gregordc572a32009-03-30 22:58:21 +00001182 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +00001183 TemplateArgs.data(),
1184 TemplateArgs.size(),
Douglas Gregordc572a32009-03-30 22:58:21 +00001185 RAngleLoc);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001186 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001187
1188 if (Result.isNull())
1189 return true;
1190
John McCalld8fe9af2009-09-08 17:47:29 +00001191 return Result.getAsOpaquePtr();
1192}
John McCall06f6fe8d2009-09-04 01:14:41 +00001193
John McCalld8fe9af2009-09-08 17:47:29 +00001194Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1195 TagUseKind TUK,
1196 DeclSpec::TST TagSpec,
1197 SourceLocation TagLoc) {
1198 if (TypeResult.isInvalid())
1199 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001200
John McCalld8fe9af2009-09-08 17:47:29 +00001201 QualType Type = QualType::getFromOpaquePtr(TypeResult.get());
John McCall06f6fe8d2009-09-04 01:14:41 +00001202
John McCalld8fe9af2009-09-08 17:47:29 +00001203 // Verify the tag specifier.
1204 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001205
John McCalld8fe9af2009-09-08 17:47:29 +00001206 if (const RecordType *RT = Type->getAs<RecordType>()) {
1207 RecordDecl *D = RT->getDecl();
1208
1209 IdentifierInfo *Id = D->getIdentifier();
1210 assert(Id && "templated class must have an identifier");
1211
1212 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1213 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001214 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001215 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1216 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001217 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001218 }
1219 }
1220
John McCalld8fe9af2009-09-08 17:47:29 +00001221 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1222
1223 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001224}
1225
Douglas Gregora727cb92009-06-30 22:34:41 +00001226Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1227 SourceLocation TemplateNameLoc,
1228 SourceLocation LAngleLoc,
1229 const TemplateArgument *TemplateArgs,
1230 unsigned NumTemplateArgs,
1231 SourceLocation RAngleLoc) {
1232 // FIXME: Can we do any checking at this point? I guess we could check the
1233 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001234 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001235 // though.
Mike Stump11289f42009-09-09 15:08:12 +00001236 return Owned(TemplateIdRefExpr::Create(Context,
Douglas Gregora727cb92009-06-30 22:34:41 +00001237 /*FIXME: New type?*/Context.OverloadTy,
1238 /*FIXME: Necessary?*/0,
1239 /*FIXME: Necessary?*/SourceRange(),
1240 Template, TemplateNameLoc, LAngleLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001241 TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001242 NumTemplateArgs, RAngleLoc));
1243}
1244
1245Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1246 SourceLocation TemplateNameLoc,
1247 SourceLocation LAngleLoc,
1248 ASTTemplateArgsPtr TemplateArgsIn,
1249 SourceLocation *TemplateArgLocs,
1250 SourceLocation RAngleLoc) {
1251 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001252
Douglas Gregora727cb92009-06-30 22:34:41 +00001253 // Translate the parser's template argument list in our AST format.
1254 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1255 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001256 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001257
Douglas Gregora727cb92009-06-30 22:34:41 +00001258 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1259 TemplateArgs.data(), TemplateArgs.size(),
1260 RAngleLoc);
1261}
1262
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001263Sema::OwningExprResult
1264Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base,
1265 SourceLocation OpLoc,
1266 tok::TokenKind OpKind,
1267 const CXXScopeSpec &SS,
1268 TemplateTy TemplateD,
1269 SourceLocation TemplateNameLoc,
1270 SourceLocation LAngleLoc,
1271 ASTTemplateArgsPtr TemplateArgsIn,
1272 SourceLocation *TemplateArgLocs,
1273 SourceLocation RAngleLoc) {
1274 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001275
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001276 // FIXME: We're going to end up looking up the template based on its name,
1277 // twice!
1278 DeclarationName Name;
1279 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
1280 Name = ActualTemplate->getDeclName();
1281 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
1282 Name = Ovl->getDeclName();
1283 else
Douglas Gregor308047d2009-09-09 00:23:06 +00001284 Name = Template.getAsDependentTemplateName()->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001285
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001286 // Translate the parser's template argument list in our AST format.
1287 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1288 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1289 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001290
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001291 // Do we have the save the actual template name? We might need it...
1292 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc,
1293 Name, true, LAngleLoc,
1294 TemplateArgs.data(), TemplateArgs.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001295 RAngleLoc, DeclPtrTy(), &SS);
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001296}
1297
Douglas Gregorb67535d2009-03-31 00:43:58 +00001298/// \brief Form a dependent template name.
1299///
1300/// This action forms a dependent template name given the template
1301/// name and its (presumably dependent) scope specifier. For
1302/// example, given "MetaFun::template apply", the scope specifier \p
1303/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1304/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001305Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001306Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1307 const IdentifierInfo &Name,
1308 SourceLocation NameLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001309 const CXXScopeSpec &SS,
1310 TypeTy *ObjectType) {
Mike Stump11289f42009-09-09 15:08:12 +00001311 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001312 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1313 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001314 // C++0x [temp.names]p5:
1315 // If a name prefixed by the keyword template is not the name of
1316 // a template, the program is ill-formed. [Note: the keyword
1317 // template may not be applied to non-template members of class
1318 // templates. -end note ] [ Note: as is the case with the
1319 // typename prefix, the template prefix is allowed in cases
1320 // where it is not strictly necessary; i.e., when the
1321 // nested-name-specifier or the expression on the left of the ->
1322 // or . is not dependent on a template-parameter, or the use
1323 // does not appear in the scope of a template. -end note]
1324 //
1325 // Note: C++03 was more strict here, because it banned the use of
1326 // the "template" keyword prior to a template-name that was not a
1327 // dependent name. C++ DR468 relaxed this requirement (the
1328 // "template" keyword is now permitted). We follow the C++0x
1329 // rules, even in C++03 mode, retroactively applying the DR.
1330 TemplateTy Template;
Mike Stump11289f42009-09-09 15:08:12 +00001331 TemplateNameKind TNK = isTemplateName(0, Name, NameLoc, &SS, ObjectType,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001332 false, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001333 if (TNK == TNK_Non_template) {
1334 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1335 << &Name;
1336 return TemplateTy();
1337 }
1338
1339 return Template;
1340 }
1341
Mike Stump11289f42009-09-09 15:08:12 +00001342 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001343 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorb67535d2009-03-31 00:43:58 +00001344 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1345}
1346
Mike Stump11289f42009-09-09 15:08:12 +00001347bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001348 const TemplateArgument &Arg,
1349 TemplateArgumentListBuilder &Converted) {
1350 // Check template type parameter.
1351 if (Arg.getKind() != TemplateArgument::Type) {
1352 // C++ [temp.arg.type]p1:
1353 // A template-argument for a template-parameter which is a
1354 // type shall be a type-id.
1355
1356 // We have a template type parameter but the template argument
1357 // is not a type.
1358 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1359 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001360
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001361 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001362 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001363
1364 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1365 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001366
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001367 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001368 Converted.Append(
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001369 TemplateArgument(Arg.getLocation(),
1370 Context.getCanonicalType(Arg.getAsType())));
1371 return false;
1372}
1373
Douglas Gregord32e0282009-02-09 23:23:08 +00001374/// \brief Check that the given template argument list is well-formed
1375/// for specializing the given template.
1376bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1377 SourceLocation TemplateLoc,
1378 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001379 const TemplateArgument *TemplateArgs,
1380 unsigned NumTemplateArgs,
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001381 SourceLocation RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001382 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001383 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001384 TemplateParameterList *Params = Template->getTemplateParameters();
1385 unsigned NumParams = Params->size();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001386 unsigned NumArgs = NumTemplateArgs;
Douglas Gregord32e0282009-02-09 23:23:08 +00001387 bool Invalid = false;
1388
Mike Stump11289f42009-09-09 15:08:12 +00001389 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001390 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001391
Anders Carlsson15201f12009-06-13 02:08:00 +00001392 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001393 (NumArgs < Params->getMinRequiredArguments() &&
1394 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001395 // FIXME: point at either the first arg beyond what we can handle,
1396 // or the '>', depending on whether we have too many or too few
1397 // arguments.
1398 SourceRange Range;
1399 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001400 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001401 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1402 << (NumArgs > NumParams)
1403 << (isa<ClassTemplateDecl>(Template)? 0 :
1404 isa<FunctionTemplateDecl>(Template)? 1 :
1405 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1406 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001407 Diag(Template->getLocation(), diag::note_template_decl_here)
1408 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001409 Invalid = true;
1410 }
Mike Stump11289f42009-09-09 15:08:12 +00001411
1412 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001413 // [...] The type and form of each template-argument specified in
1414 // a template-id shall match the type and form specified for the
1415 // corresponding parameter declared by the template in its
1416 // template-parameter-list.
1417 unsigned ArgIdx = 0;
1418 for (TemplateParameterList::iterator Param = Params->begin(),
1419 ParamEnd = Params->end();
1420 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001421 if (ArgIdx > NumArgs && PartialTemplateArgs)
1422 break;
Mike Stump11289f42009-09-09 15:08:12 +00001423
Douglas Gregord32e0282009-02-09 23:23:08 +00001424 // Decode the template argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001425 TemplateArgument Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00001426 if (ArgIdx >= NumArgs) {
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001427 // Retrieve the default template argument from the template
1428 // parameter.
1429 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001430 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001431 // We have an empty argument pack.
1432 Converted.BeginPack();
1433 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001434 break;
1435 }
Mike Stump11289f42009-09-09 15:08:12 +00001436
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001437 if (!TTP->hasDefaultArgument())
1438 break;
1439
Douglas Gregorc40290e2009-03-09 23:48:35 +00001440 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001441
1442 // If the argument type is dependent, instantiate it now based
1443 // on the previously-computed template arguments.
Douglas Gregor79cf6032009-03-10 20:44:00 +00001444 if (ArgType->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001445 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001446 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001447 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001448 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregord002c7b2009-05-11 23:53:27 +00001449
Anders Carlssonc8e71132009-06-05 04:47:51 +00001450 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001451 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001452 ArgType = SubstType(ArgType,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001453 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001454 TTP->getDefaultArgumentLoc(),
1455 TTP->getDeclName());
Douglas Gregor79cf6032009-03-10 20:44:00 +00001456 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001457
1458 if (ArgType.isNull())
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001459 return true;
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001460
Douglas Gregorc40290e2009-03-09 23:48:35 +00001461 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001462 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001463 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1464 if (!NTTP->hasDefaultArgument())
1465 break;
1466
Mike Stump11289f42009-09-09 15:08:12 +00001467 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001468 Template, Converted.getFlatArguments(),
Anders Carlsson40ed3442009-06-11 16:06:49 +00001469 Converted.flatSize(),
1470 SourceRange(TemplateLoc, RAngleLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001471
Anders Carlsson40ed3442009-06-11 16:06:49 +00001472 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001473 /*TakeArgs=*/false);
Anders Carlsson40ed3442009-06-11 16:06:49 +00001474
Mike Stump11289f42009-09-09 15:08:12 +00001475 Sema::OwningExprResult E
1476 = SubstExpr(NTTP->getDefaultArgument(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00001477 MultiLevelTemplateArgumentList(TemplateArgs));
Anders Carlsson40ed3442009-06-11 16:06:49 +00001478 if (E.isInvalid())
1479 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001480
Anders Carlsson40ed3442009-06-11 16:06:49 +00001481 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001482 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001483 TemplateTemplateParmDecl *TempParm
1484 = cast<TemplateTemplateParmDecl>(*Param);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001485
1486 if (!TempParm->hasDefaultArgument())
1487 break;
1488
John McCall76d824f2009-08-25 22:02:44 +00001489 // FIXME: Subst default argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001490 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001491 }
1492 } else {
1493 // Retrieve the template argument produced by the user.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001494 Arg = TemplateArgs[ArgIdx];
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001495 }
1496
Douglas Gregord32e0282009-02-09 23:23:08 +00001497
1498 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001499 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001500 Converted.BeginPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001501 // Check all the remaining arguments (if any).
1502 for (; ArgIdx < NumArgs; ++ArgIdx) {
1503 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1504 Invalid = true;
1505 }
Mike Stump11289f42009-09-09 15:08:12 +00001506
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001507 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001508 } else {
1509 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1510 Invalid = true;
1511 }
Mike Stump11289f42009-09-09 15:08:12 +00001512 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord32e0282009-02-09 23:23:08 +00001513 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1514 // Check non-type template parameters.
Douglas Gregor463421d2009-03-03 04:44:36 +00001515
John McCall76d824f2009-08-25 22:02:44 +00001516 // Do substitution on the type of the non-type template parameter
1517 // with the template arguments we've seen thus far.
Douglas Gregor463421d2009-03-03 04:44:36 +00001518 QualType NTTPType = NTTP->getType();
1519 if (NTTPType->isDependentType()) {
John McCall76d824f2009-08-25 22:02:44 +00001520 // Do substitution on the type of the non-type template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001521 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001522 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001523 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001524 SourceRange(TemplateLoc, RAngleLoc));
1525
Anders Carlssonc8e71132009-06-05 04:47:51 +00001526 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001527 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001528 NTTPType = SubstType(NTTPType,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00001529 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001530 NTTP->getLocation(),
1531 NTTP->getDeclName());
Douglas Gregor463421d2009-03-03 04:44:36 +00001532 // If that worked, check the non-type template parameter type
1533 // for validity.
1534 if (!NTTPType.isNull())
Mike Stump11289f42009-09-09 15:08:12 +00001535 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
Douglas Gregor463421d2009-03-03 04:44:36 +00001536 NTTP->getLocation());
Douglas Gregor463421d2009-03-03 04:44:36 +00001537 if (NTTPType.isNull()) {
1538 Invalid = true;
1539 break;
1540 }
1541 }
1542
Douglas Gregorc40290e2009-03-09 23:48:35 +00001543 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001544 case TemplateArgument::Null:
1545 assert(false && "Should never see a NULL template argument here");
1546 break;
Mike Stump11289f42009-09-09 15:08:12 +00001547
Douglas Gregorc40290e2009-03-09 23:48:35 +00001548 case TemplateArgument::Expression: {
1549 Expr *E = Arg.getAsExpr();
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001550 TemplateArgument Result;
1551 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregord32e0282009-02-09 23:23:08 +00001552 Invalid = true;
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001553 else
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001554 Converted.Append(Result);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001555 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001556 }
1557
Douglas Gregorc40290e2009-03-09 23:48:35 +00001558 case TemplateArgument::Declaration:
1559 case TemplateArgument::Integral:
1560 // We've already checked this template argument, so just copy
1561 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001562 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001563 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001564
Douglas Gregorc40290e2009-03-09 23:48:35 +00001565 case TemplateArgument::Type:
1566 // We have a non-type template parameter but the template
1567 // argument is a type.
Mike Stump11289f42009-09-09 15:08:12 +00001568
Douglas Gregorc40290e2009-03-09 23:48:35 +00001569 // C++ [temp.arg]p2:
1570 // In a template-argument, an ambiguity between a type-id and
1571 // an expression is resolved to a type-id, regardless of the
1572 // form of the corresponding template-parameter.
1573 //
1574 // We warn specifically about this case, since it can be rather
1575 // confusing for users.
1576 if (Arg.getAsType()->isFunctionType())
1577 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1578 << Arg.getAsType();
1579 else
1580 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1581 Diag((*Param)->getLocation(), diag::note_template_param_here);
1582 Invalid = true;
Anders Carlssonbc343912009-06-15 17:04:53 +00001583 break;
Mike Stump11289f42009-09-09 15:08:12 +00001584
Anders Carlssonbc343912009-06-15 17:04:53 +00001585 case TemplateArgument::Pack:
1586 assert(0 && "FIXME: Implement!");
1587 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001588 }
Mike Stump11289f42009-09-09 15:08:12 +00001589 } else {
Douglas Gregord32e0282009-02-09 23:23:08 +00001590 // Check template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001591 TemplateTemplateParmDecl *TempParm
Douglas Gregord32e0282009-02-09 23:23:08 +00001592 = cast<TemplateTemplateParmDecl>(*Param);
Mike Stump11289f42009-09-09 15:08:12 +00001593
Douglas Gregorc40290e2009-03-09 23:48:35 +00001594 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001595 case TemplateArgument::Null:
1596 assert(false && "Should never see a NULL template argument here");
1597 break;
Mike Stump11289f42009-09-09 15:08:12 +00001598
Douglas Gregorc40290e2009-03-09 23:48:35 +00001599 case TemplateArgument::Expression: {
1600 Expr *ArgExpr = Arg.getAsExpr();
1601 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1602 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1603 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1604 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001605
Douglas Gregorc40290e2009-03-09 23:48:35 +00001606 // Add the converted template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001607 Decl *D
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00001608 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001609 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorc40290e2009-03-09 23:48:35 +00001610 continue;
1611 }
1612 }
1613 // fall through
Mike Stump11289f42009-09-09 15:08:12 +00001614
Douglas Gregorc40290e2009-03-09 23:48:35 +00001615 case TemplateArgument::Type: {
1616 // We have a template template parameter but the template
1617 // argument does not refer to a template.
1618 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1619 Invalid = true;
1620 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001621 }
1622
Douglas Gregorc40290e2009-03-09 23:48:35 +00001623 case TemplateArgument::Declaration:
1624 // We've already checked this template argument, so just copy
1625 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001626 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001627 break;
Mike Stump11289f42009-09-09 15:08:12 +00001628
Douglas Gregorc40290e2009-03-09 23:48:35 +00001629 case TemplateArgument::Integral:
1630 assert(false && "Integral argument with template template parameter");
1631 break;
Mike Stump11289f42009-09-09 15:08:12 +00001632
Anders Carlssonbc343912009-06-15 17:04:53 +00001633 case TemplateArgument::Pack:
1634 assert(0 && "FIXME: Implement!");
1635 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001636 }
Douglas Gregord32e0282009-02-09 23:23:08 +00001637 }
1638 }
1639
1640 return Invalid;
1641}
1642
1643/// \brief Check a template argument against its corresponding
1644/// template type parameter.
1645///
1646/// This routine implements the semantics of C++ [temp.arg.type]. It
1647/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001648bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
Douglas Gregord32e0282009-02-09 23:23:08 +00001649 QualType Arg, SourceLocation ArgLoc) {
1650 // C++ [temp.arg.type]p2:
1651 // A local type, a type with no linkage, an unnamed type or a type
1652 // compounded from any of these types shall not be used as a
1653 // template-argument for a template type-parameter.
1654 //
1655 // FIXME: Perform the recursive and no-linkage type checks.
1656 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001657 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001658 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001659 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001660 Tag = RecordT;
1661 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1662 return Diag(ArgLoc, diag::err_template_arg_local_type)
1663 << QualType(Tag, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001664 else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001665 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001666 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1667 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1668 return true;
1669 }
1670
1671 return false;
1672}
1673
Douglas Gregorccb07762009-02-11 19:52:55 +00001674/// \brief Checks whether the given template argument is the address
1675/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001676bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1677 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001678 bool Invalid = false;
1679
1680 // See through any implicit casts we added to fix the type.
1681 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1682 Arg = Cast->getSubExpr();
1683
Sebastian Redl576fd422009-05-10 18:38:11 +00001684 // C++0x allows nullptr, and there's no further checking to be done for that.
1685 if (Arg->getType()->isNullPtrType())
1686 return false;
1687
Douglas Gregorccb07762009-02-11 19:52:55 +00001688 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001689 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001690 // A template-argument for a non-type, non-template
1691 // template-parameter shall be one of: [...]
1692 //
1693 // -- the address of an object or function with external
1694 // linkage, including function templates and function
1695 // template-ids but excluding non-static class members,
1696 // expressed as & id-expression where the & is optional if
1697 // the name refers to a function or array, or if the
1698 // corresponding template-parameter is a reference; or
1699 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001700
Douglas Gregorccb07762009-02-11 19:52:55 +00001701 // Ignore (and complain about) any excess parentheses.
1702 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1703 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001704 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001705 diag::err_template_arg_extra_parens)
1706 << Arg->getSourceRange();
1707 Invalid = true;
1708 }
1709
1710 Arg = Parens->getSubExpr();
1711 }
1712
1713 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1714 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1715 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1716 } else
1717 DRE = dyn_cast<DeclRefExpr>(Arg);
1718
1719 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00001720 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001721 diag::err_template_arg_not_object_or_func_form)
1722 << Arg->getSourceRange();
1723
1724 // Cannot refer to non-static data members
1725 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1726 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1727 << Field << Arg->getSourceRange();
1728
1729 // Cannot refer to non-static member functions
1730 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1731 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00001732 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001733 diag::err_template_arg_method)
1734 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001735
Douglas Gregorccb07762009-02-11 19:52:55 +00001736 // Functions must have external linkage.
1737 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1738 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00001739 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001740 diag::err_template_arg_function_not_extern)
1741 << Func << Arg->getSourceRange();
1742 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1743 << true;
1744 return true;
1745 }
1746
1747 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001748 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00001749 return Invalid;
1750 }
1751
1752 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1753 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00001754 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001755 diag::err_template_arg_object_not_extern)
1756 << Var << Arg->getSourceRange();
1757 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1758 << true;
1759 return true;
1760 }
1761
1762 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001763 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00001764 return Invalid;
1765 }
Mike Stump11289f42009-09-09 15:08:12 +00001766
Douglas Gregorccb07762009-02-11 19:52:55 +00001767 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001768 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001769 diag::err_template_arg_not_object_or_func)
1770 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001771 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001772 diag::note_template_arg_refers_here);
1773 return true;
1774}
1775
1776/// \brief Checks whether the given template argument is a pointer to
1777/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump11289f42009-09-09 15:08:12 +00001778bool
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001779Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001780 bool Invalid = false;
1781
1782 // See through any implicit casts we added to fix the type.
1783 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1784 Arg = Cast->getSubExpr();
1785
Sebastian Redl576fd422009-05-10 18:38:11 +00001786 // C++0x allows nullptr, and there's no further checking to be done for that.
1787 if (Arg->getType()->isNullPtrType())
1788 return false;
1789
Douglas Gregorccb07762009-02-11 19:52:55 +00001790 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001791 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001792 // A template-argument for a non-type, non-template
1793 // template-parameter shall be one of: [...]
1794 //
1795 // -- a pointer to member expressed as described in 5.3.1.
1796 QualifiedDeclRefExpr *DRE = 0;
1797
1798 // Ignore (and complain about) any excess parentheses.
1799 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1800 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001801 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001802 diag::err_template_arg_extra_parens)
1803 << Arg->getSourceRange();
1804 Invalid = true;
1805 }
1806
1807 Arg = Parens->getSubExpr();
1808 }
1809
1810 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1811 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1812 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1813
1814 if (!DRE)
1815 return Diag(Arg->getSourceRange().getBegin(),
1816 diag::err_template_arg_not_pointer_to_member_form)
1817 << Arg->getSourceRange();
1818
1819 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1820 assert((isa<FieldDecl>(DRE->getDecl()) ||
1821 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1822 "Only non-static member pointers can make it here");
1823
1824 // Okay: this is the address of a non-static member, and therefore
1825 // a member pointer constant.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001826 Member = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00001827 return Invalid;
1828 }
1829
1830 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001831 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001832 diag::err_template_arg_not_pointer_to_member_form)
1833 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001834 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001835 diag::note_template_arg_refers_here);
1836 return true;
1837}
1838
Douglas Gregord32e0282009-02-09 23:23:08 +00001839/// \brief Check a template argument against its corresponding
1840/// non-type template parameter.
1841///
Douglas Gregor463421d2009-03-03 04:44:36 +00001842/// This routine implements the semantics of C++ [temp.arg.nontype].
1843/// It returns true if an error occurred, and false otherwise. \p
1844/// InstantiatedParamType is the type of the non-type template
1845/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001846///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001847/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00001848bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00001849 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001850 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001851 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1852
Douglas Gregor86560402009-02-10 23:36:10 +00001853 // If either the parameter has a dependent type or the argument is
1854 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001855 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00001856 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1857 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001858 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00001859 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001860 }
Douglas Gregor86560402009-02-10 23:36:10 +00001861
1862 // C++ [temp.arg.nontype]p5:
1863 // The following conversions are performed on each expression used
1864 // as a non-type template-argument. If a non-type
1865 // template-argument cannot be converted to the type of the
1866 // corresponding template-parameter then the program is
1867 // ill-formed.
1868 //
1869 // -- for a non-type template-parameter of integral or
1870 // enumeration type, integral promotions (4.5) and integral
1871 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00001872 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001873 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00001874 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00001875 // C++ [temp.arg.nontype]p1:
1876 // A template-argument for a non-type, non-template
1877 // template-parameter shall be one of:
1878 //
1879 // -- an integral constant-expression of integral or enumeration
1880 // type; or
1881 // -- the name of a non-type template-parameter; or
1882 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001883 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00001884 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001885 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001886 diag::err_template_arg_not_integral_or_enumeral)
1887 << ArgType << Arg->getSourceRange();
1888 Diag(Param->getLocation(), diag::note_template_param_here);
1889 return true;
1890 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001891 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00001892 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1893 << ArgType << Arg->getSourceRange();
1894 return true;
1895 }
1896
1897 // FIXME: We need some way to more easily get the unqualified form
1898 // of the types without going all the way to the
1899 // canonical type.
1900 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1901 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1902 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1903 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1904
1905 // Try to convert the argument to the parameter's type.
1906 if (ParamType == ArgType) {
1907 // Okay: no conversion necessary
1908 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1909 !ParamType->isEnumeralType()) {
1910 // This is an integral promotion or conversion.
1911 ImpCastExprToType(Arg, ParamType);
1912 } else {
1913 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00001914 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001915 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00001916 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00001917 Diag(Param->getLocation(), diag::note_template_param_here);
1918 return true;
1919 }
1920
Douglas Gregor52aba872009-03-14 00:20:21 +00001921 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00001922 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001923 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00001924
1925 if (!Arg->isValueDependent()) {
1926 // Check that an unsigned parameter does not receive a negative
1927 // value.
1928 if (IntegerType->isUnsignedIntegerType()
1929 && (Value.isSigned() && Value.isNegative())) {
1930 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1931 << Value.toString(10) << Param->getType()
1932 << Arg->getSourceRange();
1933 Diag(Param->getLocation(), diag::note_template_param_here);
1934 return true;
1935 }
1936
1937 // Check that we don't overflow the template parameter type.
1938 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1939 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00001940 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00001941 diag::err_template_arg_too_large)
1942 << Value.toString(10) << Param->getType()
1943 << Arg->getSourceRange();
1944 Diag(Param->getLocation(), diag::note_template_param_here);
1945 return true;
1946 }
1947
1948 if (Value.getBitWidth() != AllowedBits)
1949 Value.extOrTrunc(AllowedBits);
1950 Value.setIsSigned(IntegerType->isSignedIntegerType());
1951 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001952
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001953 // Add the value of this argument to the list of converted
1954 // arguments. We use the bitwidth and signedness of the template
1955 // parameter.
1956 if (Arg->isValueDependent()) {
1957 // The argument is value-dependent. Create a new
1958 // TemplateArgument with the converted expression.
1959 Converted = TemplateArgument(Arg);
1960 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001961 }
1962
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001963 Converted = TemplateArgument(StartLoc, Value,
Mike Stump11289f42009-09-09 15:08:12 +00001964 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001965 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00001966 return false;
1967 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001968
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001969 // Handle pointer-to-function, reference-to-function, and
1970 // pointer-to-member-function all in (roughly) the same way.
1971 if (// -- For a non-type template-parameter of type pointer to
1972 // function, only the function-to-pointer conversion (4.3) is
1973 // applied. If the template-argument represents a set of
1974 // overloaded functions (or a pointer to such), the matching
1975 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00001976 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001977 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001978 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001979 // -- For a non-type template-parameter of type reference to
1980 // function, no conversions apply. If the template-argument
1981 // represents a set of overloaded functions, the matching
1982 // function is selected from the set (13.4).
1983 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001984 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001985 // -- For a non-type template-parameter of type pointer to
1986 // member function, no conversions apply. If the
1987 // template-argument represents a set of overloaded member
1988 // functions, the matching member function is selected from
1989 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00001990 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001991 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001992 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001993 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00001994 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00001995 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001996 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00001997 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1998 ParamType->isMemberPointerType())) {
1999 ArgType = ParamType;
2000 ImpCastExprToType(Arg, ParamType);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002001 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002002 ArgType = Context.getPointerType(ArgType);
2003 ImpCastExprToType(Arg, ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00002004 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002005 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002006 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2007 return true;
2008
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002009 FixOverloadedFunctionReference(Arg, Fn);
2010 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002011 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002012 ArgType = Context.getPointerType(Arg->getType());
2013 ImpCastExprToType(Arg, ArgType);
2014 }
2015 }
2016
Mike Stump11289f42009-09-09 15:08:12 +00002017 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002018 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002019 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002020 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002021 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002022 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002023 Diag(Param->getLocation(), diag::note_template_param_here);
2024 return true;
2025 }
Mike Stump11289f42009-09-09 15:08:12 +00002026
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002027 if (ParamType->isMemberPointerType()) {
2028 NamedDecl *Member = 0;
2029 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2030 return true;
2031
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002032 if (Member)
2033 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002034 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002035 return false;
2036 }
Mike Stump11289f42009-09-09 15:08:12 +00002037
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002038 NamedDecl *Entity = 0;
2039 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2040 return true;
2041
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002042 if (Entity)
2043 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002044 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002045 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002046 }
2047
Chris Lattner696197c2009-02-20 21:37:53 +00002048 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002049 // -- for a non-type template-parameter of type pointer to
2050 // object, qualification conversions (4.4) and the
2051 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002052 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002053 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002054 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002055
Sebastian Redl576fd422009-05-10 18:38:11 +00002056 if (ArgType->isNullPtrType()) {
2057 ArgType = ParamType;
2058 ImpCastExprToType(Arg, ParamType);
2059 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002060 ArgType = Context.getArrayDecayedType(ArgType);
2061 ImpCastExprToType(Arg, ArgType);
Douglas Gregora9faa442009-02-11 00:44:29 +00002062 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002063
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002064 if (IsQualificationConversion(ArgType, ParamType)) {
2065 ArgType = ParamType;
2066 ImpCastExprToType(Arg, ParamType);
2067 }
Mike Stump11289f42009-09-09 15:08:12 +00002068
Douglas Gregor1515f762009-02-11 18:22:40 +00002069 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002070 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002071 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002072 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002073 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002074 Diag(Param->getLocation(), diag::note_template_param_here);
2075 return true;
2076 }
Mike Stump11289f42009-09-09 15:08:12 +00002077
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002078 NamedDecl *Entity = 0;
2079 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2080 return true;
2081
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002082 if (Entity)
2083 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002084 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002085 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002086 }
Mike Stump11289f42009-09-09 15:08:12 +00002087
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002088 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002089 // -- For a non-type template-parameter of type reference to
2090 // object, no conversions apply. The type referred to by the
2091 // reference may be more cv-qualified than the (otherwise
2092 // identical) type of the template-argument. The
2093 // template-parameter is bound directly to the
2094 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002095 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002096 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002097
Douglas Gregor1515f762009-02-11 18:22:40 +00002098 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002099 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002100 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002101 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002102 << Arg->getSourceRange();
2103 Diag(Param->getLocation(), diag::note_template_param_here);
2104 return true;
2105 }
2106
Mike Stump11289f42009-09-09 15:08:12 +00002107 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002108 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2109 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002110
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002111 if ((ParamQuals | ArgQuals) != ParamQuals) {
2112 Diag(Arg->getSourceRange().getBegin(),
2113 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002114 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002115 << Arg->getSourceRange();
2116 Diag(Param->getLocation(), diag::note_template_param_here);
2117 return true;
2118 }
Mike Stump11289f42009-09-09 15:08:12 +00002119
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002120 NamedDecl *Entity = 0;
2121 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2122 return true;
2123
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002124 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002125 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002126 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002127 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002128
2129 // -- For a non-type template-parameter of type pointer to data
2130 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002131 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002132 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2133
Douglas Gregor1515f762009-02-11 18:22:40 +00002134 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002135 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002136 } else if (ArgType->isNullPtrType()) {
2137 ImpCastExprToType(Arg, ParamType);
Douglas Gregor0e558532009-02-11 16:16:59 +00002138 } else if (IsQualificationConversion(ArgType, ParamType)) {
2139 ImpCastExprToType(Arg, ParamType);
2140 } else {
2141 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002142 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002143 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002144 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002145 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002146 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002147 }
2148
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002149 NamedDecl *Member = 0;
2150 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2151 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002152
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002153 if (Member)
2154 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002155 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002156 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00002157}
2158
2159/// \brief Check a template argument against its corresponding
2160/// template template parameter.
2161///
2162/// This routine implements the semantics of C++ [temp.arg.template].
2163/// It returns true if an error occurred, and false otherwise.
2164bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2165 DeclRefExpr *Arg) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002166 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2167 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2168
2169 // C++ [temp.arg.template]p1:
2170 // A template-argument for a template template-parameter shall be
2171 // the name of a class template, expressed as id-expression. Only
2172 // primary class templates are considered when matching the
2173 // template template argument with the corresponding parameter;
2174 // partial specializations are not considered even if their
2175 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002176 //
2177 // Note that we also allow template template parameters here, which
2178 // will happen when we are dealing with, e.g., class template
2179 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002180 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002181 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002182 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002183 "Only function templates are possible here");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002184 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2185 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002186 << Template;
2187 }
2188
2189 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2190 Param->getTemplateParameters(),
2191 true, true,
2192 Arg->getSourceRange().getBegin());
Douglas Gregord32e0282009-02-09 23:23:08 +00002193}
2194
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002195/// \brief Determine whether the given template parameter lists are
2196/// equivalent.
2197///
Mike Stump11289f42009-09-09 15:08:12 +00002198/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002199/// source code as part of a new template declaration.
2200///
2201/// \param Old The old template parameter list, typically found via
2202/// name lookup of the template declared with this template parameter
2203/// list.
2204///
2205/// \param Complain If true, this routine will produce a diagnostic if
2206/// the template parameter lists are not equivalent.
2207///
Douglas Gregor85e0f662009-02-10 00:24:35 +00002208/// \param IsTemplateTemplateParm If true, this routine is being
2209/// called to compare the template parameter lists of a template
2210/// template parameter.
2211///
2212/// \param TemplateArgLoc If this source location is valid, then we
2213/// are actually checking the template parameter list of a template
2214/// argument (New) against the template parameter list of its
2215/// corresponding template template parameter (Old). We produce
2216/// slightly different diagnostics in this scenario.
2217///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002218/// \returns True if the template parameter lists are equal, false
2219/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002220bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002221Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2222 TemplateParameterList *Old,
2223 bool Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002224 bool IsTemplateTemplateParm,
2225 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002226 if (Old->size() != New->size()) {
2227 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002228 unsigned NextDiag = diag::err_template_param_list_different_arity;
2229 if (TemplateArgLoc.isValid()) {
2230 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2231 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002232 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002233 Diag(New->getTemplateLoc(), NextDiag)
2234 << (New->size() > Old->size())
2235 << IsTemplateTemplateParm
2236 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002237 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2238 << IsTemplateTemplateParm
2239 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2240 }
2241
2242 return false;
2243 }
2244
2245 for (TemplateParameterList::iterator OldParm = Old->begin(),
2246 OldParmEnd = Old->end(), NewParm = New->begin();
2247 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2248 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002249 if (Complain) {
2250 unsigned NextDiag = diag::err_template_param_different_kind;
2251 if (TemplateArgLoc.isValid()) {
2252 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2253 NextDiag = diag::note_template_param_different_kind;
2254 }
2255 Diag((*NewParm)->getLocation(), NextDiag)
2256 << IsTemplateTemplateParm;
2257 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2258 << IsTemplateTemplateParm;
Douglas Gregor85e0f662009-02-10 00:24:35 +00002259 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002260 return false;
2261 }
2262
2263 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2264 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002265 // know we're at the same index).
2266#if 0
Mike Stump87c57ac2009-05-16 07:39:55 +00002267 // FIXME: Enable this code in debug mode *after* we properly go through
2268 // and "instantiate" the template parameter lists of template template
2269 // parameters. It's only after this instantiation that (1) any dependent
2270 // types within the template parameter list of the template template
2271 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregor85e0f662009-02-10 00:24:35 +00002272 // will match up.
Mike Stump11289f42009-09-09 15:08:12 +00002273 QualType OldParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002274 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
Mike Stump11289f42009-09-09 15:08:12 +00002275 QualType NewParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002276 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
Mike Stump11289f42009-09-09 15:08:12 +00002277 assert(Context.getCanonicalType(OldParmType) ==
2278 Context.getCanonicalType(NewParmType) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002279 "type parameter mismatch?");
2280#endif
Mike Stump11289f42009-09-09 15:08:12 +00002281 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002282 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2283 // The types of non-type template parameters must agree.
2284 NonTypeTemplateParmDecl *NewNTTP
2285 = cast<NonTypeTemplateParmDecl>(*NewParm);
2286 if (Context.getCanonicalType(OldNTTP->getType()) !=
2287 Context.getCanonicalType(NewNTTP->getType())) {
2288 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002289 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2290 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002291 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002292 diag::err_template_arg_template_params_mismatch);
2293 NextDiag = diag::note_template_nontype_parm_different_type;
2294 }
2295 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002296 << NewNTTP->getType()
2297 << IsTemplateTemplateParm;
Mike Stump11289f42009-09-09 15:08:12 +00002298 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002299 diag::note_template_nontype_parm_prev_declaration)
2300 << OldNTTP->getType();
2301 }
2302 return false;
2303 }
2304 } else {
2305 // The template parameter lists of template template
2306 // parameters must agree.
2307 // FIXME: Could we perform a faster "type" comparison here?
Mike Stump11289f42009-09-09 15:08:12 +00002308 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002309 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002310 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002311 = cast<TemplateTemplateParmDecl>(*OldParm);
2312 TemplateTemplateParmDecl *NewTTP
2313 = cast<TemplateTemplateParmDecl>(*NewParm);
2314 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2315 OldTTP->getTemplateParameters(),
2316 Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002317 /*IsTemplateTemplateParm=*/true,
2318 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002319 return false;
2320 }
2321 }
2322
2323 return true;
2324}
2325
2326/// \brief Check whether a template can be declared within this scope.
2327///
2328/// If the template declaration is valid in this scope, returns
2329/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002330bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002331Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002332 // Find the nearest enclosing declaration scope.
2333 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2334 (S->getFlags() & Scope::TemplateParamScope) != 0)
2335 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002336
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002337 // C++ [temp]p2:
2338 // A template-declaration can appear only as a namespace scope or
2339 // class scope declaration.
2340 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002341 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2342 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002343 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002344 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002345
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002346 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002347 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002348
2349 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2350 return false;
2351
Mike Stump11289f42009-09-09 15:08:12 +00002352 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002353 diag::err_template_outside_namespace_or_class_scope)
2354 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002355}
Douglas Gregor67a65642009-02-17 23:15:12 +00002356
Douglas Gregor54888652009-10-07 00:13:32 +00002357/// \brief Determine what kind of template specialization the given declaration
2358/// is.
2359static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2360 if (!D)
2361 return TSK_Undeclared;
2362
2363 if (ClassTemplateSpecializationDecl *CTS
2364 = dyn_cast<ClassTemplateSpecializationDecl>(D))
2365 return CTS->getSpecializationKind();
2366 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2367 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002368 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2369 return Var->getTemplateSpecializationKind();
2370
Douglas Gregor54888652009-10-07 00:13:32 +00002371 // FIXME: member classes of class templates!
2372 return TSK_Undeclared;
2373}
2374
2375/// \brief Check whether a specialization or explicit instantiation is
2376/// well-formed in the current context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002377///
Douglas Gregor54888652009-10-07 00:13:32 +00002378/// This routine determines whether a template specialization or
Mike Stump11289f42009-09-09 15:08:12 +00002379/// explicit instantiation can be declared in the current context
Douglas Gregor54888652009-10-07 00:13:32 +00002380/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2).
2381///
2382/// \param S the semantic analysis object for which this check is being
2383/// performed.
2384///
2385/// \param Specialized the entity being specialized or instantiated, which
2386/// may be a kind of template (class template, function template, etc.) or
2387/// a member of a class template (member function, static data member,
2388/// member class).
2389///
2390/// \param PrevDecl the previous declaration of this entity, if any.
2391///
2392/// \param Loc the location of the explicit specialization or instantiation of
2393/// this entity.
2394///
2395/// \param IsPartialSpecialization whether this is a partial specialization of
2396/// a class template.
2397///
2398/// \param TSK the kind of specialization or implicit instantiation being
2399/// performed.
2400///
2401/// \returns true if there was an error that we cannot recover from, false
2402/// otherwise.
2403static bool CheckTemplateSpecializationScope(Sema &S,
2404 NamedDecl *Specialized,
2405 NamedDecl *PrevDecl,
2406 SourceLocation Loc,
2407 bool IsPartialSpecialization,
2408 TemplateSpecializationKind TSK) {
2409 // Keep these "kind" numbers in sync with the %select statements in the
2410 // various diagnostics emitted by this routine.
2411 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002412 bool isTemplateSpecialization = false;
2413 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002414 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002415 isTemplateSpecialization = true;
2416 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002417 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002418 isTemplateSpecialization = true;
2419 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002420 EntityKind = 3;
2421 else if (isa<VarDecl>(Specialized))
2422 EntityKind = 4;
2423 else if (isa<RecordDecl>(Specialized))
2424 EntityKind = 5;
2425 else {
2426 S.Diag(Loc, diag::err_template_spec_unknown_kind) << TSK;
2427 S.Diag(Specialized->getLocation(), diag::note_specialized_entity) << TSK;
2428 return true;
2429 }
2430
Douglas Gregorf47b9112009-02-25 22:02:03 +00002431 // C++ [temp.expl.spec]p2:
2432 // An explicit specialization shall be declared in the namespace
2433 // of which the template is a member, or, for member templates, in
2434 // the namespace of which the enclosing class or enclosing class
2435 // template is a member. An explicit specialization of a member
2436 // function, member class or static data member of a class
2437 // template shall be declared in the namespace of which the class
2438 // template is a member. Such a declaration may also be a
2439 // definition. If the declaration is not a definition, the
2440 // specialization may be defined later in the name- space in which
2441 // the explicit specialization was declared, or in a namespace
2442 // that encloses the one in which the explicit specialization was
2443 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002444 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2445 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
2446 << TSK << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002447 return true;
2448 }
Douglas Gregore4b05162009-10-07 17:21:34 +00002449
Douglas Gregor40fb7442009-10-07 17:30:37 +00002450 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2451 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
2452 << TSK << Specialized;
2453 return true;
2454 }
2455
Douglas Gregore4b05162009-10-07 17:21:34 +00002456 // C++ [temp.class.spec]p6:
2457 // A class template partial specialization may be declared or redeclared
2458 // in any namespace scope in which its definition may be defined (14.5.1
2459 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002460 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002461 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002462 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002463 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor54888652009-10-07 00:13:32 +00002464 if (TSK == TSK_ExplicitSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002465 if ((!PrevDecl ||
2466 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2467 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2468 // There is no prior declaration of this entity, so this
2469 // specialization must be in the same context as the template
2470 // itself.
2471 if (!DC->Equals(SpecializedContext)) {
2472 if (isa<TranslationUnitDecl>(SpecializedContext))
2473 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2474 << EntityKind << Specialized;
2475 else if (isa<NamespaceDecl>(SpecializedContext))
2476 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2477 << EntityKind << Specialized
2478 << cast<NamedDecl>(SpecializedContext);
2479
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002480 S.Diag(Specialized->getLocation(), diag::note_specialized_entity)
2481 << TSK;
Douglas Gregor54888652009-10-07 00:13:32 +00002482 ComplainedAboutScope = true;
2483 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002484 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002485 }
Douglas Gregor54888652009-10-07 00:13:32 +00002486
2487 // Make sure that this redeclaration (or definition) occurs in an enclosing
2488 // namespace. We perform this check for explicit specializations and, in
2489 // C++0x, for explicit instantiations as well (per DR275).
2490 // FIXME: -Wc++0x should make these warnings.
2491 // Note that HandleDeclarator() performs this check for explicit
2492 // specializations of function templates, static data members, and member
2493 // functions, so we skip the check here for those kinds of entities.
2494 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00002495 // Should we refactor that check, so that it occurs later?
2496 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor54888652009-10-07 00:13:32 +00002497 ((TSK == TSK_ExplicitSpecialization &&
2498 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2499 isa<FunctionDecl>(Specialized))) ||
2500 S.getLangOptions().CPlusPlus0x)) {
2501 if (isa<TranslationUnitDecl>(SpecializedContext))
2502 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2503 << EntityKind << Specialized;
2504 else if (isa<NamespaceDecl>(SpecializedContext))
2505 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2506 << EntityKind << Specialized
2507 << cast<NamedDecl>(SpecializedContext);
2508
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002509 S.Diag(Specialized->getLocation(), diag::note_specialized_entity) << TSK;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002510 }
Douglas Gregor54888652009-10-07 00:13:32 +00002511
2512 // FIXME: check for specialization-after-instantiation errors and such.
2513
Douglas Gregorf47b9112009-02-25 22:02:03 +00002514 return false;
2515}
Douglas Gregor54888652009-10-07 00:13:32 +00002516
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002517/// \brief Check the non-type template arguments of a class template
2518/// partial specialization according to C++ [temp.class.spec]p9.
2519///
Douglas Gregor09a30232009-06-12 22:08:06 +00002520/// \param TemplateParams the template parameters of the primary class
2521/// template.
2522///
2523/// \param TemplateArg the template arguments of the class template
2524/// partial specialization.
2525///
2526/// \param MirrorsPrimaryTemplate will be set true if the class
2527/// template partial specialization arguments are identical to the
2528/// implicit template arguments of the primary template. This is not
2529/// necessarily an error (C++0x), and it is left to the caller to diagnose
2530/// this condition when it is an error.
2531///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002532/// \returns true if there was an error, false otherwise.
2533bool Sema::CheckClassTemplatePartialSpecializationArgs(
2534 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002535 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002536 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002537 // FIXME: the interface to this function will have to change to
2538 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002539 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002540
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002541 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002542
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002543 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002544 // Determine whether the template argument list of the partial
2545 // specialization is identical to the implicit argument list of
2546 // the primary template. The caller may need to diagnostic this as
2547 // an error per C++ [temp.class.spec]p9b3.
2548 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002549 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002550 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2551 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002552 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002553 MirrorsPrimaryTemplate = false;
2554 } else if (TemplateTemplateParmDecl *TTP
2555 = dyn_cast<TemplateTemplateParmDecl>(
2556 TemplateParams->getParam(I))) {
2557 // FIXME: We should settle on either Declaration storage or
2558 // Expression storage for template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002559 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor09a30232009-06-12 22:08:06 +00002560 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson40c1d492009-06-13 18:20:51 +00002561 ArgList[I].getAsDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002562 if (!ArgDecl)
Mike Stump11289f42009-09-09 15:08:12 +00002563 if (DeclRefExpr *DRE
Anders Carlsson40c1d492009-06-13 18:20:51 +00002564 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002565 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2566
2567 if (!ArgDecl ||
2568 ArgDecl->getIndex() != TTP->getIndex() ||
2569 ArgDecl->getDepth() != TTP->getDepth())
2570 MirrorsPrimaryTemplate = false;
2571 }
2572 }
2573
Mike Stump11289f42009-09-09 15:08:12 +00002574 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002575 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002576 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002577 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002578 }
2579
Anders Carlsson40c1d492009-06-13 18:20:51 +00002580 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002581 if (!ArgExpr) {
2582 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002583 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002584 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002585
2586 // C++ [temp.class.spec]p8:
2587 // A non-type argument is non-specialized if it is the name of a
2588 // non-type parameter. All other non-type arguments are
2589 // specialized.
2590 //
2591 // Below, we check the two conditions that only apply to
2592 // specialized non-type arguments, so skip any non-specialized
2593 // arguments.
2594 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002595 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002596 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002597 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002598 (Param->getIndex() != NTTP->getIndex() ||
2599 Param->getDepth() != NTTP->getDepth()))
2600 MirrorsPrimaryTemplate = false;
2601
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002602 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002603 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002604
2605 // C++ [temp.class.spec]p9:
2606 // Within the argument list of a class template partial
2607 // specialization, the following restrictions apply:
2608 // -- A partially specialized non-type argument expression
2609 // shall not involve a template parameter of the partial
2610 // specialization except when the argument expression is a
2611 // simple identifier.
2612 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002613 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002614 diag::err_dependent_non_type_arg_in_partial_spec)
2615 << ArgExpr->getSourceRange();
2616 return true;
2617 }
2618
2619 // -- The type of a template parameter corresponding to a
2620 // specialized non-type argument shall not be dependent on a
2621 // parameter of the specialization.
2622 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002623 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002624 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2625 << Param->getType()
2626 << ArgExpr->getSourceRange();
2627 Diag(Param->getLocation(), diag::note_template_param_here);
2628 return true;
2629 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002630
2631 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002632 }
2633
2634 return false;
2635}
2636
Douglas Gregorc08f4892009-03-25 00:13:59 +00002637Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002638Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2639 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002640 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002641 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002642 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002643 SourceLocation TemplateNameLoc,
2644 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002645 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002646 SourceLocation *TemplateArgLocs,
2647 SourceLocation RAngleLoc,
2648 AttributeList *Attr,
2649 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00002650 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00002651
Douglas Gregor67a65642009-02-17 23:15:12 +00002652 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002653 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002654 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002655 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002656
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002657 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00002658 bool isPartialSpecialization = false;
2659
Douglas Gregorf47b9112009-02-25 22:02:03 +00002660 // Check the validity of the template headers that introduce this
2661 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00002662 // FIXME: We probably shouldn't complain about these headers for
2663 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002664 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002665 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2666 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002667 TemplateParameterLists.size(),
2668 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002669 if (TemplateParams && TemplateParams->size() > 0) {
2670 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002671
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002672 // C++ [temp.class.spec]p10:
2673 // The template parameter list of a specialization shall not
2674 // contain default template argument values.
2675 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2676 Decl *Param = TemplateParams->getParam(I);
2677 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2678 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002679 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002680 diag::err_default_arg_in_partial_spec);
2681 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2682 }
2683 } else if (NonTypeTemplateParmDecl *NTTP
2684 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2685 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002686 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002687 diag::err_default_arg_in_partial_spec)
2688 << DefArg->getSourceRange();
2689 NTTP->setDefaultArgument(0);
2690 DefArg->Destroy(Context);
2691 }
2692 } else {
2693 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2694 if (Expr *DefArg = TTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002695 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002696 diag::err_default_arg_in_partial_spec)
2697 << DefArg->getSourceRange();
2698 TTP->setDefaultArgument(0);
2699 DefArg->Destroy(Context);
Douglas Gregord5222052009-06-12 19:43:02 +00002700 }
2701 }
2702 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002703 } else if (!TemplateParams && TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002704 Diag(KWLoc, diag::err_template_spec_needs_header)
2705 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002706 isExplicitSpecialization = true;
2707 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002708
Douglas Gregor67a65642009-02-17 23:15:12 +00002709 // Check that the specialization uses the same tag kind as the
2710 // original template.
2711 TagDecl::TagKind Kind;
2712 switch (TagSpec) {
2713 default: assert(0 && "Unknown tag type!");
2714 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2715 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2716 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2717 }
Douglas Gregord9034f02009-05-14 16:41:31 +00002718 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00002719 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00002720 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00002721 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00002722 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00002723 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00002724 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00002725 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00002726 diag::note_previous_use);
2727 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2728 }
2729
Douglas Gregorc40290e2009-03-09 23:48:35 +00002730 // Translate the parser's template argument list in our AST format.
2731 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2732 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2733
Douglas Gregor67a65642009-02-17 23:15:12 +00002734 // Check that the template argument list is well-formed for this
2735 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002736 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2737 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00002738 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002739 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00002740 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002741 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002742
Mike Stump11289f42009-09-09 15:08:12 +00002743 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00002744 ClassTemplate->getTemplateParameters()->size()) &&
2745 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00002746
Douglas Gregor2373c592009-05-31 09:31:02 +00002747 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00002748 // corresponds to these arguments.
2749 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00002750 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002751 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002752 if (CheckClassTemplatePartialSpecializationArgs(
2753 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002754 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002755 return true;
2756
Douglas Gregor09a30232009-06-12 22:08:06 +00002757 if (MirrorsPrimaryTemplate) {
2758 // C++ [temp.class.spec]p9b3:
2759 //
Mike Stump11289f42009-09-09 15:08:12 +00002760 // -- The argument list of the specialization shall not be identical
2761 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00002762 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00002763 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00002764 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00002765 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00002766 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00002767 ClassTemplate->getIdentifier(),
2768 TemplateNameLoc,
2769 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002770 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00002771 AS_none);
2772 }
2773
Douglas Gregor2208a292009-09-26 20:57:03 +00002774 // FIXME: Diagnose friend partial specializations
2775
Douglas Gregor2373c592009-05-31 09:31:02 +00002776 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00002777 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002778 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002779 Converted.flatSize(),
2780 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002781 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002782 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002783 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002784 Converted.flatSize(),
2785 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00002786 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002787 ClassTemplateSpecializationDecl *PrevDecl = 0;
2788
2789 if (isPartialSpecialization)
2790 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00002791 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00002792 InsertPos);
2793 else
2794 PrevDecl
2795 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00002796
2797 ClassTemplateSpecializationDecl *Specialization = 0;
2798
Douglas Gregorf47b9112009-02-25 22:02:03 +00002799 // Check whether we can declare a class template specialization in
2800 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00002801 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00002802 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
2803 TemplateNameLoc, isPartialSpecialization,
2804 TSK_ExplicitSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002805 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002806
Douglas Gregor15301382009-07-30 17:40:51 +00002807 // The canonical type
2808 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00002809 if (PrevDecl &&
2810 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
2811 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002812 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00002813 // arguments was referenced but not declared, or we're only
2814 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00002815 // declaration node as our own, updating its source location to
2816 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002817 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00002818 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00002819 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00002820 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00002821 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00002822 // Build the canonical type that describes the converted template
2823 // arguments of the class template partial specialization.
2824 CanonType = Context.getTemplateSpecializationType(
2825 TemplateName(ClassTemplate),
2826 Converted.getFlatArguments(),
2827 Converted.flatSize());
2828
Douglas Gregor2373c592009-05-31 09:31:02 +00002829 // Create a new class template partial specialization declaration node.
Mike Stump11289f42009-09-09 15:08:12 +00002830 TemplateParameterList *TemplateParams
Douglas Gregor2373c592009-05-31 09:31:02 +00002831 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2832 ClassTemplatePartialSpecializationDecl *PrevPartial
2833 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002834 ClassTemplatePartialSpecializationDecl *Partial
2835 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00002836 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002837 TemplateNameLoc,
2838 TemplateParams,
2839 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002840 Converted,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002841 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00002842
2843 if (PrevPartial) {
2844 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2845 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2846 } else {
2847 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2848 }
2849 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00002850
2851 // Check that all of the template parameters of the class template
2852 // partial specialization are deducible from the template
2853 // arguments. If not, this class template partial specialization
2854 // will never be used.
2855 llvm::SmallVector<bool, 8> DeducibleParams;
2856 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002857 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2858 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00002859 unsigned NumNonDeducible = 0;
2860 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2861 if (!DeducibleParams[I])
2862 ++NumNonDeducible;
2863
2864 if (NumNonDeducible) {
2865 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2866 << (NumNonDeducible > 1)
2867 << SourceRange(TemplateNameLoc, RAngleLoc);
2868 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2869 if (!DeducibleParams[I]) {
2870 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2871 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00002872 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002873 diag::note_partial_spec_unused_parameter)
2874 << Param->getDeclName();
2875 else
Mike Stump11289f42009-09-09 15:08:12 +00002876 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002877 diag::note_partial_spec_unused_parameter)
2878 << std::string("<anonymous>");
2879 }
2880 }
2881 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002882 } else {
2883 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00002884 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002885 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00002886 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00002887 ClassTemplate->getDeclContext(),
2888 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002889 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002890 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00002891 PrevDecl);
2892
2893 if (PrevDecl) {
2894 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2895 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2896 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002897 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00002898 InsertPos);
2899 }
Douglas Gregor15301382009-07-30 17:40:51 +00002900
2901 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002902 }
2903
Douglas Gregor2208a292009-09-26 20:57:03 +00002904 // If this is not a friend, note that this is an explicit specialization.
2905 if (TUK != TUK_Friend)
2906 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002907
2908 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002909 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002910 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002911 // FIXME: Should also handle explicit specialization after implicit
2912 // instantiation with a special diagnostic.
Douglas Gregor67a65642009-02-17 23:15:12 +00002913 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002914 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00002915 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00002916 Diag(Def->getLocation(), diag::note_previous_definition);
2917 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00002918 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002919 }
2920 }
2921
Douglas Gregord56a91e2009-02-26 22:19:44 +00002922 // Build the fully-sugared type for this class template
2923 // specialization as the user wrote in the specialization
2924 // itself. This means that we'll pretty-print the type retrieved
2925 // from the specialization's declaration the way that the user
2926 // actually wrote the specialization, rather than formatting the
2927 // name based on the "canonical" representation used to store the
2928 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002929 QualType WrittenTy
2930 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002931 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00002932 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00002933 CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00002934 if (TUK != TUK_Friend)
2935 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002936 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00002937
Douglas Gregor1e249f82009-02-25 22:18:32 +00002938 // C++ [temp.expl.spec]p9:
2939 // A template explicit specialization is in the scope of the
2940 // namespace in which the template was defined.
2941 //
2942 // We actually implement this paragraph where we set the semantic
2943 // context (in the creation of the ClassTemplateSpecializationDecl),
2944 // but we also maintain the lexical context where the actual
2945 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00002946 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00002947
Douglas Gregor67a65642009-02-17 23:15:12 +00002948 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002949 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00002950 Specialization->startDefinition();
2951
Douglas Gregor2208a292009-09-26 20:57:03 +00002952 if (TUK == TUK_Friend) {
2953 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
2954 TemplateNameLoc,
2955 WrittenTy.getTypePtr(),
2956 /*FIXME:*/KWLoc);
2957 Friend->setAccess(AS_public);
2958 CurContext->addDecl(Friend);
2959 } else {
2960 // Add the specialization into its lexical context, so that it can
2961 // be seen when iterating through the list of declarations in that
2962 // context. However, specializations are not found by name lookup.
2963 CurContext->addDecl(Specialization);
2964 }
Chris Lattner83f095c2009-03-28 19:18:32 +00002965 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002966}
Douglas Gregor333489b2009-03-27 23:10:48 +00002967
Mike Stump11289f42009-09-09 15:08:12 +00002968Sema::DeclPtrTy
2969Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002970 MultiTemplateParamsArg TemplateParameterLists,
2971 Declarator &D) {
2972 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2973}
2974
Mike Stump11289f42009-09-09 15:08:12 +00002975Sema::DeclPtrTy
2976Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002977 MultiTemplateParamsArg TemplateParameterLists,
2978 Declarator &D) {
2979 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2980 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2981 "Not a function declarator!");
2982 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00002983
Douglas Gregor17a7c122009-06-24 00:54:41 +00002984 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00002985 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00002986 }
Mike Stump11289f42009-09-09 15:08:12 +00002987
Douglas Gregor17a7c122009-06-24 00:54:41 +00002988 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002989
2990 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002991 move(TemplateParameterLists),
2992 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002993 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00002994 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00002995 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002996 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00002997 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2998 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002999 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003000}
3001
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003002/// \brief Perform semantic analysis for the given function template
3003/// specialization.
3004///
3005/// This routine performs all of the semantic analysis required for an
3006/// explicit function template specialization. On successful completion,
3007/// the function declaration \p FD will become a function template
3008/// specialization.
3009///
3010/// \param FD the function declaration, which will be updated to become a
3011/// function template specialization.
3012///
3013/// \param HasExplicitTemplateArgs whether any template arguments were
3014/// explicitly provided.
3015///
3016/// \param LAngleLoc the location of the left angle bracket ('<'), if
3017/// template arguments were explicitly provided.
3018///
3019/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3020/// if any.
3021///
3022/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3023/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3024/// true as in, e.g., \c void sort<>(char*, char*);
3025///
3026/// \param RAngleLoc the location of the right angle bracket ('>'), if
3027/// template arguments were explicitly provided.
3028///
3029/// \param PrevDecl the set of declarations that
3030bool
3031Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3032 bool HasExplicitTemplateArgs,
3033 SourceLocation LAngleLoc,
3034 const TemplateArgument *ExplicitTemplateArgs,
3035 unsigned NumExplicitTemplateArgs,
3036 SourceLocation RAngleLoc,
3037 NamedDecl *&PrevDecl) {
3038 // The set of function template specializations that could match this
3039 // explicit function template specialization.
3040 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3041 CandidateSet Candidates;
3042
3043 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3044 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3045 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3046 // Only consider templates found within the same semantic lookup scope as
3047 // FD.
3048 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3049 continue;
3050
3051 // C++ [temp.expl.spec]p11:
3052 // A trailing template-argument can be left unspecified in the
3053 // template-id naming an explicit function template specialization
3054 // provided it can be deduced from the function argument type.
3055 // Perform template argument deduction to determine whether we may be
3056 // specializing this template.
3057 // FIXME: It is somewhat wasteful to build
3058 TemplateDeductionInfo Info(Context);
3059 FunctionDecl *Specialization = 0;
3060 if (TemplateDeductionResult TDK
3061 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3062 ExplicitTemplateArgs,
3063 NumExplicitTemplateArgs,
3064 FD->getType(),
3065 Specialization,
3066 Info)) {
3067 // FIXME: Template argument deduction failed; record why it failed, so
3068 // that we can provide nifty diagnostics.
3069 (void)TDK;
3070 continue;
3071 }
3072
3073 // Record this candidate.
3074 Candidates.push_back(Specialization);
3075 }
3076 }
3077
Douglas Gregor5de279c2009-09-26 03:41:46 +00003078 // Find the most specialized function template.
3079 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3080 Candidates.size(),
3081 TPOC_Other,
3082 FD->getLocation(),
3083 PartialDiagnostic(diag::err_function_template_spec_no_match)
3084 << FD->getDeclName(),
3085 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3086 << FD->getDeclName() << HasExplicitTemplateArgs,
3087 PartialDiagnostic(diag::note_function_template_spec_matched));
3088 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003089 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003090
3091 // FIXME: Check if the prior specialization has a point of instantiation.
3092 // If so, we have run afoul of C++ [temp.expl.spec]p6.
3093
Douglas Gregor54888652009-10-07 00:13:32 +00003094 // Check the scope of this explicit specialization.
3095 if (CheckTemplateSpecializationScope(*this,
3096 Specialization->getPrimaryTemplate(),
3097 Specialization, FD->getLocation(),
3098 false, TSK_ExplicitSpecialization))
3099 return true;
3100
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003101 // Mark the prior declaration as an explicit specialization, so that later
3102 // clients know that this is an explicit specialization.
3103 // FIXME: Check for prior explicit instantiations?
3104 Specialization->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
3105
3106 // Turn the given function declaration into a function template
3107 // specialization, with the template arguments from the previous
3108 // specialization.
3109 FD->setFunctionTemplateSpecialization(Context,
3110 Specialization->getPrimaryTemplate(),
3111 new (Context) TemplateArgumentList(
3112 *Specialization->getTemplateSpecializationArgs()),
3113 /*InsertPos=*/0,
3114 TSK_ExplicitSpecialization);
3115
3116 // The "previous declaration" for this function template specialization is
3117 // the prior function template specialization.
3118 PrevDecl = Specialization;
3119 return false;
3120}
3121
Douglas Gregor86d142a2009-10-08 07:24:58 +00003122/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003123/// specialization.
3124///
3125/// This routine performs all of the semantic analysis required for an
3126/// explicit member function specialization. On successful completion,
3127/// the function declaration \p FD will become a member function
3128/// specialization.
3129///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003130/// \param Member the member declaration, which will be updated to become a
3131/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003132///
3133/// \param PrevDecl the set of declarations, one of which may be specialized
3134/// by this function specialization.
3135bool
Douglas Gregor86d142a2009-10-08 07:24:58 +00003136Sema::CheckMemberSpecialization(NamedDecl *Member, NamedDecl *&PrevDecl) {
3137 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3138
3139 // Try to find the member we are instantiating.
3140 NamedDecl *Instantiation = 0;
3141 NamedDecl *InstantiatedFrom = 0;
3142 if (!PrevDecl) {
3143 // Nowhere to look anyway.
3144 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3145 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3146 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl)) {
3147 if (Context.hasSameType(Function->getType(), Method->getType())) {
3148 Instantiation = Method;
3149 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
3150 break;
3151 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003152 }
3153 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003154 } else if (isa<VarDecl>(Member)) {
3155 if (VarDecl *PrevVar = dyn_cast<VarDecl>(PrevDecl))
3156 if (PrevVar->isStaticDataMember()) {
3157 Instantiation = PrevDecl;
3158 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
3159 }
3160 } else if (isa<RecordDecl>(Member)) {
3161 if (CXXRecordDecl *PrevRecord = dyn_cast<CXXRecordDecl>(PrevDecl)) {
3162 Instantiation = PrevDecl;
3163 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
3164 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003165 }
3166
3167 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003168 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003169 // specializations are always out-of-line, the caller will complain about
3170 // this mismatch later.
3171 return false;
3172 }
3173
3174 // FIXME: Check if the prior declaration has a point of instantiation.
3175 // If so, we have run afoul of C++ [temp.expl.spec]p6.
3176
Douglas Gregor86d142a2009-10-08 07:24:58 +00003177 // Make sure that this is a specialization of a member.
3178 if (!InstantiatedFrom) {
3179 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3180 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003181 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3182 return true;
3183 }
3184
3185 // Check the scope of this explicit specialization.
3186 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003187 InstantiatedFrom,
3188 Instantiation, Member->getLocation(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003189 false, TSK_ExplicitSpecialization))
3190 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003191
3192 // FIXME: Check for specialization-after-instantiation errors and such.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003193
Douglas Gregor86d142a2009-10-08 07:24:58 +00003194 // Note that this is an explicit instantiation of a member.
3195 if (isa<FunctionDecl>(Member)) {
3196 // FIXME: We're also setting the original instantiation we found to be
3197 // an explicit specialization, although I'd rather not have to do this.
3198 cast<FunctionDecl>(Instantiation)->setTemplateSpecializationKind(
3199 TSK_ExplicitSpecialization);
3200 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3201 cast<CXXMethodDecl>(InstantiatedFrom),
3202 TSK_ExplicitSpecialization);
3203 } else if (isa<VarDecl>(Member)) {
3204 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3205 cast<VarDecl>(InstantiatedFrom),
3206 TSK_ExplicitSpecialization);
3207 } else {
3208 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
3209 // FIXME: Record TSK_ExplicitSpecialization.
3210 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
3211 cast<CXXRecordDecl>(InstantiatedFrom));
3212 }
3213
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003214 // Save the caller the trouble of having to figure out which declaration
3215 // this specialization matches.
3216 PrevDecl = Instantiation;
3217 return false;
3218}
3219
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003220// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003221// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003222Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003223Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003224 SourceLocation ExternLoc,
3225 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003226 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003227 SourceLocation KWLoc,
3228 const CXXScopeSpec &SS,
3229 TemplateTy TemplateD,
3230 SourceLocation TemplateNameLoc,
3231 SourceLocation LAngleLoc,
3232 ASTTemplateArgsPtr TemplateArgsIn,
3233 SourceLocation *TemplateArgLocs,
3234 SourceLocation RAngleLoc,
3235 AttributeList *Attr) {
3236 // Find the class template we're specializing
3237 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003238 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003239 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3240
3241 // Check that the specialization uses the same tag kind as the
3242 // original template.
3243 TagDecl::TagKind Kind;
3244 switch (TagSpec) {
3245 default: assert(0 && "Unknown tag type!");
3246 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3247 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3248 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3249 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003250 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003251 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003252 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003253 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003254 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003255 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003256 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003257 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003258 diag::note_previous_use);
3259 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3260 }
3261
Douglas Gregor54888652009-10-07 00:13:32 +00003262 TemplateSpecializationKind TSK
3263 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3264 : TSK_ExplicitInstantiationDeclaration;
3265
Douglas Gregora1f49972009-05-13 00:25:59 +00003266 // Translate the parser's template argument list in our AST format.
3267 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3268 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3269
3270 // Check that the template argument list is well-formed for this
3271 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003272 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3273 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003274 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003275 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003276 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003277 return true;
3278
Mike Stump11289f42009-09-09 15:08:12 +00003279 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003280 ClassTemplate->getTemplateParameters()->size()) &&
3281 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003282
Douglas Gregora1f49972009-05-13 00:25:59 +00003283 // Find the class template specialization declaration that
3284 // corresponds to these arguments.
3285 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003286 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003287 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003288 Converted.flatSize(),
3289 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003290 void *InsertPos = 0;
3291 ClassTemplateSpecializationDecl *PrevDecl
3292 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3293
Douglas Gregor54888652009-10-07 00:13:32 +00003294 // C++0x [temp.explicit]p2:
3295 // [...] An explicit instantiation shall appear in an enclosing
3296 // namespace of its template. [...]
3297 //
3298 // This is C++ DR 275.
3299 if (CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
3300 TemplateNameLoc, false,
3301 TSK))
3302 return true;
3303
Douglas Gregora1f49972009-05-13 00:25:59 +00003304 ClassTemplateSpecializationDecl *Specialization = 0;
3305
Douglas Gregorf61eca92009-05-13 18:28:20 +00003306 bool SpecializationRequiresInstantiation = true;
Douglas Gregora1f49972009-05-13 00:25:59 +00003307 if (PrevDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003308 if (PrevDecl->getSpecializationKind()
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003309 == TSK_ExplicitInstantiationDefinition) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003310 // This particular specialization has already been declared or
3311 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorf61eca92009-05-13 18:28:20 +00003312 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
3313 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003314 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003315 diag::note_previous_explicit_instantiation);
Douglas Gregora1f49972009-05-13 00:25:59 +00003316 return DeclPtrTy::make(PrevDecl);
3317 }
3318
Douglas Gregorf61eca92009-05-13 18:28:20 +00003319 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003320 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorf61eca92009-05-13 18:28:20 +00003321 // For a given set of template parameters, if an explicit
3322 // instantiation of a template appears after a declaration of
3323 // an explicit specialization for that template, the explicit
3324 // instantiation has no effect.
3325 if (!getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00003326 Diag(TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003327 diag::ext_explicit_instantiation_after_specialization)
3328 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003329 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003330 diag::note_previous_template_specialization);
3331 }
3332
3333 // Create a new class template specialization declaration node
3334 // for this explicit specialization. This node is only used to
3335 // record the existence of this explicit instantiation for
3336 // accurate reproduction of the source code; we don't actually
3337 // use it for anything, since it is semantically irrelevant.
3338 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003339 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003340 ClassTemplate->getDeclContext(),
3341 TemplateNameLoc,
3342 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003343 Converted, 0);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003344 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003345 CurContext->addDecl(Specialization);
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003346 return DeclPtrTy::make(PrevDecl);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003347 }
3348
3349 // If we have already (implicitly) instantiated this
3350 // specialization, there is less work to do.
3351 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
3352 SpecializationRequiresInstantiation = false;
3353
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003354 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3355 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3356 // Since the only prior class template specialization with these
3357 // arguments was referenced but not declared, reuse that
3358 // declaration node as our own, updating its source location to
3359 // reflect our new declaration.
3360 Specialization = PrevDecl;
3361 Specialization->setLocation(TemplateNameLoc);
3362 PrevDecl = 0;
3363 }
3364 }
3365
3366 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003367 // Create a new class template specialization declaration node for
3368 // this explicit specialization.
3369 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003370 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003371 ClassTemplate->getDeclContext(),
3372 TemplateNameLoc,
3373 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003374 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003375
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003376 if (PrevDecl) {
3377 // Remove the previous declaration from the folding set, since we want
3378 // to introduce a new declaration.
3379 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3380 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3381 }
3382
3383 // Insert the new specialization.
3384 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003385 }
3386
3387 // Build the fully-sugared type for this explicit instantiation as
3388 // the user wrote in the explicit instantiation itself. This means
3389 // that we'll pretty-print the type retrieved from the
3390 // specialization's declaration the way that the user actually wrote
3391 // the explicit instantiation, rather than formatting the name based
3392 // on the "canonical" representation used to store the template
3393 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003394 QualType WrittenTy
3395 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003396 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003397 TemplateArgs.size(),
3398 Context.getTypeDeclType(Specialization));
3399 Specialization->setTypeAsWritten(WrittenTy);
3400 TemplateArgsIn.release();
3401
3402 // Add the explicit instantiation into its lexical context. However,
3403 // since explicit instantiations are never found by name lookup, we
3404 // just put it into the declaration context directly.
3405 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003406 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003407
John McCall1806c272009-09-11 07:25:08 +00003408 Specialization->setPointOfInstantiation(TemplateNameLoc);
3409
Douglas Gregora1f49972009-05-13 00:25:59 +00003410 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003411 // A definition of a class template or class member template
3412 // shall be in scope at the point of the explicit instantiation of
3413 // the class template or class member template.
3414 //
3415 // This check comes when we actually try to perform the
3416 // instantiation.
Douglas Gregor67da0d92009-05-15 17:59:04 +00003417 if (SpecializationRequiresInstantiation)
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003418 InstantiateClassTemplateSpecialization(Specialization, TSK);
Douglas Gregor85673582009-05-18 17:01:57 +00003419 else // Instantiate the members of this class template specialization.
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003420 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization,
3421 TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003422
3423 return DeclPtrTy::make(Specialization);
3424}
3425
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003426// Explicit instantiation of a member class of a class template.
3427Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003428Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003429 SourceLocation ExternLoc,
3430 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003431 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003432 SourceLocation KWLoc,
3433 const CXXScopeSpec &SS,
3434 IdentifierInfo *Name,
3435 SourceLocation NameLoc,
3436 AttributeList *Attr) {
3437
Douglas Gregord6ab8742009-05-28 23:31:59 +00003438 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003439 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00003440 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00003441 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00003442 MultiTemplateParamsArg(*this, 0, 0),
3443 Owned, IsDependent);
3444 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3445
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003446 if (!TagD)
3447 return true;
3448
3449 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3450 if (Tag->isEnum()) {
3451 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3452 << Context.getTypeDeclType(Tag);
3453 return true;
3454 }
3455
Douglas Gregorb8006faf2009-05-27 17:30:49 +00003456 if (Tag->isInvalidDecl())
3457 return true;
3458
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003459 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3460 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3461 if (!Pattern) {
3462 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3463 << Context.getTypeDeclType(Record);
3464 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3465 return true;
3466 }
3467
3468 // C++0x [temp.explicit]p2:
3469 // [...] An explicit instantiation shall appear in an enclosing
3470 // namespace of its template. [...]
3471 //
3472 // This is C++ DR 275.
3473 if (getLangOptions().CPlusPlus0x) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003474 // FIXME: In C++98, we would like to turn these errors into warnings,
3475 // dependent on a -Wc++0x flag.
Mike Stump11289f42009-09-09 15:08:12 +00003476 DeclContext *PatternContext
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003477 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
3478 if (!CurContext->Encloses(PatternContext)) {
3479 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
3480 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
3481 Diag(Pattern->getLocation(), diag::note_previous_declaration);
3482 }
3483 }
3484
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003485 TemplateSpecializationKind TSK
Mike Stump11289f42009-09-09 15:08:12 +00003486 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003487 : TSK_ExplicitInstantiationDeclaration;
Mike Stump11289f42009-09-09 15:08:12 +00003488
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003489 if (!Record->getDefinition(Context)) {
3490 // If the class has a definition, instantiate it (and all of its
3491 // members, recursively).
3492 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
Mike Stump11289f42009-09-09 15:08:12 +00003493 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregorb4850462009-05-14 23:26:13 +00003494 getTemplateInstantiationArgs(Record),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003495 TSK))
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003496 return true;
John McCall76d824f2009-08-25 22:02:44 +00003497 } else // Instantiate all of the members of the class.
Mike Stump11289f42009-09-09 15:08:12 +00003498 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003499 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003500
Mike Stump87c57ac2009-05-16 07:39:55 +00003501 // FIXME: We don't have any representation for explicit instantiations of
3502 // member classes. Such a representation is not needed for compilation, but it
3503 // should be available for clients that want to see all of the declarations in
3504 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003505 return TagD;
3506}
3507
Douglas Gregor450f00842009-09-25 18:43:00 +00003508Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
3509 SourceLocation ExternLoc,
3510 SourceLocation TemplateLoc,
3511 Declarator &D) {
3512 // Explicit instantiations always require a name.
3513 DeclarationName Name = GetNameForDeclarator(D);
3514 if (!Name) {
3515 if (!D.isInvalidType())
3516 Diag(D.getDeclSpec().getSourceRange().getBegin(),
3517 diag::err_explicit_instantiation_requires_name)
3518 << D.getDeclSpec().getSourceRange()
3519 << D.getSourceRange();
3520
3521 return true;
3522 }
3523
3524 // The scope passed in may not be a decl scope. Zip up the scope tree until
3525 // we find one that is.
3526 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3527 (S->getFlags() & Scope::TemplateParamScope) != 0)
3528 S = S->getParent();
3529
3530 // Determine the type of the declaration.
3531 QualType R = GetTypeForDeclarator(D, S, 0);
3532 if (R.isNull())
3533 return true;
3534
3535 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3536 // Cannot explicitly instantiate a typedef.
3537 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
3538 << Name;
3539 return true;
3540 }
3541
3542 // Determine what kind of explicit instantiation we have.
3543 TemplateSpecializationKind TSK
3544 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3545 : TSK_ExplicitInstantiationDeclaration;
3546
3547 LookupResult Previous = LookupParsedName(S, &D.getCXXScopeSpec(),
3548 Name, LookupOrdinaryName);
3549
3550 if (!R->isFunctionType()) {
3551 // C++ [temp.explicit]p1:
3552 // A [...] static data member of a class template can be explicitly
3553 // instantiated from the member definition associated with its class
3554 // template.
3555 if (Previous.isAmbiguous()) {
3556 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
3557 D.getSourceRange());
3558 }
3559
3560 VarDecl *Prev = dyn_cast_or_null<VarDecl>(Previous.getAsDecl());
3561 if (!Prev || !Prev->isStaticDataMember()) {
3562 // We expect to see a data data member here.
3563 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
3564 << Name;
3565 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3566 P != PEnd; ++P)
3567 Diag(P->getLocation(), diag::note_explicit_instantiation_here);
3568 return true;
3569 }
3570
3571 if (!Prev->getInstantiatedFromStaticDataMember()) {
3572 // FIXME: Check for explicit specialization?
3573 Diag(D.getIdentifierLoc(),
3574 diag::err_explicit_instantiation_data_member_not_instantiated)
3575 << Prev;
3576 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
3577 // FIXME: Can we provide a note showing where this was declared?
3578 return true;
3579 }
3580
3581 // Instantiate static data member.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003582 // FIXME: Check for prior specializations and such.
3583 Prev->setTemplateSpecializationKind(TSK);
Douglas Gregor450f00842009-09-25 18:43:00 +00003584 if (TSK == TSK_ExplicitInstantiationDefinition)
3585 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false);
3586
3587 // FIXME: Create an ExplicitInstantiation node?
3588 return DeclPtrTy();
3589 }
3590
Douglas Gregor0e876e02009-09-25 23:53:26 +00003591 // If the declarator is a template-id, translate the parser's template
3592 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00003593 bool HasExplicitTemplateArgs = false;
3594 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3595 if (D.getKind() == Declarator::DK_TemplateId) {
3596 TemplateIdAnnotation *TemplateId = D.getTemplateId();
3597 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3598 TemplateId->getTemplateArgs(),
3599 TemplateId->getTemplateArgIsType(),
3600 TemplateId->NumArgs);
3601 translateTemplateArguments(TemplateArgsPtr,
3602 TemplateId->getTemplateArgLocations(),
3603 TemplateArgs);
3604 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00003605 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00003606 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00003607
Douglas Gregor450f00842009-09-25 18:43:00 +00003608 // C++ [temp.explicit]p1:
3609 // A [...] function [...] can be explicitly instantiated from its template.
3610 // A member function [...] of a class template can be explicitly
3611 // instantiated from the member definition associated with its class
3612 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00003613 llvm::SmallVector<FunctionDecl *, 8> Matches;
3614 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3615 P != PEnd; ++P) {
3616 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00003617 if (!HasExplicitTemplateArgs) {
3618 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
3619 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
3620 Matches.clear();
3621 Matches.push_back(Method);
3622 break;
3623 }
Douglas Gregor450f00842009-09-25 18:43:00 +00003624 }
3625 }
3626
3627 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
3628 if (!FunTmpl)
3629 continue;
3630
3631 TemplateDeductionInfo Info(Context);
3632 FunctionDecl *Specialization = 0;
3633 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00003634 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3635 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00003636 R, Specialization, Info)) {
3637 // FIXME: Keep track of almost-matches?
3638 (void)TDK;
3639 continue;
3640 }
3641
3642 Matches.push_back(Specialization);
3643 }
3644
3645 // Find the most specialized function template specialization.
3646 FunctionDecl *Specialization
3647 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
3648 D.getIdentifierLoc(),
3649 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
3650 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
3651 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
3652
3653 if (!Specialization)
3654 return true;
3655
3656 switch (Specialization->getTemplateSpecializationKind()) {
3657 case TSK_Undeclared:
3658 Diag(D.getIdentifierLoc(),
3659 diag::err_explicit_instantiation_member_function_not_instantiated)
3660 << Specialization
3661 << (Specialization->getTemplateSpecializationKind() ==
3662 TSK_ExplicitSpecialization);
3663 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
3664 return true;
3665
3666 case TSK_ExplicitSpecialization:
3667 // C++ [temp.explicit]p4:
3668 // For a given set of template parameters, if an explicit instantiation
3669 // of a template appears after a declaration of an explicit
3670 // specialization for that template, the explicit instantiation has no
3671 // effect.
3672 break;
3673
3674 case TSK_ExplicitInstantiationDefinition:
3675 // FIXME: Check that we aren't trying to perform an explicit instantiation
3676 // declaration now.
3677 // Fall through
3678
3679 case TSK_ImplicitInstantiation:
3680 case TSK_ExplicitInstantiationDeclaration:
3681 // Instantiate the function, if this is an explicit instantiation
3682 // definition.
3683 if (TSK == TSK_ExplicitInstantiationDefinition)
3684 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
3685 false);
3686
Douglas Gregor450f00842009-09-25 18:43:00 +00003687 Specialization->setTemplateSpecializationKind(TSK);
3688 break;
3689 }
3690
3691 // FIXME: Create some kind of ExplicitInstantiationDecl here.
3692 return DeclPtrTy();
3693}
3694
Douglas Gregor333489b2009-03-27 23:10:48 +00003695Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00003696Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3697 const CXXScopeSpec &SS, IdentifierInfo *Name,
3698 SourceLocation TagLoc, SourceLocation NameLoc) {
3699 // This has to hold, because SS is expected to be defined.
3700 assert(Name && "Expected a name in a dependent tag");
3701
3702 NestedNameSpecifier *NNS
3703 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3704 if (!NNS)
3705 return true;
3706
3707 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
3708 if (T.isNull())
3709 return true;
3710
3711 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
3712 QualType ElabType = Context.getElaboratedType(T, TagKind);
3713
3714 return ElabType.getAsOpaquePtr();
3715}
3716
3717Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00003718Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3719 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00003720 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00003721 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3722 if (!NNS)
3723 return true;
3724
3725 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003726 if (T.isNull())
3727 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00003728 return T.getAsOpaquePtr();
3729}
3730
Douglas Gregordce2b622009-04-01 00:28:59 +00003731Sema::TypeResult
3732Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3733 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003734 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003735 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00003736 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00003737 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00003738 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00003739 assert(TemplateId && "Expected a template specialization type");
3740
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003741 if (computeDeclContext(SS, false)) {
3742 // If we can compute a declaration context, then the "typename"
3743 // keyword was superfluous. Just build a QualifiedNameType to keep
3744 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00003745
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003746 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
3747 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
3748 }
Mike Stump11289f42009-09-09 15:08:12 +00003749
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003750 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00003751}
3752
Douglas Gregor333489b2009-03-27 23:10:48 +00003753/// \brief Build the type that describes a C++ typename specifier,
3754/// e.g., "typename T::type".
3755QualType
3756Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
3757 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003758 CXXRecordDecl *CurrentInstantiation = 0;
3759 if (NNS->isDependent()) {
3760 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00003761
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003762 // If the nested-name-specifier does not refer to the current
3763 // instantiation, then build a typename type.
3764 if (!CurrentInstantiation)
3765 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00003766
Douglas Gregorc707da62009-09-02 13:12:51 +00003767 // The nested-name-specifier refers to the current instantiation, so the
3768 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00003769 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00003770 // extraneous "typename" keywords, and we retroactively apply this DR to
3771 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003772 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003773
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003774 DeclContext *Ctx = 0;
3775
3776 if (CurrentInstantiation)
3777 Ctx = CurrentInstantiation;
3778 else {
3779 CXXScopeSpec SS;
3780 SS.setScopeRep(NNS);
3781 SS.setRange(Range);
3782 if (RequireCompleteDeclContext(SS))
3783 return QualType();
3784
3785 Ctx = computeDeclContext(SS);
3786 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003787 assert(Ctx && "No declaration context?");
3788
3789 DeclarationName Name(&II);
Mike Stump11289f42009-09-09 15:08:12 +00003790 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
Douglas Gregor333489b2009-03-27 23:10:48 +00003791 false);
3792 unsigned DiagID = 0;
3793 Decl *Referenced = 0;
3794 switch (Result.getKind()) {
3795 case LookupResult::NotFound:
3796 if (Ctx->isTranslationUnit())
3797 DiagID = diag::err_typename_nested_not_found_global;
3798 else
3799 DiagID = diag::err_typename_nested_not_found;
3800 break;
3801
3802 case LookupResult::Found:
3803 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3804 // We found a type. Build a QualifiedNameType, since the
3805 // typename-specifier was just sugar. FIXME: Tell
3806 // QualifiedNameType that it has a "typename" prefix.
3807 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3808 }
3809
3810 DiagID = diag::err_typename_nested_not_type;
3811 Referenced = Result.getAsDecl();
3812 break;
3813
3814 case LookupResult::FoundOverloaded:
3815 DiagID = diag::err_typename_nested_not_type;
3816 Referenced = *Result.begin();
3817 break;
3818
3819 case LookupResult::AmbiguousBaseSubobjectTypes:
3820 case LookupResult::AmbiguousBaseSubobjects:
3821 case LookupResult::AmbiguousReference:
3822 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3823 return QualType();
3824 }
3825
3826 // If we get here, it's because name lookup did not find a
3827 // type. Emit an appropriate diagnostic and return an error.
3828 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3829 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3830 else
3831 Diag(Range.getEnd(), DiagID) << Range << Name;
3832 if (Referenced)
3833 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3834 << Name;
3835 return QualType();
3836}
Douglas Gregor15acfb92009-08-06 16:20:37 +00003837
3838namespace {
3839 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00003840 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3841 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00003842 SourceLocation Loc;
3843 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00003844
Douglas Gregor15acfb92009-08-06 16:20:37 +00003845 public:
Mike Stump11289f42009-09-09 15:08:12 +00003846 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00003847 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003848 DeclarationName Entity)
3849 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00003850 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00003851
3852 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00003853 /// transformed.
3854 ///
3855 /// For the purposes of type reconstruction, a type has already been
3856 /// transformed if it is NULL or if it is not dependent.
3857 bool AlreadyTransformed(QualType T) {
3858 return T.isNull() || !T->isDependentType();
3859 }
Mike Stump11289f42009-09-09 15:08:12 +00003860
3861 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00003862 /// rebuilt.
3863 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00003864
Douglas Gregor15acfb92009-08-06 16:20:37 +00003865 /// \brief Returns the name of the entity whose type is being rebuilt.
3866 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00003867
Douglas Gregor15acfb92009-08-06 16:20:37 +00003868 /// \brief Transforms an expression by returning the expression itself
3869 /// (an identity function).
3870 ///
3871 /// FIXME: This is completely unsafe; we will need to actually clone the
3872 /// expressions.
3873 Sema::OwningExprResult TransformExpr(Expr *E) {
3874 return getSema().Owned(E);
3875 }
Mike Stump11289f42009-09-09 15:08:12 +00003876
Douglas Gregor15acfb92009-08-06 16:20:37 +00003877 /// \brief Transforms a typename type by determining whether the type now
3878 /// refers to a member of the current instantiation, and then
3879 /// type-checking and building a QualifiedNameType (when possible).
3880 QualType TransformTypenameType(const TypenameType *T);
3881 };
3882}
3883
Mike Stump11289f42009-09-09 15:08:12 +00003884QualType
Douglas Gregor15acfb92009-08-06 16:20:37 +00003885CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3886 NestedNameSpecifier *NNS
3887 = TransformNestedNameSpecifier(T->getQualifier(),
3888 /*FIXME:*/SourceRange(getBaseLocation()));
3889 if (!NNS)
3890 return QualType();
3891
3892 // If the nested-name-specifier did not change, and we cannot compute the
3893 // context corresponding to the nested-name-specifier, then this
3894 // typename type will not change; exit early.
3895 CXXScopeSpec SS;
3896 SS.setRange(SourceRange(getBaseLocation()));
3897 SS.setScopeRep(NNS);
3898 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3899 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003900
3901 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00003902 // QualifiedNameType.
3903 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00003904 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00003905 = TransformType(QualType(TemplateId, 0));
3906 if (NewTemplateId.isNull())
3907 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003908
Douglas Gregor15acfb92009-08-06 16:20:37 +00003909 if (NNS == T->getQualifier() &&
3910 NewTemplateId == QualType(TemplateId, 0))
3911 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003912
Douglas Gregor15acfb92009-08-06 16:20:37 +00003913 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3914 }
Mike Stump11289f42009-09-09 15:08:12 +00003915
Douglas Gregor15acfb92009-08-06 16:20:37 +00003916 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3917}
3918
3919/// \brief Rebuilds a type within the context of the current instantiation.
3920///
Mike Stump11289f42009-09-09 15:08:12 +00003921/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00003922/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00003923/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00003924/// partial specialization thereof). This routine will rebuild that type now
3925/// that we have entered the declarator's scope, which may produce different
3926/// canonical types, e.g.,
3927///
3928/// \code
3929/// template<typename T>
3930/// struct X {
3931/// typedef T* pointer;
3932/// pointer data();
3933/// };
3934///
3935/// template<typename T>
3936/// typename X<T>::pointer X<T>::data() { ... }
3937/// \endcode
3938///
3939/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3940/// since we do not know that we can look into X<T> when we parsed the type.
3941/// This function will rebuild the type, performing the lookup of "pointer"
3942/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3943/// as the canonical type of T*, allowing the return types of the out-of-line
3944/// definition and the declaration to match.
3945QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3946 DeclarationName Name) {
3947 if (T.isNull() || !T->isDependentType())
3948 return T;
Mike Stump11289f42009-09-09 15:08:12 +00003949
Douglas Gregor15acfb92009-08-06 16:20:37 +00003950 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3951 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00003952}
Douglas Gregorbe999392009-09-15 16:23:51 +00003953
3954/// \brief Produces a formatted string that describes the binding of
3955/// template parameters to template arguments.
3956std::string
3957Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3958 const TemplateArgumentList &Args) {
3959 std::string Result;
3960
3961 if (!Params || Params->size() == 0)
3962 return Result;
3963
3964 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3965 if (I == 0)
3966 Result += "[with ";
3967 else
3968 Result += ", ";
3969
3970 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
3971 Result += Id->getName();
3972 } else {
3973 Result += '$';
3974 Result += llvm::utostr(I);
3975 }
3976
3977 Result += " = ";
3978
3979 switch (Args[I].getKind()) {
3980 case TemplateArgument::Null:
3981 Result += "<no value>";
3982 break;
3983
3984 case TemplateArgument::Type: {
3985 std::string TypeStr;
3986 Args[I].getAsType().getAsStringInternal(TypeStr,
3987 Context.PrintingPolicy);
3988 Result += TypeStr;
3989 break;
3990 }
3991
3992 case TemplateArgument::Declaration: {
3993 bool Unnamed = true;
3994 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
3995 if (ND->getDeclName()) {
3996 Unnamed = false;
3997 Result += ND->getNameAsString();
3998 }
3999 }
4000
4001 if (Unnamed) {
4002 Result += "<anonymous>";
4003 }
4004 break;
4005 }
4006
4007 case TemplateArgument::Integral: {
4008 Result += Args[I].getAsIntegral()->toString(10);
4009 break;
4010 }
4011
4012 case TemplateArgument::Expression: {
4013 assert(false && "No expressions in deduced template arguments!");
4014 Result += "<expression>";
4015 break;
4016 }
4017
4018 case TemplateArgument::Pack:
4019 // FIXME: Format template argument packs
4020 Result += "<template argument pack>";
4021 break;
4022 }
4023 }
4024
4025 Result += ']';
4026 return Result;
4027}