blob: f3cd2e41fbd3f63f35238d27a1b8427b5a25839b [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();
2368
2369 // FIXME: static data members!
2370 // FIXME: member classes of class templates!
2371 return TSK_Undeclared;
2372}
2373
2374/// \brief Check whether a specialization or explicit instantiation is
2375/// well-formed in the current context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002376///
Douglas Gregor54888652009-10-07 00:13:32 +00002377/// This routine determines whether a template specialization or
Mike Stump11289f42009-09-09 15:08:12 +00002378/// explicit instantiation can be declared in the current context
Douglas Gregor54888652009-10-07 00:13:32 +00002379/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2).
2380///
2381/// \param S the semantic analysis object for which this check is being
2382/// performed.
2383///
2384/// \param Specialized the entity being specialized or instantiated, which
2385/// may be a kind of template (class template, function template, etc.) or
2386/// a member of a class template (member function, static data member,
2387/// member class).
2388///
2389/// \param PrevDecl the previous declaration of this entity, if any.
2390///
2391/// \param Loc the location of the explicit specialization or instantiation of
2392/// this entity.
2393///
2394/// \param IsPartialSpecialization whether this is a partial specialization of
2395/// a class template.
2396///
2397/// \param TSK the kind of specialization or implicit instantiation being
2398/// performed.
2399///
2400/// \returns true if there was an error that we cannot recover from, false
2401/// otherwise.
2402static bool CheckTemplateSpecializationScope(Sema &S,
2403 NamedDecl *Specialized,
2404 NamedDecl *PrevDecl,
2405 SourceLocation Loc,
2406 bool IsPartialSpecialization,
2407 TemplateSpecializationKind TSK) {
2408 // Keep these "kind" numbers in sync with the %select statements in the
2409 // various diagnostics emitted by this routine.
2410 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002411 bool isTemplateSpecialization = false;
2412 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002413 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002414 isTemplateSpecialization = true;
2415 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002416 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002417 isTemplateSpecialization = true;
2418 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002419 EntityKind = 3;
2420 else if (isa<VarDecl>(Specialized))
2421 EntityKind = 4;
2422 else if (isa<RecordDecl>(Specialized))
2423 EntityKind = 5;
2424 else {
2425 S.Diag(Loc, diag::err_template_spec_unknown_kind) << TSK;
2426 S.Diag(Specialized->getLocation(), diag::note_specialized_entity) << TSK;
2427 return true;
2428 }
2429
Douglas Gregorf47b9112009-02-25 22:02:03 +00002430 // C++ [temp.expl.spec]p2:
2431 // An explicit specialization shall be declared in the namespace
2432 // of which the template is a member, or, for member templates, in
2433 // the namespace of which the enclosing class or enclosing class
2434 // template is a member. An explicit specialization of a member
2435 // function, member class or static data member of a class
2436 // template shall be declared in the namespace of which the class
2437 // template is a member. Such a declaration may also be a
2438 // definition. If the declaration is not a definition, the
2439 // specialization may be defined later in the name- space in which
2440 // the explicit specialization was declared, or in a namespace
2441 // that encloses the one in which the explicit specialization was
2442 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002443 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2444 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
2445 << TSK << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002446 return true;
2447 }
Douglas Gregore4b05162009-10-07 17:21:34 +00002448
Douglas Gregor40fb7442009-10-07 17:30:37 +00002449 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2450 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
2451 << TSK << Specialized;
2452 return true;
2453 }
2454
Douglas Gregore4b05162009-10-07 17:21:34 +00002455 // C++ [temp.class.spec]p6:
2456 // A class template partial specialization may be declared or redeclared
2457 // in any namespace scope in which its definition may be defined (14.5.1
2458 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002459 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002460 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002461 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002462 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor54888652009-10-07 00:13:32 +00002463 if (TSK == TSK_ExplicitSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002464 if ((!PrevDecl ||
2465 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2466 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2467 // There is no prior declaration of this entity, so this
2468 // specialization must be in the same context as the template
2469 // itself.
2470 if (!DC->Equals(SpecializedContext)) {
2471 if (isa<TranslationUnitDecl>(SpecializedContext))
2472 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2473 << EntityKind << Specialized;
2474 else if (isa<NamespaceDecl>(SpecializedContext))
2475 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2476 << EntityKind << Specialized
2477 << cast<NamedDecl>(SpecializedContext);
2478
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002479 S.Diag(Specialized->getLocation(), diag::note_specialized_entity)
2480 << TSK;
Douglas Gregor54888652009-10-07 00:13:32 +00002481 ComplainedAboutScope = true;
2482 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002483 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002484 }
Douglas Gregor54888652009-10-07 00:13:32 +00002485
2486 // Make sure that this redeclaration (or definition) occurs in an enclosing
2487 // namespace. We perform this check for explicit specializations and, in
2488 // C++0x, for explicit instantiations as well (per DR275).
2489 // FIXME: -Wc++0x should make these warnings.
2490 // Note that HandleDeclarator() performs this check for explicit
2491 // specializations of function templates, static data members, and member
2492 // functions, so we skip the check here for those kinds of entities.
2493 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00002494 // Should we refactor that check, so that it occurs later?
2495 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor54888652009-10-07 00:13:32 +00002496 ((TSK == TSK_ExplicitSpecialization &&
2497 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2498 isa<FunctionDecl>(Specialized))) ||
2499 S.getLangOptions().CPlusPlus0x)) {
2500 if (isa<TranslationUnitDecl>(SpecializedContext))
2501 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2502 << EntityKind << Specialized;
2503 else if (isa<NamespaceDecl>(SpecializedContext))
2504 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2505 << EntityKind << Specialized
2506 << cast<NamedDecl>(SpecializedContext);
2507
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002508 S.Diag(Specialized->getLocation(), diag::note_specialized_entity) << TSK;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002509 }
Douglas Gregor54888652009-10-07 00:13:32 +00002510
2511 // FIXME: check for specialization-after-instantiation errors and such.
2512
Douglas Gregorf47b9112009-02-25 22:02:03 +00002513 return false;
2514}
Douglas Gregor54888652009-10-07 00:13:32 +00002515
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002516/// \brief Check the non-type template arguments of a class template
2517/// partial specialization according to C++ [temp.class.spec]p9.
2518///
Douglas Gregor09a30232009-06-12 22:08:06 +00002519/// \param TemplateParams the template parameters of the primary class
2520/// template.
2521///
2522/// \param TemplateArg the template arguments of the class template
2523/// partial specialization.
2524///
2525/// \param MirrorsPrimaryTemplate will be set true if the class
2526/// template partial specialization arguments are identical to the
2527/// implicit template arguments of the primary template. This is not
2528/// necessarily an error (C++0x), and it is left to the caller to diagnose
2529/// this condition when it is an error.
2530///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002531/// \returns true if there was an error, false otherwise.
2532bool Sema::CheckClassTemplatePartialSpecializationArgs(
2533 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002534 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002535 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002536 // FIXME: the interface to this function will have to change to
2537 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002538 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002539
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002540 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002541
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002542 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002543 // Determine whether the template argument list of the partial
2544 // specialization is identical to the implicit argument list of
2545 // the primary template. The caller may need to diagnostic this as
2546 // an error per C++ [temp.class.spec]p9b3.
2547 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002548 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002549 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2550 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002551 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002552 MirrorsPrimaryTemplate = false;
2553 } else if (TemplateTemplateParmDecl *TTP
2554 = dyn_cast<TemplateTemplateParmDecl>(
2555 TemplateParams->getParam(I))) {
2556 // FIXME: We should settle on either Declaration storage or
2557 // Expression storage for template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002558 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor09a30232009-06-12 22:08:06 +00002559 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson40c1d492009-06-13 18:20:51 +00002560 ArgList[I].getAsDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002561 if (!ArgDecl)
Mike Stump11289f42009-09-09 15:08:12 +00002562 if (DeclRefExpr *DRE
Anders Carlsson40c1d492009-06-13 18:20:51 +00002563 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002564 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2565
2566 if (!ArgDecl ||
2567 ArgDecl->getIndex() != TTP->getIndex() ||
2568 ArgDecl->getDepth() != TTP->getDepth())
2569 MirrorsPrimaryTemplate = false;
2570 }
2571 }
2572
Mike Stump11289f42009-09-09 15:08:12 +00002573 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002574 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002575 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002576 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002577 }
2578
Anders Carlsson40c1d492009-06-13 18:20:51 +00002579 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002580 if (!ArgExpr) {
2581 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002582 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002583 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002584
2585 // C++ [temp.class.spec]p8:
2586 // A non-type argument is non-specialized if it is the name of a
2587 // non-type parameter. All other non-type arguments are
2588 // specialized.
2589 //
2590 // Below, we check the two conditions that only apply to
2591 // specialized non-type arguments, so skip any non-specialized
2592 // arguments.
2593 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002594 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002595 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002596 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002597 (Param->getIndex() != NTTP->getIndex() ||
2598 Param->getDepth() != NTTP->getDepth()))
2599 MirrorsPrimaryTemplate = false;
2600
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002601 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002602 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002603
2604 // C++ [temp.class.spec]p9:
2605 // Within the argument list of a class template partial
2606 // specialization, the following restrictions apply:
2607 // -- A partially specialized non-type argument expression
2608 // shall not involve a template parameter of the partial
2609 // specialization except when the argument expression is a
2610 // simple identifier.
2611 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002612 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002613 diag::err_dependent_non_type_arg_in_partial_spec)
2614 << ArgExpr->getSourceRange();
2615 return true;
2616 }
2617
2618 // -- The type of a template parameter corresponding to a
2619 // specialized non-type argument shall not be dependent on a
2620 // parameter of the specialization.
2621 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002622 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002623 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2624 << Param->getType()
2625 << ArgExpr->getSourceRange();
2626 Diag(Param->getLocation(), diag::note_template_param_here);
2627 return true;
2628 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002629
2630 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002631 }
2632
2633 return false;
2634}
2635
Douglas Gregorc08f4892009-03-25 00:13:59 +00002636Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002637Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2638 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002639 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002640 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002641 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002642 SourceLocation TemplateNameLoc,
2643 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002644 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002645 SourceLocation *TemplateArgLocs,
2646 SourceLocation RAngleLoc,
2647 AttributeList *Attr,
2648 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00002649 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00002650
Douglas Gregor67a65642009-02-17 23:15:12 +00002651 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002652 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002653 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002654 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002655
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002656 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00002657 bool isPartialSpecialization = false;
2658
Douglas Gregorf47b9112009-02-25 22:02:03 +00002659 // Check the validity of the template headers that introduce this
2660 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00002661 // FIXME: We probably shouldn't complain about these headers for
2662 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002663 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002664 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2665 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002666 TemplateParameterLists.size(),
2667 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002668 if (TemplateParams && TemplateParams->size() > 0) {
2669 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002670
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002671 // C++ [temp.class.spec]p10:
2672 // The template parameter list of a specialization shall not
2673 // contain default template argument values.
2674 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2675 Decl *Param = TemplateParams->getParam(I);
2676 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2677 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002678 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002679 diag::err_default_arg_in_partial_spec);
2680 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2681 }
2682 } else if (NonTypeTemplateParmDecl *NTTP
2683 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2684 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002685 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002686 diag::err_default_arg_in_partial_spec)
2687 << DefArg->getSourceRange();
2688 NTTP->setDefaultArgument(0);
2689 DefArg->Destroy(Context);
2690 }
2691 } else {
2692 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2693 if (Expr *DefArg = TTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002694 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002695 diag::err_default_arg_in_partial_spec)
2696 << DefArg->getSourceRange();
2697 TTP->setDefaultArgument(0);
2698 DefArg->Destroy(Context);
Douglas Gregord5222052009-06-12 19:43:02 +00002699 }
2700 }
2701 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002702 } else if (!TemplateParams && TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002703 Diag(KWLoc, diag::err_template_spec_needs_header)
2704 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002705 isExplicitSpecialization = true;
2706 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002707
Douglas Gregor67a65642009-02-17 23:15:12 +00002708 // Check that the specialization uses the same tag kind as the
2709 // original template.
2710 TagDecl::TagKind Kind;
2711 switch (TagSpec) {
2712 default: assert(0 && "Unknown tag type!");
2713 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2714 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2715 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2716 }
Douglas Gregord9034f02009-05-14 16:41:31 +00002717 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00002718 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00002719 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00002720 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00002721 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00002722 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00002723 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00002724 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00002725 diag::note_previous_use);
2726 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2727 }
2728
Douglas Gregorc40290e2009-03-09 23:48:35 +00002729 // Translate the parser's template argument list in our AST format.
2730 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2731 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2732
Douglas Gregor67a65642009-02-17 23:15:12 +00002733 // Check that the template argument list is well-formed for this
2734 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002735 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2736 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00002737 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002738 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00002739 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002740 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002741
Mike Stump11289f42009-09-09 15:08:12 +00002742 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00002743 ClassTemplate->getTemplateParameters()->size()) &&
2744 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00002745
Douglas Gregor2373c592009-05-31 09:31:02 +00002746 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00002747 // corresponds to these arguments.
2748 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00002749 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002750 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002751 if (CheckClassTemplatePartialSpecializationArgs(
2752 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002753 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002754 return true;
2755
Douglas Gregor09a30232009-06-12 22:08:06 +00002756 if (MirrorsPrimaryTemplate) {
2757 // C++ [temp.class.spec]p9b3:
2758 //
Mike Stump11289f42009-09-09 15:08:12 +00002759 // -- The argument list of the specialization shall not be identical
2760 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00002761 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00002762 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00002763 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00002764 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00002765 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00002766 ClassTemplate->getIdentifier(),
2767 TemplateNameLoc,
2768 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002769 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00002770 AS_none);
2771 }
2772
Douglas Gregor2208a292009-09-26 20:57:03 +00002773 // FIXME: Diagnose friend partial specializations
2774
Douglas Gregor2373c592009-05-31 09:31:02 +00002775 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00002776 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002777 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002778 Converted.flatSize(),
2779 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002780 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002781 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002782 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002783 Converted.flatSize(),
2784 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00002785 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002786 ClassTemplateSpecializationDecl *PrevDecl = 0;
2787
2788 if (isPartialSpecialization)
2789 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00002790 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00002791 InsertPos);
2792 else
2793 PrevDecl
2794 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00002795
2796 ClassTemplateSpecializationDecl *Specialization = 0;
2797
Douglas Gregorf47b9112009-02-25 22:02:03 +00002798 // Check whether we can declare a class template specialization in
2799 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00002800 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00002801 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
2802 TemplateNameLoc, isPartialSpecialization,
2803 TSK_ExplicitSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002804 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002805
Douglas Gregor15301382009-07-30 17:40:51 +00002806 // The canonical type
2807 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00002808 if (PrevDecl &&
2809 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
2810 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002811 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00002812 // arguments was referenced but not declared, or we're only
2813 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00002814 // declaration node as our own, updating its source location to
2815 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002816 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00002817 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00002818 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00002819 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00002820 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00002821 // Build the canonical type that describes the converted template
2822 // arguments of the class template partial specialization.
2823 CanonType = Context.getTemplateSpecializationType(
2824 TemplateName(ClassTemplate),
2825 Converted.getFlatArguments(),
2826 Converted.flatSize());
2827
Douglas Gregor2373c592009-05-31 09:31:02 +00002828 // Create a new class template partial specialization declaration node.
Mike Stump11289f42009-09-09 15:08:12 +00002829 TemplateParameterList *TemplateParams
Douglas Gregor2373c592009-05-31 09:31:02 +00002830 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2831 ClassTemplatePartialSpecializationDecl *PrevPartial
2832 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002833 ClassTemplatePartialSpecializationDecl *Partial
2834 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00002835 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002836 TemplateNameLoc,
2837 TemplateParams,
2838 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002839 Converted,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002840 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00002841
2842 if (PrevPartial) {
2843 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2844 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2845 } else {
2846 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2847 }
2848 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00002849
2850 // Check that all of the template parameters of the class template
2851 // partial specialization are deducible from the template
2852 // arguments. If not, this class template partial specialization
2853 // will never be used.
2854 llvm::SmallVector<bool, 8> DeducibleParams;
2855 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002856 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2857 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00002858 unsigned NumNonDeducible = 0;
2859 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2860 if (!DeducibleParams[I])
2861 ++NumNonDeducible;
2862
2863 if (NumNonDeducible) {
2864 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2865 << (NumNonDeducible > 1)
2866 << SourceRange(TemplateNameLoc, RAngleLoc);
2867 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2868 if (!DeducibleParams[I]) {
2869 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2870 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00002871 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002872 diag::note_partial_spec_unused_parameter)
2873 << Param->getDeclName();
2874 else
Mike Stump11289f42009-09-09 15:08:12 +00002875 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002876 diag::note_partial_spec_unused_parameter)
2877 << std::string("<anonymous>");
2878 }
2879 }
2880 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002881 } else {
2882 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00002883 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002884 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00002885 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00002886 ClassTemplate->getDeclContext(),
2887 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002888 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002889 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00002890 PrevDecl);
2891
2892 if (PrevDecl) {
2893 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2894 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2895 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002896 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00002897 InsertPos);
2898 }
Douglas Gregor15301382009-07-30 17:40:51 +00002899
2900 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002901 }
2902
Douglas Gregor2208a292009-09-26 20:57:03 +00002903 // If this is not a friend, note that this is an explicit specialization.
2904 if (TUK != TUK_Friend)
2905 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002906
2907 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002908 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002909 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002910 // FIXME: Should also handle explicit specialization after implicit
2911 // instantiation with a special diagnostic.
Douglas Gregor67a65642009-02-17 23:15:12 +00002912 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002913 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00002914 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00002915 Diag(Def->getLocation(), diag::note_previous_definition);
2916 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00002917 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002918 }
2919 }
2920
Douglas Gregord56a91e2009-02-26 22:19:44 +00002921 // Build the fully-sugared type for this class template
2922 // specialization as the user wrote in the specialization
2923 // itself. This means that we'll pretty-print the type retrieved
2924 // from the specialization's declaration the way that the user
2925 // actually wrote the specialization, rather than formatting the
2926 // name based on the "canonical" representation used to store the
2927 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002928 QualType WrittenTy
2929 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002930 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00002931 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00002932 CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00002933 if (TUK != TUK_Friend)
2934 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002935 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00002936
Douglas Gregor1e249f82009-02-25 22:18:32 +00002937 // C++ [temp.expl.spec]p9:
2938 // A template explicit specialization is in the scope of the
2939 // namespace in which the template was defined.
2940 //
2941 // We actually implement this paragraph where we set the semantic
2942 // context (in the creation of the ClassTemplateSpecializationDecl),
2943 // but we also maintain the lexical context where the actual
2944 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00002945 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00002946
Douglas Gregor67a65642009-02-17 23:15:12 +00002947 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002948 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00002949 Specialization->startDefinition();
2950
Douglas Gregor2208a292009-09-26 20:57:03 +00002951 if (TUK == TUK_Friend) {
2952 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
2953 TemplateNameLoc,
2954 WrittenTy.getTypePtr(),
2955 /*FIXME:*/KWLoc);
2956 Friend->setAccess(AS_public);
2957 CurContext->addDecl(Friend);
2958 } else {
2959 // Add the specialization into its lexical context, so that it can
2960 // be seen when iterating through the list of declarations in that
2961 // context. However, specializations are not found by name lookup.
2962 CurContext->addDecl(Specialization);
2963 }
Chris Lattner83f095c2009-03-28 19:18:32 +00002964 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002965}
Douglas Gregor333489b2009-03-27 23:10:48 +00002966
Mike Stump11289f42009-09-09 15:08:12 +00002967Sema::DeclPtrTy
2968Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002969 MultiTemplateParamsArg TemplateParameterLists,
2970 Declarator &D) {
2971 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2972}
2973
Mike Stump11289f42009-09-09 15:08:12 +00002974Sema::DeclPtrTy
2975Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002976 MultiTemplateParamsArg TemplateParameterLists,
2977 Declarator &D) {
2978 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2979 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2980 "Not a function declarator!");
2981 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00002982
Douglas Gregor17a7c122009-06-24 00:54:41 +00002983 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00002984 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00002985 }
Mike Stump11289f42009-09-09 15:08:12 +00002986
Douglas Gregor17a7c122009-06-24 00:54:41 +00002987 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002988
2989 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002990 move(TemplateParameterLists),
2991 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002992 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00002993 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00002994 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002995 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00002996 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2997 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002998 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00002999}
3000
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003001/// \brief Perform semantic analysis for the given function template
3002/// specialization.
3003///
3004/// This routine performs all of the semantic analysis required for an
3005/// explicit function template specialization. On successful completion,
3006/// the function declaration \p FD will become a function template
3007/// specialization.
3008///
3009/// \param FD the function declaration, which will be updated to become a
3010/// function template specialization.
3011///
3012/// \param HasExplicitTemplateArgs whether any template arguments were
3013/// explicitly provided.
3014///
3015/// \param LAngleLoc the location of the left angle bracket ('<'), if
3016/// template arguments were explicitly provided.
3017///
3018/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3019/// if any.
3020///
3021/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3022/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3023/// true as in, e.g., \c void sort<>(char*, char*);
3024///
3025/// \param RAngleLoc the location of the right angle bracket ('>'), if
3026/// template arguments were explicitly provided.
3027///
3028/// \param PrevDecl the set of declarations that
3029bool
3030Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3031 bool HasExplicitTemplateArgs,
3032 SourceLocation LAngleLoc,
3033 const TemplateArgument *ExplicitTemplateArgs,
3034 unsigned NumExplicitTemplateArgs,
3035 SourceLocation RAngleLoc,
3036 NamedDecl *&PrevDecl) {
3037 // The set of function template specializations that could match this
3038 // explicit function template specialization.
3039 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3040 CandidateSet Candidates;
3041
3042 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3043 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3044 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3045 // Only consider templates found within the same semantic lookup scope as
3046 // FD.
3047 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3048 continue;
3049
3050 // C++ [temp.expl.spec]p11:
3051 // A trailing template-argument can be left unspecified in the
3052 // template-id naming an explicit function template specialization
3053 // provided it can be deduced from the function argument type.
3054 // Perform template argument deduction to determine whether we may be
3055 // specializing this template.
3056 // FIXME: It is somewhat wasteful to build
3057 TemplateDeductionInfo Info(Context);
3058 FunctionDecl *Specialization = 0;
3059 if (TemplateDeductionResult TDK
3060 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3061 ExplicitTemplateArgs,
3062 NumExplicitTemplateArgs,
3063 FD->getType(),
3064 Specialization,
3065 Info)) {
3066 // FIXME: Template argument deduction failed; record why it failed, so
3067 // that we can provide nifty diagnostics.
3068 (void)TDK;
3069 continue;
3070 }
3071
3072 // Record this candidate.
3073 Candidates.push_back(Specialization);
3074 }
3075 }
3076
Douglas Gregor5de279c2009-09-26 03:41:46 +00003077 // Find the most specialized function template.
3078 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3079 Candidates.size(),
3080 TPOC_Other,
3081 FD->getLocation(),
3082 PartialDiagnostic(diag::err_function_template_spec_no_match)
3083 << FD->getDeclName(),
3084 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3085 << FD->getDeclName() << HasExplicitTemplateArgs,
3086 PartialDiagnostic(diag::note_function_template_spec_matched));
3087 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003088 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003089
3090 // FIXME: Check if the prior specialization has a point of instantiation.
3091 // If so, we have run afoul of C++ [temp.expl.spec]p6.
3092
Douglas Gregor54888652009-10-07 00:13:32 +00003093 // Check the scope of this explicit specialization.
3094 if (CheckTemplateSpecializationScope(*this,
3095 Specialization->getPrimaryTemplate(),
3096 Specialization, FD->getLocation(),
3097 false, TSK_ExplicitSpecialization))
3098 return true;
3099
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003100 // Mark the prior declaration as an explicit specialization, so that later
3101 // clients know that this is an explicit specialization.
3102 // FIXME: Check for prior explicit instantiations?
3103 Specialization->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
3104
3105 // Turn the given function declaration into a function template
3106 // specialization, with the template arguments from the previous
3107 // specialization.
3108 FD->setFunctionTemplateSpecialization(Context,
3109 Specialization->getPrimaryTemplate(),
3110 new (Context) TemplateArgumentList(
3111 *Specialization->getTemplateSpecializationArgs()),
3112 /*InsertPos=*/0,
3113 TSK_ExplicitSpecialization);
3114
3115 // The "previous declaration" for this function template specialization is
3116 // the prior function template specialization.
3117 PrevDecl = Specialization;
3118 return false;
3119}
3120
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003121/// \brief Perform semantic analysis for the given member function
3122/// specialization.
3123///
3124/// This routine performs all of the semantic analysis required for an
3125/// explicit member function specialization. On successful completion,
3126/// the function declaration \p FD will become a member function
3127/// specialization.
3128///
3129/// \param FD the function declaration, which will be updated to become a
3130/// function template specialization.
3131///
3132/// \param PrevDecl the set of declarations, one of which may be specialized
3133/// by this function specialization.
3134bool
3135Sema::CheckMemberFunctionSpecialization(CXXMethodDecl *FD,
3136 NamedDecl *&PrevDecl) {
3137 // Try to find the member function we are instantiating.
3138 CXXMethodDecl *Instantiation = 0;
3139 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3140 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl)) {
3141 if (Context.hasSameType(FD->getType(), Method->getType())) {
3142 Instantiation = Method;
3143 break;
3144 }
3145 }
3146 }
3147
3148 if (!Instantiation) {
3149 // There is no previous declaration that matches. Since member function
3150 // specializations are always out-of-line, the caller will complain about
3151 // this mismatch later.
3152 return false;
3153 }
3154
3155 // FIXME: Check if the prior declaration has a point of instantiation.
3156 // If so, we have run afoul of C++ [temp.expl.spec]p6.
3157
3158 // Make sure that this is a specialization of a member function.
3159 FunctionDecl *FunctionInTemplate
3160 = Instantiation->getInstantiatedFromMemberFunction();
3161 if (!FunctionInTemplate) {
3162 Diag(FD->getLocation(), diag::err_function_spec_not_instantiated)
3163 << FD;
3164 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3165 return true;
3166 }
3167
3168 // Check the scope of this explicit specialization.
3169 if (CheckTemplateSpecializationScope(*this,
3170 FunctionInTemplate,
3171 Instantiation, FD->getLocation(),
3172 false, TSK_ExplicitSpecialization))
3173 return true;
3174
3175 // FIXME: Mark the new declaration as a member function specialization.
3176 // We may also want to mark the original instantiation as having been
3177 // explicitly specialized.
3178
3179 // Save the caller the trouble of having to figure out which declaration
3180 // this specialization matches.
3181 PrevDecl = Instantiation;
3182 return false;
3183}
3184
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003185// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003186// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003187Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003188Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003189 SourceLocation ExternLoc,
3190 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003191 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003192 SourceLocation KWLoc,
3193 const CXXScopeSpec &SS,
3194 TemplateTy TemplateD,
3195 SourceLocation TemplateNameLoc,
3196 SourceLocation LAngleLoc,
3197 ASTTemplateArgsPtr TemplateArgsIn,
3198 SourceLocation *TemplateArgLocs,
3199 SourceLocation RAngleLoc,
3200 AttributeList *Attr) {
3201 // Find the class template we're specializing
3202 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003203 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003204 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3205
3206 // Check that the specialization uses the same tag kind as the
3207 // original template.
3208 TagDecl::TagKind Kind;
3209 switch (TagSpec) {
3210 default: assert(0 && "Unknown tag type!");
3211 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3212 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3213 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3214 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003215 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003216 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003217 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003218 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003219 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003220 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003221 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003222 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003223 diag::note_previous_use);
3224 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3225 }
3226
Douglas Gregor54888652009-10-07 00:13:32 +00003227 TemplateSpecializationKind TSK
3228 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3229 : TSK_ExplicitInstantiationDeclaration;
3230
Douglas Gregora1f49972009-05-13 00:25:59 +00003231 // Translate the parser's template argument list in our AST format.
3232 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3233 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3234
3235 // Check that the template argument list is well-formed for this
3236 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003237 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3238 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003239 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003240 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003241 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003242 return true;
3243
Mike Stump11289f42009-09-09 15:08:12 +00003244 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003245 ClassTemplate->getTemplateParameters()->size()) &&
3246 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003247
Douglas Gregora1f49972009-05-13 00:25:59 +00003248 // Find the class template specialization declaration that
3249 // corresponds to these arguments.
3250 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003251 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003252 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003253 Converted.flatSize(),
3254 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003255 void *InsertPos = 0;
3256 ClassTemplateSpecializationDecl *PrevDecl
3257 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3258
Douglas Gregor54888652009-10-07 00:13:32 +00003259 // C++0x [temp.explicit]p2:
3260 // [...] An explicit instantiation shall appear in an enclosing
3261 // namespace of its template. [...]
3262 //
3263 // This is C++ DR 275.
3264 if (CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
3265 TemplateNameLoc, false,
3266 TSK))
3267 return true;
3268
Douglas Gregora1f49972009-05-13 00:25:59 +00003269 ClassTemplateSpecializationDecl *Specialization = 0;
3270
Douglas Gregorf61eca92009-05-13 18:28:20 +00003271 bool SpecializationRequiresInstantiation = true;
Douglas Gregora1f49972009-05-13 00:25:59 +00003272 if (PrevDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003273 if (PrevDecl->getSpecializationKind()
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003274 == TSK_ExplicitInstantiationDefinition) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003275 // This particular specialization has already been declared or
3276 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorf61eca92009-05-13 18:28:20 +00003277 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
3278 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003279 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003280 diag::note_previous_explicit_instantiation);
Douglas Gregora1f49972009-05-13 00:25:59 +00003281 return DeclPtrTy::make(PrevDecl);
3282 }
3283
Douglas Gregorf61eca92009-05-13 18:28:20 +00003284 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003285 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorf61eca92009-05-13 18:28:20 +00003286 // For a given set of template parameters, if an explicit
3287 // instantiation of a template appears after a declaration of
3288 // an explicit specialization for that template, the explicit
3289 // instantiation has no effect.
3290 if (!getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00003291 Diag(TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003292 diag::ext_explicit_instantiation_after_specialization)
3293 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003294 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003295 diag::note_previous_template_specialization);
3296 }
3297
3298 // Create a new class template specialization declaration node
3299 // for this explicit specialization. This node is only used to
3300 // record the existence of this explicit instantiation for
3301 // accurate reproduction of the source code; we don't actually
3302 // use it for anything, since it is semantically irrelevant.
3303 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003304 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003305 ClassTemplate->getDeclContext(),
3306 TemplateNameLoc,
3307 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003308 Converted, 0);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003309 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003310 CurContext->addDecl(Specialization);
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003311 return DeclPtrTy::make(PrevDecl);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003312 }
3313
3314 // If we have already (implicitly) instantiated this
3315 // specialization, there is less work to do.
3316 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
3317 SpecializationRequiresInstantiation = false;
3318
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003319 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3320 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3321 // Since the only prior class template specialization with these
3322 // arguments was referenced but not declared, reuse that
3323 // declaration node as our own, updating its source location to
3324 // reflect our new declaration.
3325 Specialization = PrevDecl;
3326 Specialization->setLocation(TemplateNameLoc);
3327 PrevDecl = 0;
3328 }
3329 }
3330
3331 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003332 // Create a new class template specialization declaration node for
3333 // this explicit specialization.
3334 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003335 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003336 ClassTemplate->getDeclContext(),
3337 TemplateNameLoc,
3338 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003339 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003340
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003341 if (PrevDecl) {
3342 // Remove the previous declaration from the folding set, since we want
3343 // to introduce a new declaration.
3344 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3345 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3346 }
3347
3348 // Insert the new specialization.
3349 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003350 }
3351
3352 // Build the fully-sugared type for this explicit instantiation as
3353 // the user wrote in the explicit instantiation itself. This means
3354 // that we'll pretty-print the type retrieved from the
3355 // specialization's declaration the way that the user actually wrote
3356 // the explicit instantiation, rather than formatting the name based
3357 // on the "canonical" representation used to store the template
3358 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003359 QualType WrittenTy
3360 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003361 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003362 TemplateArgs.size(),
3363 Context.getTypeDeclType(Specialization));
3364 Specialization->setTypeAsWritten(WrittenTy);
3365 TemplateArgsIn.release();
3366
3367 // Add the explicit instantiation into its lexical context. However,
3368 // since explicit instantiations are never found by name lookup, we
3369 // just put it into the declaration context directly.
3370 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003371 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003372
John McCall1806c272009-09-11 07:25:08 +00003373 Specialization->setPointOfInstantiation(TemplateNameLoc);
3374
Douglas Gregora1f49972009-05-13 00:25:59 +00003375 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003376 // A definition of a class template or class member template
3377 // shall be in scope at the point of the explicit instantiation of
3378 // the class template or class member template.
3379 //
3380 // This check comes when we actually try to perform the
3381 // instantiation.
Douglas Gregor67da0d92009-05-15 17:59:04 +00003382 if (SpecializationRequiresInstantiation)
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003383 InstantiateClassTemplateSpecialization(Specialization, TSK);
Douglas Gregor85673582009-05-18 17:01:57 +00003384 else // Instantiate the members of this class template specialization.
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003385 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization,
3386 TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003387
3388 return DeclPtrTy::make(Specialization);
3389}
3390
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003391// Explicit instantiation of a member class of a class template.
3392Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003393Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003394 SourceLocation ExternLoc,
3395 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003396 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003397 SourceLocation KWLoc,
3398 const CXXScopeSpec &SS,
3399 IdentifierInfo *Name,
3400 SourceLocation NameLoc,
3401 AttributeList *Attr) {
3402
Douglas Gregord6ab8742009-05-28 23:31:59 +00003403 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003404 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00003405 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00003406 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00003407 MultiTemplateParamsArg(*this, 0, 0),
3408 Owned, IsDependent);
3409 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3410
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003411 if (!TagD)
3412 return true;
3413
3414 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3415 if (Tag->isEnum()) {
3416 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3417 << Context.getTypeDeclType(Tag);
3418 return true;
3419 }
3420
Douglas Gregorb8006faf2009-05-27 17:30:49 +00003421 if (Tag->isInvalidDecl())
3422 return true;
3423
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003424 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3425 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3426 if (!Pattern) {
3427 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3428 << Context.getTypeDeclType(Record);
3429 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3430 return true;
3431 }
3432
3433 // C++0x [temp.explicit]p2:
3434 // [...] An explicit instantiation shall appear in an enclosing
3435 // namespace of its template. [...]
3436 //
3437 // This is C++ DR 275.
3438 if (getLangOptions().CPlusPlus0x) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003439 // FIXME: In C++98, we would like to turn these errors into warnings,
3440 // dependent on a -Wc++0x flag.
Mike Stump11289f42009-09-09 15:08:12 +00003441 DeclContext *PatternContext
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003442 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
3443 if (!CurContext->Encloses(PatternContext)) {
3444 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
3445 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
3446 Diag(Pattern->getLocation(), diag::note_previous_declaration);
3447 }
3448 }
3449
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003450 TemplateSpecializationKind TSK
Mike Stump11289f42009-09-09 15:08:12 +00003451 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003452 : TSK_ExplicitInstantiationDeclaration;
Mike Stump11289f42009-09-09 15:08:12 +00003453
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003454 if (!Record->getDefinition(Context)) {
3455 // If the class has a definition, instantiate it (and all of its
3456 // members, recursively).
3457 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
Mike Stump11289f42009-09-09 15:08:12 +00003458 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregorb4850462009-05-14 23:26:13 +00003459 getTemplateInstantiationArgs(Record),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003460 TSK))
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003461 return true;
John McCall76d824f2009-08-25 22:02:44 +00003462 } else // Instantiate all of the members of the class.
Mike Stump11289f42009-09-09 15:08:12 +00003463 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003464 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003465
Mike Stump87c57ac2009-05-16 07:39:55 +00003466 // FIXME: We don't have any representation for explicit instantiations of
3467 // member classes. Such a representation is not needed for compilation, but it
3468 // should be available for clients that want to see all of the declarations in
3469 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003470 return TagD;
3471}
3472
Douglas Gregor450f00842009-09-25 18:43:00 +00003473Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
3474 SourceLocation ExternLoc,
3475 SourceLocation TemplateLoc,
3476 Declarator &D) {
3477 // Explicit instantiations always require a name.
3478 DeclarationName Name = GetNameForDeclarator(D);
3479 if (!Name) {
3480 if (!D.isInvalidType())
3481 Diag(D.getDeclSpec().getSourceRange().getBegin(),
3482 diag::err_explicit_instantiation_requires_name)
3483 << D.getDeclSpec().getSourceRange()
3484 << D.getSourceRange();
3485
3486 return true;
3487 }
3488
3489 // The scope passed in may not be a decl scope. Zip up the scope tree until
3490 // we find one that is.
3491 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3492 (S->getFlags() & Scope::TemplateParamScope) != 0)
3493 S = S->getParent();
3494
3495 // Determine the type of the declaration.
3496 QualType R = GetTypeForDeclarator(D, S, 0);
3497 if (R.isNull())
3498 return true;
3499
3500 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3501 // Cannot explicitly instantiate a typedef.
3502 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
3503 << Name;
3504 return true;
3505 }
3506
3507 // Determine what kind of explicit instantiation we have.
3508 TemplateSpecializationKind TSK
3509 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3510 : TSK_ExplicitInstantiationDeclaration;
3511
3512 LookupResult Previous = LookupParsedName(S, &D.getCXXScopeSpec(),
3513 Name, LookupOrdinaryName);
3514
3515 if (!R->isFunctionType()) {
3516 // C++ [temp.explicit]p1:
3517 // A [...] static data member of a class template can be explicitly
3518 // instantiated from the member definition associated with its class
3519 // template.
3520 if (Previous.isAmbiguous()) {
3521 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
3522 D.getSourceRange());
3523 }
3524
3525 VarDecl *Prev = dyn_cast_or_null<VarDecl>(Previous.getAsDecl());
3526 if (!Prev || !Prev->isStaticDataMember()) {
3527 // We expect to see a data data member here.
3528 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
3529 << Name;
3530 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3531 P != PEnd; ++P)
3532 Diag(P->getLocation(), diag::note_explicit_instantiation_here);
3533 return true;
3534 }
3535
3536 if (!Prev->getInstantiatedFromStaticDataMember()) {
3537 // FIXME: Check for explicit specialization?
3538 Diag(D.getIdentifierLoc(),
3539 diag::err_explicit_instantiation_data_member_not_instantiated)
3540 << Prev;
3541 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
3542 // FIXME: Can we provide a note showing where this was declared?
3543 return true;
3544 }
3545
3546 // Instantiate static data member.
3547 // FIXME: Note that this is an explicit instantiation.
3548 if (TSK == TSK_ExplicitInstantiationDefinition)
3549 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false);
3550
3551 // FIXME: Create an ExplicitInstantiation node?
3552 return DeclPtrTy();
3553 }
3554
Douglas Gregor0e876e02009-09-25 23:53:26 +00003555 // If the declarator is a template-id, translate the parser's template
3556 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00003557 bool HasExplicitTemplateArgs = false;
3558 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3559 if (D.getKind() == Declarator::DK_TemplateId) {
3560 TemplateIdAnnotation *TemplateId = D.getTemplateId();
3561 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3562 TemplateId->getTemplateArgs(),
3563 TemplateId->getTemplateArgIsType(),
3564 TemplateId->NumArgs);
3565 translateTemplateArguments(TemplateArgsPtr,
3566 TemplateId->getTemplateArgLocations(),
3567 TemplateArgs);
3568 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00003569 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00003570 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00003571
Douglas Gregor450f00842009-09-25 18:43:00 +00003572 // C++ [temp.explicit]p1:
3573 // A [...] function [...] can be explicitly instantiated from its template.
3574 // A member function [...] of a class template can be explicitly
3575 // instantiated from the member definition associated with its class
3576 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00003577 llvm::SmallVector<FunctionDecl *, 8> Matches;
3578 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3579 P != PEnd; ++P) {
3580 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00003581 if (!HasExplicitTemplateArgs) {
3582 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
3583 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
3584 Matches.clear();
3585 Matches.push_back(Method);
3586 break;
3587 }
Douglas Gregor450f00842009-09-25 18:43:00 +00003588 }
3589 }
3590
3591 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
3592 if (!FunTmpl)
3593 continue;
3594
3595 TemplateDeductionInfo Info(Context);
3596 FunctionDecl *Specialization = 0;
3597 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00003598 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3599 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00003600 R, Specialization, Info)) {
3601 // FIXME: Keep track of almost-matches?
3602 (void)TDK;
3603 continue;
3604 }
3605
3606 Matches.push_back(Specialization);
3607 }
3608
3609 // Find the most specialized function template specialization.
3610 FunctionDecl *Specialization
3611 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
3612 D.getIdentifierLoc(),
3613 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
3614 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
3615 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
3616
3617 if (!Specialization)
3618 return true;
3619
3620 switch (Specialization->getTemplateSpecializationKind()) {
3621 case TSK_Undeclared:
3622 Diag(D.getIdentifierLoc(),
3623 diag::err_explicit_instantiation_member_function_not_instantiated)
3624 << Specialization
3625 << (Specialization->getTemplateSpecializationKind() ==
3626 TSK_ExplicitSpecialization);
3627 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
3628 return true;
3629
3630 case TSK_ExplicitSpecialization:
3631 // C++ [temp.explicit]p4:
3632 // For a given set of template parameters, if an explicit instantiation
3633 // of a template appears after a declaration of an explicit
3634 // specialization for that template, the explicit instantiation has no
3635 // effect.
3636 break;
3637
3638 case TSK_ExplicitInstantiationDefinition:
3639 // FIXME: Check that we aren't trying to perform an explicit instantiation
3640 // declaration now.
3641 // Fall through
3642
3643 case TSK_ImplicitInstantiation:
3644 case TSK_ExplicitInstantiationDeclaration:
3645 // Instantiate the function, if this is an explicit instantiation
3646 // definition.
3647 if (TSK == TSK_ExplicitInstantiationDefinition)
3648 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
3649 false);
3650
3651 // FIXME: setTemplateSpecializationKind doesn't (yet) work for
3652 // non-templated member functions.
3653 if (!Specialization->getPrimaryTemplate())
3654 break;
3655
3656 Specialization->setTemplateSpecializationKind(TSK);
3657 break;
3658 }
3659
3660 // FIXME: Create some kind of ExplicitInstantiationDecl here.
3661 return DeclPtrTy();
3662}
3663
Douglas Gregor333489b2009-03-27 23:10:48 +00003664Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00003665Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3666 const CXXScopeSpec &SS, IdentifierInfo *Name,
3667 SourceLocation TagLoc, SourceLocation NameLoc) {
3668 // This has to hold, because SS is expected to be defined.
3669 assert(Name && "Expected a name in a dependent tag");
3670
3671 NestedNameSpecifier *NNS
3672 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3673 if (!NNS)
3674 return true;
3675
3676 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
3677 if (T.isNull())
3678 return true;
3679
3680 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
3681 QualType ElabType = Context.getElaboratedType(T, TagKind);
3682
3683 return ElabType.getAsOpaquePtr();
3684}
3685
3686Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00003687Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3688 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00003689 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00003690 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3691 if (!NNS)
3692 return true;
3693
3694 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003695 if (T.isNull())
3696 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00003697 return T.getAsOpaquePtr();
3698}
3699
Douglas Gregordce2b622009-04-01 00:28:59 +00003700Sema::TypeResult
3701Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3702 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003703 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003704 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00003705 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00003706 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00003707 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00003708 assert(TemplateId && "Expected a template specialization type");
3709
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003710 if (computeDeclContext(SS, false)) {
3711 // If we can compute a declaration context, then the "typename"
3712 // keyword was superfluous. Just build a QualifiedNameType to keep
3713 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00003714
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003715 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
3716 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
3717 }
Mike Stump11289f42009-09-09 15:08:12 +00003718
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003719 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00003720}
3721
Douglas Gregor333489b2009-03-27 23:10:48 +00003722/// \brief Build the type that describes a C++ typename specifier,
3723/// e.g., "typename T::type".
3724QualType
3725Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
3726 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003727 CXXRecordDecl *CurrentInstantiation = 0;
3728 if (NNS->isDependent()) {
3729 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00003730
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003731 // If the nested-name-specifier does not refer to the current
3732 // instantiation, then build a typename type.
3733 if (!CurrentInstantiation)
3734 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00003735
Douglas Gregorc707da62009-09-02 13:12:51 +00003736 // The nested-name-specifier refers to the current instantiation, so the
3737 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00003738 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00003739 // extraneous "typename" keywords, and we retroactively apply this DR to
3740 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003741 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003742
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003743 DeclContext *Ctx = 0;
3744
3745 if (CurrentInstantiation)
3746 Ctx = CurrentInstantiation;
3747 else {
3748 CXXScopeSpec SS;
3749 SS.setScopeRep(NNS);
3750 SS.setRange(Range);
3751 if (RequireCompleteDeclContext(SS))
3752 return QualType();
3753
3754 Ctx = computeDeclContext(SS);
3755 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003756 assert(Ctx && "No declaration context?");
3757
3758 DeclarationName Name(&II);
Mike Stump11289f42009-09-09 15:08:12 +00003759 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
Douglas Gregor333489b2009-03-27 23:10:48 +00003760 false);
3761 unsigned DiagID = 0;
3762 Decl *Referenced = 0;
3763 switch (Result.getKind()) {
3764 case LookupResult::NotFound:
3765 if (Ctx->isTranslationUnit())
3766 DiagID = diag::err_typename_nested_not_found_global;
3767 else
3768 DiagID = diag::err_typename_nested_not_found;
3769 break;
3770
3771 case LookupResult::Found:
3772 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3773 // We found a type. Build a QualifiedNameType, since the
3774 // typename-specifier was just sugar. FIXME: Tell
3775 // QualifiedNameType that it has a "typename" prefix.
3776 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3777 }
3778
3779 DiagID = diag::err_typename_nested_not_type;
3780 Referenced = Result.getAsDecl();
3781 break;
3782
3783 case LookupResult::FoundOverloaded:
3784 DiagID = diag::err_typename_nested_not_type;
3785 Referenced = *Result.begin();
3786 break;
3787
3788 case LookupResult::AmbiguousBaseSubobjectTypes:
3789 case LookupResult::AmbiguousBaseSubobjects:
3790 case LookupResult::AmbiguousReference:
3791 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3792 return QualType();
3793 }
3794
3795 // If we get here, it's because name lookup did not find a
3796 // type. Emit an appropriate diagnostic and return an error.
3797 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3798 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3799 else
3800 Diag(Range.getEnd(), DiagID) << Range << Name;
3801 if (Referenced)
3802 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3803 << Name;
3804 return QualType();
3805}
Douglas Gregor15acfb92009-08-06 16:20:37 +00003806
3807namespace {
3808 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00003809 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3810 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00003811 SourceLocation Loc;
3812 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00003813
Douglas Gregor15acfb92009-08-06 16:20:37 +00003814 public:
Mike Stump11289f42009-09-09 15:08:12 +00003815 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00003816 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003817 DeclarationName Entity)
3818 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00003819 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00003820
3821 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00003822 /// transformed.
3823 ///
3824 /// For the purposes of type reconstruction, a type has already been
3825 /// transformed if it is NULL or if it is not dependent.
3826 bool AlreadyTransformed(QualType T) {
3827 return T.isNull() || !T->isDependentType();
3828 }
Mike Stump11289f42009-09-09 15:08:12 +00003829
3830 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00003831 /// rebuilt.
3832 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00003833
Douglas Gregor15acfb92009-08-06 16:20:37 +00003834 /// \brief Returns the name of the entity whose type is being rebuilt.
3835 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00003836
Douglas Gregor15acfb92009-08-06 16:20:37 +00003837 /// \brief Transforms an expression by returning the expression itself
3838 /// (an identity function).
3839 ///
3840 /// FIXME: This is completely unsafe; we will need to actually clone the
3841 /// expressions.
3842 Sema::OwningExprResult TransformExpr(Expr *E) {
3843 return getSema().Owned(E);
3844 }
Mike Stump11289f42009-09-09 15:08:12 +00003845
Douglas Gregor15acfb92009-08-06 16:20:37 +00003846 /// \brief Transforms a typename type by determining whether the type now
3847 /// refers to a member of the current instantiation, and then
3848 /// type-checking and building a QualifiedNameType (when possible).
3849 QualType TransformTypenameType(const TypenameType *T);
3850 };
3851}
3852
Mike Stump11289f42009-09-09 15:08:12 +00003853QualType
Douglas Gregor15acfb92009-08-06 16:20:37 +00003854CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3855 NestedNameSpecifier *NNS
3856 = TransformNestedNameSpecifier(T->getQualifier(),
3857 /*FIXME:*/SourceRange(getBaseLocation()));
3858 if (!NNS)
3859 return QualType();
3860
3861 // If the nested-name-specifier did not change, and we cannot compute the
3862 // context corresponding to the nested-name-specifier, then this
3863 // typename type will not change; exit early.
3864 CXXScopeSpec SS;
3865 SS.setRange(SourceRange(getBaseLocation()));
3866 SS.setScopeRep(NNS);
3867 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3868 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003869
3870 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00003871 // QualifiedNameType.
3872 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00003873 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00003874 = TransformType(QualType(TemplateId, 0));
3875 if (NewTemplateId.isNull())
3876 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003877
Douglas Gregor15acfb92009-08-06 16:20:37 +00003878 if (NNS == T->getQualifier() &&
3879 NewTemplateId == QualType(TemplateId, 0))
3880 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003881
Douglas Gregor15acfb92009-08-06 16:20:37 +00003882 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3883 }
Mike Stump11289f42009-09-09 15:08:12 +00003884
Douglas Gregor15acfb92009-08-06 16:20:37 +00003885 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3886}
3887
3888/// \brief Rebuilds a type within the context of the current instantiation.
3889///
Mike Stump11289f42009-09-09 15:08:12 +00003890/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00003891/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00003892/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00003893/// partial specialization thereof). This routine will rebuild that type now
3894/// that we have entered the declarator's scope, which may produce different
3895/// canonical types, e.g.,
3896///
3897/// \code
3898/// template<typename T>
3899/// struct X {
3900/// typedef T* pointer;
3901/// pointer data();
3902/// };
3903///
3904/// template<typename T>
3905/// typename X<T>::pointer X<T>::data() { ... }
3906/// \endcode
3907///
3908/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3909/// since we do not know that we can look into X<T> when we parsed the type.
3910/// This function will rebuild the type, performing the lookup of "pointer"
3911/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3912/// as the canonical type of T*, allowing the return types of the out-of-line
3913/// definition and the declaration to match.
3914QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3915 DeclarationName Name) {
3916 if (T.isNull() || !T->isDependentType())
3917 return T;
Mike Stump11289f42009-09-09 15:08:12 +00003918
Douglas Gregor15acfb92009-08-06 16:20:37 +00003919 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3920 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00003921}
Douglas Gregorbe999392009-09-15 16:23:51 +00003922
3923/// \brief Produces a formatted string that describes the binding of
3924/// template parameters to template arguments.
3925std::string
3926Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3927 const TemplateArgumentList &Args) {
3928 std::string Result;
3929
3930 if (!Params || Params->size() == 0)
3931 return Result;
3932
3933 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3934 if (I == 0)
3935 Result += "[with ";
3936 else
3937 Result += ", ";
3938
3939 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
3940 Result += Id->getName();
3941 } else {
3942 Result += '$';
3943 Result += llvm::utostr(I);
3944 }
3945
3946 Result += " = ";
3947
3948 switch (Args[I].getKind()) {
3949 case TemplateArgument::Null:
3950 Result += "<no value>";
3951 break;
3952
3953 case TemplateArgument::Type: {
3954 std::string TypeStr;
3955 Args[I].getAsType().getAsStringInternal(TypeStr,
3956 Context.PrintingPolicy);
3957 Result += TypeStr;
3958 break;
3959 }
3960
3961 case TemplateArgument::Declaration: {
3962 bool Unnamed = true;
3963 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
3964 if (ND->getDeclName()) {
3965 Unnamed = false;
3966 Result += ND->getNameAsString();
3967 }
3968 }
3969
3970 if (Unnamed) {
3971 Result += "<anonymous>";
3972 }
3973 break;
3974 }
3975
3976 case TemplateArgument::Integral: {
3977 Result += Args[I].getAsIntegral()->toString(10);
3978 break;
3979 }
3980
3981 case TemplateArgument::Expression: {
3982 assert(false && "No expressions in deduced template arguments!");
3983 Result += "<expression>";
3984 break;
3985 }
3986
3987 case TemplateArgument::Pack:
3988 // FIXME: Format template argument packs
3989 Result += "<template argument pack>";
3990 break;
3991 }
3992 }
3993
3994 Result += ']';
3995 return Result;
3996}