blob: 72274525fd07221c54af6659632eb0eb0f9e65db [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000020#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000021#include "llvm/Support/Compiler.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000022#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000023using namespace clang;
24
Douglas Gregorb7bfe792009-09-02 22:59:36 +000025/// \brief Determine whether the declaration found is acceptable as the name
26/// of a template and, if so, return that template declaration. Otherwise,
27/// returns NULL.
28static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
29 if (!D)
30 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000031
Douglas Gregorb7bfe792009-09-02 22:59:36 +000032 if (isa<TemplateDecl>(D))
33 return D;
Mike Stump11289f42009-09-09 15:08:12 +000034
Douglas Gregorb7bfe792009-09-02 22:59:36 +000035 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
36 // C++ [temp.local]p1:
37 // Like normal (non-template) classes, class templates have an
38 // injected-class-name (Clause 9). The injected-class-name
39 // can be used with or without a template-argument-list. When
40 // it is used without a template-argument-list, it is
41 // equivalent to the injected-class-name followed by the
42 // template-parameters of the class template enclosed in
43 // <>. When it is used with a template-argument-list, it
44 // refers to the specified class template specialization,
45 // which could be the current specialization or another
46 // specialization.
47 if (Record->isInjectedClassName()) {
48 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
49 if (Record->getDescribedClassTemplate())
50 return Record->getDescribedClassTemplate();
51
52 if (ClassTemplateSpecializationDecl *Spec
53 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
54 return Spec->getSpecializedTemplate();
55 }
Mike Stump11289f42009-09-09 15:08:12 +000056
Douglas Gregorb7bfe792009-09-02 22:59:36 +000057 return 0;
58 }
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregorb7bfe792009-09-02 22:59:36 +000060 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
61 if (!Ovl)
62 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000063
Douglas Gregorb7bfe792009-09-02 22:59:36 +000064 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
65 FEnd = Ovl->function_end();
66 F != FEnd; ++F) {
67 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
68 // We've found a function template. Determine whether there are
69 // any other function templates we need to bundle together in an
70 // OverloadedFunctionDecl
71 for (++F; F != FEnd; ++F) {
72 if (isa<FunctionTemplateDecl>(*F))
73 break;
74 }
Mike Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregorb7bfe792009-09-02 22:59:36 +000076 if (F != FEnd) {
77 // Build an overloaded function decl containing only the
78 // function templates in Ovl.
Mike Stump11289f42009-09-09 15:08:12 +000079 OverloadedFunctionDecl *OvlTemplate
Douglas Gregorb7bfe792009-09-02 22:59:36 +000080 = OverloadedFunctionDecl::Create(Context,
81 Ovl->getDeclContext(),
82 Ovl->getDeclName());
83 OvlTemplate->addOverload(FuncTmpl);
84 OvlTemplate->addOverload(*F);
85 for (++F; F != FEnd; ++F) {
86 if (isa<FunctionTemplateDecl>(*F))
87 OvlTemplate->addOverload(*F);
88 }
Mike Stump11289f42009-09-09 15:08:12 +000089
Douglas Gregorb7bfe792009-09-02 22:59:36 +000090 return OvlTemplate;
91 }
92
93 return FuncTmpl;
94 }
95 }
Mike Stump11289f42009-09-09 15:08:12 +000096
Douglas Gregorb7bfe792009-09-02 22:59:36 +000097 return 0;
98}
99
100TemplateNameKind Sema::isTemplateName(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +0000101 const IdentifierInfo &II,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000102 SourceLocation IdLoc,
Douglas Gregore861bac2009-08-25 22:51:20 +0000103 const CXXScopeSpec *SS,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000104 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000105 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000106 TemplateTy &TemplateResult) {
107 // Determine where to perform name lookup
108 DeclContext *LookupCtx = 0;
109 bool isDependent = false;
110 if (ObjectTypePtr) {
111 // This nested-name-specifier occurs in a member access expression, e.g.,
112 // x->B::f, and we are looking into the type of the object.
Mike Stump11289f42009-09-09 15:08:12 +0000113 assert((!SS || !SS->isSet()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000114 "ObjectType and scope specifier cannot coexist");
115 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
116 LookupCtx = computeDeclContext(ObjectType);
117 isDependent = ObjectType->isDependentType();
118 } else if (SS && SS->isSet()) {
119 // This nested-name-specifier occurs after another nested-name-specifier,
120 // so long into the context associated with the prior nested-name-specifier.
121
122 LookupCtx = computeDeclContext(*SS, EnteringContext);
123 isDependent = isDependentScopeSpecifier(*SS);
124 }
Mike Stump11289f42009-09-09 15:08:12 +0000125
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000126 LookupResult Found;
127 bool ObjectTypeSearchedInScope = false;
128 if (LookupCtx) {
129 // Perform "qualified" name lookup into the declaration context we
130 // computed, which is either the type of the base of a member access
Mike Stump11289f42009-09-09 15:08:12 +0000131 // expression or the declaration context associated with a prior
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000132 // nested-name-specifier.
133
134 // The declaration context must be complete.
135 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
136 return TNK_Non_template;
Mike Stump11289f42009-09-09 15:08:12 +0000137
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000138 Found = LookupQualifiedName(LookupCtx, &II, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +0000139
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000140 if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
141 // C++ [basic.lookup.classref]p1:
142 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump11289f42009-09-09 15:08:12 +0000143 // immediately followed by an identifier followed by a <, the
144 // identifier must be looked up to determine whether the < is the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000145 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump11289f42009-09-09 15:08:12 +0000146 // The identifier is first looked up in the class of the object
147 // expression. If the identifier is not found, it is then looked up in
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000148 // the context of the entire postfix-expression and shall name a class
149 // or function template.
150 //
151 // FIXME: When we're instantiating a template, do we actually have to
152 // look in the scope of the template? Seems fishy...
153 Found = LookupName(S, &II, LookupOrdinaryName);
154 ObjectTypeSearchedInScope = true;
155 }
156 } else if (isDependent) {
Mike Stump11289f42009-09-09 15:08:12 +0000157 // We cannot look into a dependent object type or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158 return TNK_Non_template;
159 } else {
160 // Perform unqualified name lookup in the current scope.
161 Found = LookupName(S, &II, LookupOrdinaryName);
162 }
Mike Stump11289f42009-09-09 15:08:12 +0000163
Douglas Gregore861bac2009-08-25 22:51:20 +0000164 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump11289f42009-09-09 15:08:12 +0000165 assert(!Found.isAmbiguous() &&
Douglas Gregore861bac2009-08-25 22:51:20 +0000166 "Cannot handle template name-lookup ambiguities");
Douglas Gregordc572a32009-03-30 22:58:21 +0000167
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000168 NamedDecl *Template = isAcceptableTemplateName(Context, Found);
169 if (!Template)
170 return TNK_Non_template;
171
172 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
173 // C++ [basic.lookup.classref]p1:
Mike Stump11289f42009-09-09 15:08:12 +0000174 // [...] If the lookup in the class of the object expression finds a
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000175 // template, the name is also looked up in the context of the entire
176 // postfix-expression and [...]
177 //
178 LookupResult FoundOuter = LookupName(S, &II, LookupOrdinaryName);
179 // FIXME: Handle ambiguities in this lookup better
180 NamedDecl *OuterTemplate = isAcceptableTemplateName(Context, FoundOuter);
Mike Stump11289f42009-09-09 15:08:12 +0000181
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000182 if (!OuterTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +0000183 // - if the name is not found, the name found in the class of the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000184 // object expression is used, otherwise
185 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump11289f42009-09-09 15:08:12 +0000186 // - if the name is found in the context of the entire
187 // postfix-expression and does not name a class template, the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000188 // found in the class of the object expression is used, otherwise
189 } else {
190 // - if the name found is a class template, it must refer to the same
Mike Stump11289f42009-09-09 15:08:12 +0000191 // entity as the one found in the class of the object expression,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000192 // otherwise the program is ill-formed.
193 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
194 Diag(IdLoc, diag::err_nested_name_member_ref_lookup_ambiguous)
195 << &II;
196 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
197 << QualType::getFromOpaquePtr(ObjectTypePtr);
198 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump11289f42009-09-09 15:08:12 +0000199
200 // Recover by taking the template that we found in the object
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000201 // expression's type.
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000202 }
Mike Stump11289f42009-09-09 15:08:12 +0000203 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000204 }
Mike Stump11289f42009-09-09 15:08:12 +0000205
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000206 if (SS && SS->isSet() && !SS->isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000207 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000208 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000209 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000210 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000211 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000212 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
213 Ovl));
214 else
Mike Stump11289f42009-09-09 15:08:12 +0000215 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000216 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000217 cast<TemplateDecl>(Template)));
218 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000219 = dyn_cast<OverloadedFunctionDecl>(Template)) {
220 TemplateResult = TemplateTy::make(TemplateName(Ovl));
221 } else {
222 TemplateResult = TemplateTy::make(
223 TemplateName(cast<TemplateDecl>(Template)));
224 }
Mike Stump11289f42009-09-09 15:08:12 +0000225
226 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000227 isa<TemplateTemplateParmDecl>(Template))
228 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000229
230 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000231 isa<OverloadedFunctionDecl>(Template)) &&
232 "Unhandled template kind in Sema::isTemplateName");
233 return TNK_Function_template;
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000234}
235
Douglas Gregor5101c242008-12-05 18:15:24 +0000236/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
237/// that the template parameter 'PrevDecl' is being shadowed by a new
238/// declaration at location Loc. Returns true to indicate that this is
239/// an error, and false otherwise.
240bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000241 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000242
243 // Microsoft Visual C++ permits template parameters to be shadowed.
244 if (getLangOptions().Microsoft)
245 return false;
246
247 // C++ [temp.local]p4:
248 // A template-parameter shall not be redeclared within its
249 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000250 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000251 << cast<NamedDecl>(PrevDecl)->getDeclName();
252 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
253 return true;
254}
255
Douglas Gregor463421d2009-03-03 04:44:36 +0000256/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000257/// the parameter D to reference the templated declaration and return a pointer
258/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000259TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
260 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
261 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000262 return Temp;
263 }
264 return 0;
265}
266
Douglas Gregor5101c242008-12-05 18:15:24 +0000267/// ActOnTypeParameter - Called when a C++ template type parameter
268/// (e.g., "typename T") has been parsed. Typename specifies whether
269/// the keyword "typename" was used to declare the type parameter
270/// (otherwise, "class" was used), and KeyLoc is the location of the
271/// "class" or "typename" keyword. ParamName is the name of the
272/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000273/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000274/// If the type parameter has a default argument, it will be added
275/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000276Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000277 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000278 SourceLocation KeyLoc,
279 IdentifierInfo *ParamName,
280 SourceLocation ParamNameLoc,
281 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000282 assert(S->isTemplateParamScope() &&
283 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000284 bool Invalid = false;
285
286 if (ParamName) {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000287 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000288 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000289 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000290 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000291 }
292
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000293 SourceLocation Loc = ParamNameLoc;
294 if (!ParamName)
295 Loc = KeyLoc;
296
Douglas Gregor5101c242008-12-05 18:15:24 +0000297 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000298 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
299 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000300 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000301 if (Invalid)
302 Param->setInvalidDecl();
303
304 if (ParamName) {
305 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000306 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000307 IdResolver.AddDecl(Param);
308 }
309
Chris Lattner83f095c2009-03-28 19:18:32 +0000310 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000311}
312
Douglas Gregordba32632009-02-10 19:49:53 +0000313/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000314/// Default) to the given template type parameter (TypeParam).
315void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000316 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000317 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000318 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000319 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000320 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000321 // FIXME: Preserve type source info.
322 QualType Default = GetTypeFromParser(DefaultT);
Douglas Gregordba32632009-02-10 19:49:53 +0000323
Anders Carlssond3824352009-06-12 22:30:13 +0000324 // C++0x [temp.param]p9:
325 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000326 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000327 if (Parm->isParameterPack()) {
328 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000329 return;
330 }
Mike Stump11289f42009-09-09 15:08:12 +0000331
Douglas Gregordba32632009-02-10 19:49:53 +0000332 // C++ [temp.param]p14:
333 // A template-parameter shall not be used in its own default argument.
334 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000335
Douglas Gregordba32632009-02-10 19:49:53 +0000336 // Check the template argument itself.
337 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
338 Parm->setInvalidDecl();
339 return;
340 }
341
342 Parm->setDefaultArgument(Default, DefaultLoc, false);
343}
344
Douglas Gregor463421d2009-03-03 04:44:36 +0000345/// \brief Check that the type of a non-type template parameter is
346/// well-formed.
347///
348/// \returns the (possibly-promoted) parameter type if valid;
349/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000350QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000351Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
352 // C++ [temp.param]p4:
353 //
354 // A non-type template-parameter shall have one of the following
355 // (optionally cv-qualified) types:
356 //
357 // -- integral or enumeration type,
358 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000359 // -- pointer to object or pointer to function,
360 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000361 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
362 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000363 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000364 T->isReferenceType() ||
365 // -- pointer to member.
366 T->isMemberPointerType() ||
367 // If T is a dependent type, we can't do the check now, so we
368 // assume that it is well-formed.
369 T->isDependentType())
370 return T;
371 // C++ [temp.param]p8:
372 //
373 // A non-type template-parameter of type "array of T" or
374 // "function returning T" is adjusted to be of type "pointer to
375 // T" or "pointer to function returning T", respectively.
376 else if (T->isArrayType())
377 // FIXME: Keep the type prior to promotion?
378 return Context.getArrayDecayedType(T);
379 else if (T->isFunctionType())
380 // FIXME: Keep the type prior to promotion?
381 return Context.getPointerType(T);
382
383 Diag(Loc, diag::err_template_nontype_parm_bad_type)
384 << T;
385
386 return QualType();
387}
388
Douglas Gregor5101c242008-12-05 18:15:24 +0000389/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
390/// template parameter (e.g., "int Size" in "template<int Size>
391/// class Array") has been parsed. S is the current scope and D is
392/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000393Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000394 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000395 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000396 DeclaratorInfo *DInfo = 0;
397 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000398
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000399 assert(S->isTemplateParamScope() &&
400 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000401 bool Invalid = false;
402
403 IdentifierInfo *ParamName = D.getIdentifier();
404 if (ParamName) {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000405 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000406 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000407 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000408 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000409 }
410
Douglas Gregor463421d2009-03-03 04:44:36 +0000411 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000412 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000413 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000414 Invalid = true;
415 }
Douglas Gregor81338792009-02-10 17:43:50 +0000416
Douglas Gregor5101c242008-12-05 18:15:24 +0000417 NonTypeTemplateParmDecl *Param
418 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000419 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000420 if (Invalid)
421 Param->setInvalidDecl();
422
423 if (D.getIdentifier()) {
424 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000425 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000426 IdResolver.AddDecl(Param);
427 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000428 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000429}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000430
Douglas Gregordba32632009-02-10 19:49:53 +0000431/// \brief Adds a default argument to the given non-type template
432/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000433void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000434 SourceLocation EqualLoc,
435 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000436 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000437 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000438 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000439
Douglas Gregordba32632009-02-10 19:49:53 +0000440 // C++ [temp.param]p14:
441 // A template-parameter shall not be used in its own default argument.
442 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000443
Douglas Gregordba32632009-02-10 19:49:53 +0000444 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000445 TemplateArgument Converted;
446 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
447 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000448 TemplateParm->setInvalidDecl();
449 return;
450 }
451
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000452 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000453}
454
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000455
456/// ActOnTemplateTemplateParameter - Called when a C++ template template
457/// parameter (e.g. T in template <template <typename> class T> class array)
458/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000459Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
460 SourceLocation TmpLoc,
461 TemplateParamsTy *Params,
462 IdentifierInfo *Name,
463 SourceLocation NameLoc,
464 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000465 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000466 assert(S->isTemplateParamScope() &&
467 "Template template parameter not in template parameter scope!");
468
469 // Construct the parameter object.
470 TemplateTemplateParmDecl *Param =
471 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
472 Position, Name,
473 (TemplateParameterList*)Params);
474
475 // Make sure the parameter is valid.
476 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
477 // do anything yet. However, if the template parameter list or (eventual)
478 // default value is ever invalidated, that will propagate here.
479 bool Invalid = false;
480 if (Invalid) {
481 Param->setInvalidDecl();
482 }
483
484 // If the tt-param has a name, then link the identifier into the scope
485 // and lookup mechanisms.
486 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000487 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000488 IdResolver.AddDecl(Param);
489 }
490
Chris Lattner83f095c2009-03-28 19:18:32 +0000491 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000492}
493
Douglas Gregordba32632009-02-10 19:49:53 +0000494/// \brief Adds a default argument to the given template template
495/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000496void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000497 SourceLocation EqualLoc,
498 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000499 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000500 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000501
502 // Since a template-template parameter's default argument is an
503 // id-expression, it must be a DeclRefExpr.
Mike Stump11289f42009-09-09 15:08:12 +0000504 DeclRefExpr *Default
Douglas Gregordba32632009-02-10 19:49:53 +0000505 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
506
507 // C++ [temp.param]p14:
508 // A template-parameter shall not be used in its own default argument.
509 // FIXME: Implement this check! Needs a recursive walk over the types.
510
511 // Check the well-formedness of the template argument.
512 if (!isa<TemplateDecl>(Default->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +0000513 Diag(Default->getSourceRange().getBegin(),
Douglas Gregordba32632009-02-10 19:49:53 +0000514 diag::err_template_arg_must_be_template)
515 << Default->getSourceRange();
516 TemplateParm->setInvalidDecl();
517 return;
Mike Stump11289f42009-09-09 15:08:12 +0000518 }
Douglas Gregordba32632009-02-10 19:49:53 +0000519 if (CheckTemplateArgument(TemplateParm, Default)) {
520 TemplateParm->setInvalidDecl();
521 return;
522 }
523
524 DefaultE.release();
525 TemplateParm->setDefaultArgument(Default);
526}
527
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000528/// ActOnTemplateParameterList - Builds a TemplateParameterList that
529/// contains the template parameters in Params/NumParams.
530Sema::TemplateParamsTy *
531Sema::ActOnTemplateParameterList(unsigned Depth,
532 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000533 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000534 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000535 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000536 SourceLocation RAngleLoc) {
537 if (ExportLoc.isValid())
538 Diag(ExportLoc, diag::note_template_export_unsupported);
539
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000540 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000541 (NamedDecl**)Params, NumParams,
542 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000543}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000544
Douglas Gregorc08f4892009-03-25 00:13:59 +0000545Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000546Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000547 SourceLocation KWLoc, const CXXScopeSpec &SS,
548 IdentifierInfo *Name, SourceLocation NameLoc,
549 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000550 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000551 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000552 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000553 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000554 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000555 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000556
557 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000558 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000559 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000560
John McCall27b5c252009-09-14 21:59:20 +0000561 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
562 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000563
564 // There is no such thing as an unnamed class template.
565 if (!Name) {
566 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000567 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000568 }
569
570 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000571 DeclContext *SemanticContext;
572 LookupResult Previous;
573 if (SS.isNotEmpty() && !SS.isInvalid()) {
574 SemanticContext = computeDeclContext(SS, true);
575 if (!SemanticContext) {
576 // FIXME: Produce a reasonable diagnostic here
577 return true;
578 }
Mike Stump11289f42009-09-09 15:08:12 +0000579
580 Previous = LookupQualifiedName(SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000581 true);
Douglas Gregor3dad8422009-09-26 06:47:28 +0000582 } else if (TUK == TUK_Friend) {
583 // C++ [namespace.memdef]p3:
584 // [...] When looking for a prior declaration of a class or a function
585 // declared as a friend, and when the name of the friend class or
586 // function is neither a qualified name nor a template-id, scopes outside
587 // the innermost enclosing namespace scope are not considered.
588 SemanticContext = CurContext;
589 while (!SemanticContext->isFileContext())
590 SemanticContext = SemanticContext->getLookupParent();
591
592 Previous = LookupQualifiedName(SemanticContext, Name, LookupOrdinaryName,
593 true);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000594 } else {
595 SemanticContext = CurContext;
596 Previous = LookupName(S, Name, LookupOrdinaryName, true);
597 }
Mike Stump11289f42009-09-09 15:08:12 +0000598
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000599 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
600 NamedDecl *PrevDecl = 0;
601 if (Previous.begin() != Previous.end())
602 PrevDecl = *Previous.begin();
603
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000604 if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000605 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000606
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000607 // If there is a previous declaration with the same name, check
608 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000609 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000610 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
611 if (PrevClassTemplate) {
612 // Ensure that the template parameter lists are compatible.
613 if (!TemplateParameterListsAreEqual(TemplateParams,
614 PrevClassTemplate->getTemplateParameters(),
615 /*Complain=*/true))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000616 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000617
618 // C++ [temp.class]p4:
619 // In a redeclaration, partial specialization, explicit
620 // specialization or explicit instantiation of a class template,
621 // the class-key shall agree in kind with the original class
622 // template declaration (7.1.5.3).
623 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000624 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000625 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000626 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000627 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000628 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000629 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000630 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000631 }
632
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000633 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000634 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000635 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
636 Diag(NameLoc, diag::err_redefinition) << Name;
637 Diag(Def->getLocation(), diag::note_previous_definition);
638 // FIXME: Would it make sense to try to "forget" the previous
639 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000640 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000641 }
642 }
643 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
644 // Maybe we will complain about the shadowed template parameter.
645 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
646 // Just pretend that we didn't see the previous declaration.
647 PrevDecl = 0;
648 } else if (PrevDecl) {
649 // C++ [temp]p5:
650 // A class template shall not have the same name as any other
651 // template, class, function, object, enumeration, enumerator,
652 // namespace, or type in the same scope (3.3), except as specified
653 // in (14.5.4).
654 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
655 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000656 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000657 }
658
Douglas Gregordba32632009-02-10 19:49:53 +0000659 // Check the template parameter list of this declaration, possibly
660 // merging in the template parameter list from the previous class
661 // template declaration.
662 if (CheckTemplateParameterList(TemplateParams,
663 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
664 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000665
Douglas Gregore362cea2009-05-10 22:57:19 +0000666 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000667 // declaration!
668
Mike Stump11289f42009-09-09 15:08:12 +0000669 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000670 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000671 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000672 PrevClassTemplate->getTemplatedDecl() : 0,
673 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000674
675 ClassTemplateDecl *NewTemplate
676 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
677 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000678 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000679 NewClass->setDescribedClassTemplate(NewTemplate);
680
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000681 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000682 QualType T =
683 Context.getTypeDeclType(NewClass,
684 PrevClassTemplate?
685 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000686 assert(T->isDependentType() && "Class template type is not dependent?");
687 (void)T;
688
Anders Carlsson137108d2009-03-26 01:24:28 +0000689 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000690 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000691 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000692
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000693 // Set the lexical context of these templates
694 NewClass->setLexicalDeclContext(CurContext);
695 NewTemplate->setLexicalDeclContext(CurContext);
696
John McCall9bb74a52009-07-31 02:45:11 +0000697 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000698 NewClass->startDefinition();
699
700 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000701 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000702
John McCall27b5c252009-09-14 21:59:20 +0000703 if (TUK != TUK_Friend)
704 PushOnScopeChains(NewTemplate, S);
705 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000706 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000707 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000708 NewClass->setAccess(PrevClassTemplate->getAccess());
709 }
John McCall27b5c252009-09-14 21:59:20 +0000710
Douglas Gregor3dad8422009-09-26 06:47:28 +0000711 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
712 PrevClassTemplate != NULL);
713
John McCall27b5c252009-09-14 21:59:20 +0000714 // Friend templates are visible in fairly strange ways.
715 if (!CurContext->isDependentContext()) {
716 DeclContext *DC = SemanticContext->getLookupContext();
717 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
718 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
719 PushOnScopeChains(NewTemplate, EnclosingScope,
720 /* AddToContext = */ false);
721 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000722
723 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
724 NewClass->getLocation(),
725 NewTemplate,
726 /*FIXME:*/NewClass->getLocation());
727 Friend->setAccess(AS_public);
728 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000729 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000730
Douglas Gregordba32632009-02-10 19:49:53 +0000731 if (Invalid) {
732 NewTemplate->setInvalidDecl();
733 NewClass->setInvalidDecl();
734 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000735 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000736}
737
Douglas Gregordba32632009-02-10 19:49:53 +0000738/// \brief Checks the validity of a template parameter list, possibly
739/// considering the template parameter list from a previous
740/// declaration.
741///
742/// If an "old" template parameter list is provided, it must be
743/// equivalent (per TemplateParameterListsAreEqual) to the "new"
744/// template parameter list.
745///
746/// \param NewParams Template parameter list for a new template
747/// declaration. This template parameter list will be updated with any
748/// default arguments that are carried through from the previous
749/// template parameter list.
750///
751/// \param OldParams If provided, template parameter list from a
752/// previous declaration of the same template. Default template
753/// arguments will be merged from the old template parameter list to
754/// the new template parameter list.
755///
756/// \returns true if an error occurred, false otherwise.
757bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
758 TemplateParameterList *OldParams) {
759 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000760
Douglas Gregordba32632009-02-10 19:49:53 +0000761 // C++ [temp.param]p10:
762 // The set of default template-arguments available for use with a
763 // template declaration or definition is obtained by merging the
764 // default arguments from the definition (if in scope) and all
765 // declarations in scope in the same way default function
766 // arguments are (8.3.6).
767 bool SawDefaultArgument = false;
768 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000769
Anders Carlsson327865d2009-06-12 23:20:15 +0000770 bool SawParameterPack = false;
771 SourceLocation ParameterPackLoc;
772
Mike Stumpc89c8e32009-02-11 23:03:27 +0000773 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000774 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000775 if (OldParams)
776 OldParam = OldParams->begin();
777
778 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
779 NewParamEnd = NewParams->end();
780 NewParam != NewParamEnd; ++NewParam) {
781 // Variables used to diagnose redundant default arguments
782 bool RedundantDefaultArg = false;
783 SourceLocation OldDefaultLoc;
784 SourceLocation NewDefaultLoc;
785
786 // Variables used to diagnose missing default arguments
787 bool MissingDefaultArg = false;
788
Anders Carlsson327865d2009-06-12 23:20:15 +0000789 // C++0x [temp.param]p11:
790 // If a template parameter of a class template is a template parameter pack,
791 // it must be the last template parameter.
792 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +0000793 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +0000794 diag::err_template_param_pack_must_be_last_template_parameter);
795 Invalid = true;
796 }
797
Douglas Gregordba32632009-02-10 19:49:53 +0000798 // Merge default arguments for template type parameters.
799 if (TemplateTypeParmDecl *NewTypeParm
800 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump11289f42009-09-09 15:08:12 +0000801 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000802 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000803
Anders Carlsson327865d2009-06-12 23:20:15 +0000804 if (NewTypeParm->isParameterPack()) {
805 assert(!NewTypeParm->hasDefaultArgument() &&
806 "Parameter packs can't have a default argument!");
807 SawParameterPack = true;
808 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000809 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000810 NewTypeParm->hasDefaultArgument()) {
811 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
812 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
813 SawDefaultArgument = true;
814 RedundantDefaultArg = true;
815 PreviousDefaultArgLoc = NewDefaultLoc;
816 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
817 // Merge the default argument from the old declaration to the
818 // new declaration.
819 SawDefaultArgument = true;
820 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
821 OldTypeParm->getDefaultArgumentLoc(),
822 true);
823 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
824 } else if (NewTypeParm->hasDefaultArgument()) {
825 SawDefaultArgument = true;
826 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
827 } else if (SawDefaultArgument)
828 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000829 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000830 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000831 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000832 NonTypeTemplateParmDecl *OldNonTypeParm
833 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000834 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000835 NewNonTypeParm->hasDefaultArgument()) {
836 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
837 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
838 SawDefaultArgument = true;
839 RedundantDefaultArg = true;
840 PreviousDefaultArgLoc = NewDefaultLoc;
841 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
842 // Merge the default argument from the old declaration to the
843 // new declaration.
844 SawDefaultArgument = true;
845 // FIXME: We need to create a new kind of "default argument"
846 // expression that points to a previous template template
847 // parameter.
848 NewNonTypeParm->setDefaultArgument(
849 OldNonTypeParm->getDefaultArgument());
850 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
851 } else if (NewNonTypeParm->hasDefaultArgument()) {
852 SawDefaultArgument = true;
853 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
854 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000855 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000856 } else {
Douglas Gregordba32632009-02-10 19:49:53 +0000857 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000858 TemplateTemplateParmDecl *NewTemplateParm
859 = cast<TemplateTemplateParmDecl>(*NewParam);
860 TemplateTemplateParmDecl *OldTemplateParm
861 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000862 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000863 NewTemplateParm->hasDefaultArgument()) {
864 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
865 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
866 SawDefaultArgument = true;
867 RedundantDefaultArg = true;
868 PreviousDefaultArgLoc = NewDefaultLoc;
869 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
870 // Merge the default argument from the old declaration to the
871 // new declaration.
872 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +0000873 // FIXME: We need to create a new kind of "default argument" expression
874 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +0000875 NewTemplateParm->setDefaultArgument(
876 OldTemplateParm->getDefaultArgument());
877 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
878 } else if (NewTemplateParm->hasDefaultArgument()) {
879 SawDefaultArgument = true;
880 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
881 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000882 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +0000883 }
884
885 if (RedundantDefaultArg) {
886 // C++ [temp.param]p12:
887 // A template-parameter shall not be given default arguments
888 // by two different declarations in the same scope.
889 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
890 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
891 Invalid = true;
892 } else if (MissingDefaultArg) {
893 // C++ [temp.param]p11:
894 // If a template-parameter has a default template-argument,
895 // all subsequent template-parameters shall have a default
896 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +0000897 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +0000898 diag::err_template_param_default_arg_missing);
899 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
900 Invalid = true;
901 }
902
903 // If we have an old template parameter list that we're merging
904 // in, move on to the next parameter.
905 if (OldParams)
906 ++OldParam;
907 }
908
909 return Invalid;
910}
Douglas Gregord32e0282009-02-09 23:23:08 +0000911
Mike Stump11289f42009-09-09 15:08:12 +0000912/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +0000913/// specifier, returning the template parameter list that applies to the
914/// name.
915///
916/// \param DeclStartLoc the start of the declaration that has a scope
917/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +0000918///
Douglas Gregord8d297c2009-07-21 23:53:31 +0000919/// \param SS the scope specifier that will be matched to the given template
920/// parameter lists. This scope specifier precedes a qualified name that is
921/// being declared.
922///
923/// \param ParamLists the template parameter lists, from the outermost to the
924/// innermost template parameter lists.
925///
926/// \param NumParamLists the number of template parameter lists in ParamLists.
927///
Mike Stump11289f42009-09-09 15:08:12 +0000928/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +0000929/// name that is preceded by the scope specifier @p SS. This template
930/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +0000931/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +0000932/// template specialization), or may be NULL (if we were's declaring isn't
933/// itself a template).
934TemplateParameterList *
935Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
936 const CXXScopeSpec &SS,
937 TemplateParameterList **ParamLists,
938 unsigned NumParamLists) {
Douglas Gregord8d297c2009-07-21 23:53:31 +0000939 // Find the template-ids that occur within the nested-name-specifier. These
940 // template-ids will match up with the template parameter lists.
941 llvm::SmallVector<const TemplateSpecializationType *, 4>
942 TemplateIdsInSpecifier;
943 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
944 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +0000945 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +0000946 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
947 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
948 if (!Template)
949 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +0000950
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000951 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +0000952 ClassTemplateSpecializationDecl *SpecDecl
953 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
954 // If the nested name specifier refers to an explicit specialization,
955 // we don't need a template<> header.
Douglas Gregor82e22862009-09-16 00:01:48 +0000956 // FIXME: revisit this approach once we cope with specializations
Douglas Gregor15301382009-07-30 17:40:51 +0000957 // properly.
Douglas Gregord8d297c2009-07-21 23:53:31 +0000958 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
959 continue;
960 }
Mike Stump11289f42009-09-09 15:08:12 +0000961
Douglas Gregord8d297c2009-07-21 23:53:31 +0000962 TemplateIdsInSpecifier.push_back(SpecType);
963 }
964 }
Mike Stump11289f42009-09-09 15:08:12 +0000965
Douglas Gregord8d297c2009-07-21 23:53:31 +0000966 // Reverse the list of template-ids in the scope specifier, so that we can
967 // more easily match up the template-ids and the template parameter lists.
968 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +0000969
Douglas Gregord8d297c2009-07-21 23:53:31 +0000970 SourceLocation FirstTemplateLoc = DeclStartLoc;
971 if (NumParamLists)
972 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000973
Douglas Gregord8d297c2009-07-21 23:53:31 +0000974 // Match the template-ids found in the specifier to the template parameter
975 // lists.
976 unsigned Idx = 0;
977 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
978 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +0000979 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
980 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +0000981 if (Idx >= NumParamLists) {
982 // We have a template-id without a corresponding template parameter
983 // list.
984 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +0000985 // FIXME: the location information here isn't great.
986 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +0000987 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +0000988 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +0000989 << SS.getRange();
990 } else {
991 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
992 << SS.getRange()
993 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
994 "template<> ");
995 }
996 return 0;
997 }
Mike Stump11289f42009-09-09 15:08:12 +0000998
Douglas Gregord8d297c2009-07-21 23:53:31 +0000999 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001000 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001001 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001002 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1003
Mike Stump11289f42009-09-09 15:08:12 +00001004 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001005 = dyn_cast<ClassTemplateDecl>(Template)) {
1006 TemplateParameterList *ExpectedTemplateParams = 0;
1007 // Is this template-id naming the primary template?
1008 if (Context.hasSameType(TemplateId,
1009 ClassTemplate->getInjectedClassNameType(Context)))
1010 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1011 // ... or a partial specialization?
1012 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1013 = ClassTemplate->findPartialSpecialization(TemplateId))
1014 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1015
1016 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001017 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001018 ExpectedTemplateParams,
1019 true);
Mike Stump11289f42009-09-09 15:08:12 +00001020 }
Douglas Gregor15301382009-07-30 17:40:51 +00001021 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001022 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001023 diag::err_template_param_list_matches_nontemplate)
1024 << TemplateId
1025 << ParamLists[Idx]->getSourceRange();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001026 }
Mike Stump11289f42009-09-09 15:08:12 +00001027
Douglas Gregord8d297c2009-07-21 23:53:31 +00001028 // If there were at least as many template-ids as there were template
1029 // parameter lists, then there are no template parameter lists remaining for
1030 // the declaration itself.
1031 if (Idx >= NumParamLists)
1032 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001033
Douglas Gregord8d297c2009-07-21 23:53:31 +00001034 // If there were too many template parameter lists, complain about that now.
1035 if (Idx != NumParamLists - 1) {
1036 while (Idx < NumParamLists - 1) {
Mike Stump11289f42009-09-09 15:08:12 +00001037 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001038 diag::err_template_spec_extra_headers)
1039 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1040 ParamLists[Idx]->getRAngleLoc());
1041 ++Idx;
1042 }
1043 }
Mike Stump11289f42009-09-09 15:08:12 +00001044
Douglas Gregord8d297c2009-07-21 23:53:31 +00001045 // Return the last template parameter list, which corresponds to the
1046 // entity being declared.
1047 return ParamLists[NumParamLists - 1];
1048}
1049
Douglas Gregorc40290e2009-03-09 23:48:35 +00001050/// \brief Translates template arguments as provided by the parser
1051/// into template arguments used by semantic analysis.
Douglas Gregor0e876e02009-09-25 23:53:26 +00001052void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
1053 SourceLocation *TemplateArgLocs,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001054 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
1055 TemplateArgs.reserve(TemplateArgsIn.size());
1056
1057 void **Args = TemplateArgsIn.getArgs();
1058 bool *ArgIsType = TemplateArgsIn.getArgIsType();
1059 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
1060 TemplateArgs.push_back(
1061 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001062 //FIXME: Preserve type source info.
1063 Sema::GetTypeFromParser(Args[Arg]))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001064 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
1065 }
1066}
1067
Douglas Gregordc572a32009-03-30 22:58:21 +00001068QualType Sema::CheckTemplateIdType(TemplateName Name,
1069 SourceLocation TemplateLoc,
1070 SourceLocation LAngleLoc,
1071 const TemplateArgument *TemplateArgs,
1072 unsigned NumTemplateArgs,
1073 SourceLocation RAngleLoc) {
1074 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001075 if (!Template) {
1076 // The template name does not resolve to a template, so we just
1077 // build a dependent template-id type.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001078 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001079 NumTemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001080 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001081
Douglas Gregorc40290e2009-03-09 23:48:35 +00001082 // Check that the template argument list is well-formed for this
1083 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001084 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1085 NumTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001086 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001087 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001088 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001089 return QualType();
1090
Mike Stump11289f42009-09-09 15:08:12 +00001091 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001092 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001093 "Converted template argument list is too short!");
1094
1095 QualType CanonType;
1096
Douglas Gregordc572a32009-03-30 22:58:21 +00001097 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorc40290e2009-03-09 23:48:35 +00001098 TemplateArgs,
1099 NumTemplateArgs)) {
1100 // This class template specialization is a dependent
1101 // type. Therefore, its canonical type is another class template
1102 // specialization type that contains all of the converted
1103 // arguments in canonical form. This ensures that, e.g., A<T> and
1104 // A<T, T> have identical types when A is declared as:
1105 //
1106 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001107 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001108 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001109 Converted.getFlatArguments(),
1110 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001111
Douglas Gregora8e02e72009-07-28 23:00:59 +00001112 // FIXME: CanonType is not actually the canonical type, and unfortunately
1113 // it is a TemplateTypeSpecializationType that we will never use again.
1114 // In the future, we need to teach getTemplateSpecializationType to only
1115 // build the canonical type and return that to us.
1116 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001117 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001118 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001119 // Find the class template specialization declaration that
1120 // corresponds to these arguments.
1121 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001122 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001123 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001124 Converted.flatSize(),
1125 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001126 void *InsertPos = 0;
1127 ClassTemplateSpecializationDecl *Decl
1128 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1129 if (!Decl) {
1130 // This is the first time we have referenced this class template
1131 // specialization. Create the canonical declaration and add it to
1132 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001133 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001134 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001135 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001136 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001137 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001138 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1139 Decl->setLexicalDeclContext(CurContext);
1140 }
1141
1142 CanonType = Context.getTypeDeclType(Decl);
1143 }
Mike Stump11289f42009-09-09 15:08:12 +00001144
Douglas Gregorc40290e2009-03-09 23:48:35 +00001145 // Build the fully-sugared type for this class template
1146 // specialization, which refers back to the class template
1147 // specialization we created or found.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001148 //FIXME: Preserve type source info.
Douglas Gregordc572a32009-03-30 22:58:21 +00001149 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1150 NumTemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001151}
1152
Douglas Gregor67a65642009-02-17 23:15:12 +00001153Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001154Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001155 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001156 ASTTemplateArgsPtr TemplateArgsIn,
1157 SourceLocation *TemplateArgLocs,
John McCalld8fe9af2009-09-08 17:47:29 +00001158 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001159 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001160
Douglas Gregorc40290e2009-03-09 23:48:35 +00001161 // Translate the parser's template argument list in our AST format.
1162 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1163 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001164
Douglas Gregordc572a32009-03-30 22:58:21 +00001165 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +00001166 TemplateArgs.data(),
1167 TemplateArgs.size(),
Douglas Gregordc572a32009-03-30 22:58:21 +00001168 RAngleLoc);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001169 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001170
1171 if (Result.isNull())
1172 return true;
1173
John McCalld8fe9af2009-09-08 17:47:29 +00001174 return Result.getAsOpaquePtr();
1175}
John McCall06f6fe8d2009-09-04 01:14:41 +00001176
John McCalld8fe9af2009-09-08 17:47:29 +00001177Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1178 TagUseKind TUK,
1179 DeclSpec::TST TagSpec,
1180 SourceLocation TagLoc) {
1181 if (TypeResult.isInvalid())
1182 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001183
John McCalld8fe9af2009-09-08 17:47:29 +00001184 QualType Type = QualType::getFromOpaquePtr(TypeResult.get());
John McCall06f6fe8d2009-09-04 01:14:41 +00001185
John McCalld8fe9af2009-09-08 17:47:29 +00001186 // Verify the tag specifier.
1187 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001188
John McCalld8fe9af2009-09-08 17:47:29 +00001189 if (const RecordType *RT = Type->getAs<RecordType>()) {
1190 RecordDecl *D = RT->getDecl();
1191
1192 IdentifierInfo *Id = D->getIdentifier();
1193 assert(Id && "templated class must have an identifier");
1194
1195 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1196 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001197 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001198 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1199 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001200 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001201 }
1202 }
1203
John McCalld8fe9af2009-09-08 17:47:29 +00001204 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1205
1206 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001207}
1208
Douglas Gregora727cb92009-06-30 22:34:41 +00001209Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1210 SourceLocation TemplateNameLoc,
1211 SourceLocation LAngleLoc,
1212 const TemplateArgument *TemplateArgs,
1213 unsigned NumTemplateArgs,
1214 SourceLocation RAngleLoc) {
1215 // FIXME: Can we do any checking at this point? I guess we could check the
1216 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001217 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001218 // though.
Mike Stump11289f42009-09-09 15:08:12 +00001219 return Owned(TemplateIdRefExpr::Create(Context,
Douglas Gregora727cb92009-06-30 22:34:41 +00001220 /*FIXME: New type?*/Context.OverloadTy,
1221 /*FIXME: Necessary?*/0,
1222 /*FIXME: Necessary?*/SourceRange(),
1223 Template, TemplateNameLoc, LAngleLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001224 TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001225 NumTemplateArgs, RAngleLoc));
1226}
1227
1228Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1229 SourceLocation TemplateNameLoc,
1230 SourceLocation LAngleLoc,
1231 ASTTemplateArgsPtr TemplateArgsIn,
1232 SourceLocation *TemplateArgLocs,
1233 SourceLocation RAngleLoc) {
1234 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001235
Douglas Gregora727cb92009-06-30 22:34:41 +00001236 // Translate the parser's template argument list in our AST format.
1237 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1238 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001239 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001240
Douglas Gregora727cb92009-06-30 22:34:41 +00001241 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1242 TemplateArgs.data(), TemplateArgs.size(),
1243 RAngleLoc);
1244}
1245
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001246Sema::OwningExprResult
1247Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base,
1248 SourceLocation OpLoc,
1249 tok::TokenKind OpKind,
1250 const CXXScopeSpec &SS,
1251 TemplateTy TemplateD,
1252 SourceLocation TemplateNameLoc,
1253 SourceLocation LAngleLoc,
1254 ASTTemplateArgsPtr TemplateArgsIn,
1255 SourceLocation *TemplateArgLocs,
1256 SourceLocation RAngleLoc) {
1257 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001258
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001259 // FIXME: We're going to end up looking up the template based on its name,
1260 // twice!
1261 DeclarationName Name;
1262 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
1263 Name = ActualTemplate->getDeclName();
1264 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
1265 Name = Ovl->getDeclName();
1266 else
Douglas Gregor308047d2009-09-09 00:23:06 +00001267 Name = Template.getAsDependentTemplateName()->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001268
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001269 // Translate the parser's template argument list in our AST format.
1270 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1271 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1272 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001273
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001274 // Do we have the save the actual template name? We might need it...
1275 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc,
1276 Name, true, LAngleLoc,
1277 TemplateArgs.data(), TemplateArgs.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001278 RAngleLoc, DeclPtrTy(), &SS);
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001279}
1280
Douglas Gregorb67535d2009-03-31 00:43:58 +00001281/// \brief Form a dependent template name.
1282///
1283/// This action forms a dependent template name given the template
1284/// name and its (presumably dependent) scope specifier. For
1285/// example, given "MetaFun::template apply", the scope specifier \p
1286/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1287/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001288Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001289Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1290 const IdentifierInfo &Name,
1291 SourceLocation NameLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001292 const CXXScopeSpec &SS,
1293 TypeTy *ObjectType) {
Mike Stump11289f42009-09-09 15:08:12 +00001294 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001295 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1296 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001297 // C++0x [temp.names]p5:
1298 // If a name prefixed by the keyword template is not the name of
1299 // a template, the program is ill-formed. [Note: the keyword
1300 // template may not be applied to non-template members of class
1301 // templates. -end note ] [ Note: as is the case with the
1302 // typename prefix, the template prefix is allowed in cases
1303 // where it is not strictly necessary; i.e., when the
1304 // nested-name-specifier or the expression on the left of the ->
1305 // or . is not dependent on a template-parameter, or the use
1306 // does not appear in the scope of a template. -end note]
1307 //
1308 // Note: C++03 was more strict here, because it banned the use of
1309 // the "template" keyword prior to a template-name that was not a
1310 // dependent name. C++ DR468 relaxed this requirement (the
1311 // "template" keyword is now permitted). We follow the C++0x
1312 // rules, even in C++03 mode, retroactively applying the DR.
1313 TemplateTy Template;
Mike Stump11289f42009-09-09 15:08:12 +00001314 TemplateNameKind TNK = isTemplateName(0, Name, NameLoc, &SS, ObjectType,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001315 false, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001316 if (TNK == TNK_Non_template) {
1317 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1318 << &Name;
1319 return TemplateTy();
1320 }
1321
1322 return Template;
1323 }
1324
Mike Stump11289f42009-09-09 15:08:12 +00001325 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001326 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorb67535d2009-03-31 00:43:58 +00001327 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1328}
1329
Mike Stump11289f42009-09-09 15:08:12 +00001330bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001331 const TemplateArgument &Arg,
1332 TemplateArgumentListBuilder &Converted) {
1333 // Check template type parameter.
1334 if (Arg.getKind() != TemplateArgument::Type) {
1335 // C++ [temp.arg.type]p1:
1336 // A template-argument for a template-parameter which is a
1337 // type shall be a type-id.
1338
1339 // We have a template type parameter but the template argument
1340 // is not a type.
1341 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1342 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001343
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001344 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001345 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001346
1347 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1348 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001349
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001350 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001351 Converted.Append(
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001352 TemplateArgument(Arg.getLocation(),
1353 Context.getCanonicalType(Arg.getAsType())));
1354 return false;
1355}
1356
Douglas Gregord32e0282009-02-09 23:23:08 +00001357/// \brief Check that the given template argument list is well-formed
1358/// for specializing the given template.
1359bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1360 SourceLocation TemplateLoc,
1361 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001362 const TemplateArgument *TemplateArgs,
1363 unsigned NumTemplateArgs,
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001364 SourceLocation RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001365 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001366 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001367 TemplateParameterList *Params = Template->getTemplateParameters();
1368 unsigned NumParams = Params->size();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001369 unsigned NumArgs = NumTemplateArgs;
Douglas Gregord32e0282009-02-09 23:23:08 +00001370 bool Invalid = false;
1371
Mike Stump11289f42009-09-09 15:08:12 +00001372 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001373 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001374
Anders Carlsson15201f12009-06-13 02:08:00 +00001375 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001376 (NumArgs < Params->getMinRequiredArguments() &&
1377 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001378 // FIXME: point at either the first arg beyond what we can handle,
1379 // or the '>', depending on whether we have too many or too few
1380 // arguments.
1381 SourceRange Range;
1382 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001383 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001384 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1385 << (NumArgs > NumParams)
1386 << (isa<ClassTemplateDecl>(Template)? 0 :
1387 isa<FunctionTemplateDecl>(Template)? 1 :
1388 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1389 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001390 Diag(Template->getLocation(), diag::note_template_decl_here)
1391 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001392 Invalid = true;
1393 }
Mike Stump11289f42009-09-09 15:08:12 +00001394
1395 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001396 // [...] The type and form of each template-argument specified in
1397 // a template-id shall match the type and form specified for the
1398 // corresponding parameter declared by the template in its
1399 // template-parameter-list.
1400 unsigned ArgIdx = 0;
1401 for (TemplateParameterList::iterator Param = Params->begin(),
1402 ParamEnd = Params->end();
1403 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001404 if (ArgIdx > NumArgs && PartialTemplateArgs)
1405 break;
Mike Stump11289f42009-09-09 15:08:12 +00001406
Douglas Gregord32e0282009-02-09 23:23:08 +00001407 // Decode the template argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001408 TemplateArgument Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00001409 if (ArgIdx >= NumArgs) {
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001410 // Retrieve the default template argument from the template
1411 // parameter.
1412 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001413 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001414 // We have an empty argument pack.
1415 Converted.BeginPack();
1416 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001417 break;
1418 }
Mike Stump11289f42009-09-09 15:08:12 +00001419
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001420 if (!TTP->hasDefaultArgument())
1421 break;
1422
Douglas Gregorc40290e2009-03-09 23:48:35 +00001423 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001424
1425 // If the argument type is dependent, instantiate it now based
1426 // on the previously-computed template arguments.
Douglas Gregor79cf6032009-03-10 20:44:00 +00001427 if (ArgType->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001428 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001429 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001430 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001431 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregord002c7b2009-05-11 23:53:27 +00001432
Anders Carlssonc8e71132009-06-05 04:47:51 +00001433 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001434 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001435 ArgType = SubstType(ArgType,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001436 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001437 TTP->getDefaultArgumentLoc(),
1438 TTP->getDeclName());
Douglas Gregor79cf6032009-03-10 20:44:00 +00001439 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001440
1441 if (ArgType.isNull())
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001442 return true;
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001443
Douglas Gregorc40290e2009-03-09 23:48:35 +00001444 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001445 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001446 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1447 if (!NTTP->hasDefaultArgument())
1448 break;
1449
Mike Stump11289f42009-09-09 15:08:12 +00001450 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001451 Template, Converted.getFlatArguments(),
Anders Carlsson40ed3442009-06-11 16:06:49 +00001452 Converted.flatSize(),
1453 SourceRange(TemplateLoc, RAngleLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001454
Anders Carlsson40ed3442009-06-11 16:06:49 +00001455 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001456 /*TakeArgs=*/false);
Anders Carlsson40ed3442009-06-11 16:06:49 +00001457
Mike Stump11289f42009-09-09 15:08:12 +00001458 Sema::OwningExprResult E
1459 = SubstExpr(NTTP->getDefaultArgument(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00001460 MultiLevelTemplateArgumentList(TemplateArgs));
Anders Carlsson40ed3442009-06-11 16:06:49 +00001461 if (E.isInvalid())
1462 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001463
Anders Carlsson40ed3442009-06-11 16:06:49 +00001464 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001465 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001466 TemplateTemplateParmDecl *TempParm
1467 = cast<TemplateTemplateParmDecl>(*Param);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001468
1469 if (!TempParm->hasDefaultArgument())
1470 break;
1471
John McCall76d824f2009-08-25 22:02:44 +00001472 // FIXME: Subst default argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001473 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001474 }
1475 } else {
1476 // Retrieve the template argument produced by the user.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001477 Arg = TemplateArgs[ArgIdx];
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001478 }
1479
Douglas Gregord32e0282009-02-09 23:23:08 +00001480
1481 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001482 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001483 Converted.BeginPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001484 // Check all the remaining arguments (if any).
1485 for (; ArgIdx < NumArgs; ++ArgIdx) {
1486 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1487 Invalid = true;
1488 }
Mike Stump11289f42009-09-09 15:08:12 +00001489
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001490 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001491 } else {
1492 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1493 Invalid = true;
1494 }
Mike Stump11289f42009-09-09 15:08:12 +00001495 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord32e0282009-02-09 23:23:08 +00001496 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1497 // Check non-type template parameters.
Douglas Gregor463421d2009-03-03 04:44:36 +00001498
John McCall76d824f2009-08-25 22:02:44 +00001499 // Do substitution on the type of the non-type template parameter
1500 // with the template arguments we've seen thus far.
Douglas Gregor463421d2009-03-03 04:44:36 +00001501 QualType NTTPType = NTTP->getType();
1502 if (NTTPType->isDependentType()) {
John McCall76d824f2009-08-25 22:02:44 +00001503 // Do substitution on the type of the non-type template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001504 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001505 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001506 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001507 SourceRange(TemplateLoc, RAngleLoc));
1508
Anders Carlssonc8e71132009-06-05 04:47:51 +00001509 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001510 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001511 NTTPType = SubstType(NTTPType,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00001512 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001513 NTTP->getLocation(),
1514 NTTP->getDeclName());
Douglas Gregor463421d2009-03-03 04:44:36 +00001515 // If that worked, check the non-type template parameter type
1516 // for validity.
1517 if (!NTTPType.isNull())
Mike Stump11289f42009-09-09 15:08:12 +00001518 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
Douglas Gregor463421d2009-03-03 04:44:36 +00001519 NTTP->getLocation());
Douglas Gregor463421d2009-03-03 04:44:36 +00001520 if (NTTPType.isNull()) {
1521 Invalid = true;
1522 break;
1523 }
1524 }
1525
Douglas Gregorc40290e2009-03-09 23:48:35 +00001526 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001527 case TemplateArgument::Null:
1528 assert(false && "Should never see a NULL template argument here");
1529 break;
Mike Stump11289f42009-09-09 15:08:12 +00001530
Douglas Gregorc40290e2009-03-09 23:48:35 +00001531 case TemplateArgument::Expression: {
1532 Expr *E = Arg.getAsExpr();
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001533 TemplateArgument Result;
1534 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregord32e0282009-02-09 23:23:08 +00001535 Invalid = true;
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001536 else
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001537 Converted.Append(Result);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001538 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001539 }
1540
Douglas Gregorc40290e2009-03-09 23:48:35 +00001541 case TemplateArgument::Declaration:
1542 case TemplateArgument::Integral:
1543 // We've already checked this template argument, so just copy
1544 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001545 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001546 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001547
Douglas Gregorc40290e2009-03-09 23:48:35 +00001548 case TemplateArgument::Type:
1549 // We have a non-type template parameter but the template
1550 // argument is a type.
Mike Stump11289f42009-09-09 15:08:12 +00001551
Douglas Gregorc40290e2009-03-09 23:48:35 +00001552 // C++ [temp.arg]p2:
1553 // In a template-argument, an ambiguity between a type-id and
1554 // an expression is resolved to a type-id, regardless of the
1555 // form of the corresponding template-parameter.
1556 //
1557 // We warn specifically about this case, since it can be rather
1558 // confusing for users.
1559 if (Arg.getAsType()->isFunctionType())
1560 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1561 << Arg.getAsType();
1562 else
1563 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1564 Diag((*Param)->getLocation(), diag::note_template_param_here);
1565 Invalid = true;
Anders Carlssonbc343912009-06-15 17:04:53 +00001566 break;
Mike Stump11289f42009-09-09 15:08:12 +00001567
Anders Carlssonbc343912009-06-15 17:04:53 +00001568 case TemplateArgument::Pack:
1569 assert(0 && "FIXME: Implement!");
1570 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001571 }
Mike Stump11289f42009-09-09 15:08:12 +00001572 } else {
Douglas Gregord32e0282009-02-09 23:23:08 +00001573 // Check template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001574 TemplateTemplateParmDecl *TempParm
Douglas Gregord32e0282009-02-09 23:23:08 +00001575 = cast<TemplateTemplateParmDecl>(*Param);
Mike Stump11289f42009-09-09 15:08:12 +00001576
Douglas Gregorc40290e2009-03-09 23:48:35 +00001577 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001578 case TemplateArgument::Null:
1579 assert(false && "Should never see a NULL template argument here");
1580 break;
Mike Stump11289f42009-09-09 15:08:12 +00001581
Douglas Gregorc40290e2009-03-09 23:48:35 +00001582 case TemplateArgument::Expression: {
1583 Expr *ArgExpr = Arg.getAsExpr();
1584 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1585 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1586 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1587 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001588
Douglas Gregorc40290e2009-03-09 23:48:35 +00001589 // Add the converted template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001590 Decl *D
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00001591 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001592 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorc40290e2009-03-09 23:48:35 +00001593 continue;
1594 }
1595 }
1596 // fall through
Mike Stump11289f42009-09-09 15:08:12 +00001597
Douglas Gregorc40290e2009-03-09 23:48:35 +00001598 case TemplateArgument::Type: {
1599 // We have a template template parameter but the template
1600 // argument does not refer to a template.
1601 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1602 Invalid = true;
1603 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001604 }
1605
Douglas Gregorc40290e2009-03-09 23:48:35 +00001606 case TemplateArgument::Declaration:
1607 // We've already checked this template argument, so just copy
1608 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001609 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001610 break;
Mike Stump11289f42009-09-09 15:08:12 +00001611
Douglas Gregorc40290e2009-03-09 23:48:35 +00001612 case TemplateArgument::Integral:
1613 assert(false && "Integral argument with template template parameter");
1614 break;
Mike Stump11289f42009-09-09 15:08:12 +00001615
Anders Carlssonbc343912009-06-15 17:04:53 +00001616 case TemplateArgument::Pack:
1617 assert(0 && "FIXME: Implement!");
1618 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001619 }
Douglas Gregord32e0282009-02-09 23:23:08 +00001620 }
1621 }
1622
1623 return Invalid;
1624}
1625
1626/// \brief Check a template argument against its corresponding
1627/// template type parameter.
1628///
1629/// This routine implements the semantics of C++ [temp.arg.type]. It
1630/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001631bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
Douglas Gregord32e0282009-02-09 23:23:08 +00001632 QualType Arg, SourceLocation ArgLoc) {
1633 // C++ [temp.arg.type]p2:
1634 // A local type, a type with no linkage, an unnamed type or a type
1635 // compounded from any of these types shall not be used as a
1636 // template-argument for a template type-parameter.
1637 //
1638 // FIXME: Perform the recursive and no-linkage type checks.
1639 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001640 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001641 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001642 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001643 Tag = RecordT;
1644 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1645 return Diag(ArgLoc, diag::err_template_arg_local_type)
1646 << QualType(Tag, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001647 else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001648 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001649 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1650 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1651 return true;
1652 }
1653
1654 return false;
1655}
1656
Douglas Gregorccb07762009-02-11 19:52:55 +00001657/// \brief Checks whether the given template argument is the address
1658/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001659bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1660 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001661 bool Invalid = false;
1662
1663 // See through any implicit casts we added to fix the type.
1664 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1665 Arg = Cast->getSubExpr();
1666
Sebastian Redl576fd422009-05-10 18:38:11 +00001667 // C++0x allows nullptr, and there's no further checking to be done for that.
1668 if (Arg->getType()->isNullPtrType())
1669 return false;
1670
Douglas Gregorccb07762009-02-11 19:52:55 +00001671 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001672 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001673 // A template-argument for a non-type, non-template
1674 // template-parameter shall be one of: [...]
1675 //
1676 // -- the address of an object or function with external
1677 // linkage, including function templates and function
1678 // template-ids but excluding non-static class members,
1679 // expressed as & id-expression where the & is optional if
1680 // the name refers to a function or array, or if the
1681 // corresponding template-parameter is a reference; or
1682 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001683
Douglas Gregorccb07762009-02-11 19:52:55 +00001684 // Ignore (and complain about) any excess parentheses.
1685 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1686 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001687 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001688 diag::err_template_arg_extra_parens)
1689 << Arg->getSourceRange();
1690 Invalid = true;
1691 }
1692
1693 Arg = Parens->getSubExpr();
1694 }
1695
1696 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1697 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1698 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1699 } else
1700 DRE = dyn_cast<DeclRefExpr>(Arg);
1701
1702 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00001703 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001704 diag::err_template_arg_not_object_or_func_form)
1705 << Arg->getSourceRange();
1706
1707 // Cannot refer to non-static data members
1708 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1709 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1710 << Field << Arg->getSourceRange();
1711
1712 // Cannot refer to non-static member functions
1713 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1714 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00001715 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001716 diag::err_template_arg_method)
1717 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001718
Douglas Gregorccb07762009-02-11 19:52:55 +00001719 // Functions must have external linkage.
1720 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1721 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00001722 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001723 diag::err_template_arg_function_not_extern)
1724 << Func << Arg->getSourceRange();
1725 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1726 << true;
1727 return true;
1728 }
1729
1730 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001731 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00001732 return Invalid;
1733 }
1734
1735 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1736 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00001737 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001738 diag::err_template_arg_object_not_extern)
1739 << Var << Arg->getSourceRange();
1740 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1741 << true;
1742 return true;
1743 }
1744
1745 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001746 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00001747 return Invalid;
1748 }
Mike Stump11289f42009-09-09 15:08:12 +00001749
Douglas Gregorccb07762009-02-11 19:52:55 +00001750 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001751 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001752 diag::err_template_arg_not_object_or_func)
1753 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001754 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001755 diag::note_template_arg_refers_here);
1756 return true;
1757}
1758
1759/// \brief Checks whether the given template argument is a pointer to
1760/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump11289f42009-09-09 15:08:12 +00001761bool
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001762Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001763 bool Invalid = false;
1764
1765 // See through any implicit casts we added to fix the type.
1766 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1767 Arg = Cast->getSubExpr();
1768
Sebastian Redl576fd422009-05-10 18:38:11 +00001769 // C++0x allows nullptr, and there's no further checking to be done for that.
1770 if (Arg->getType()->isNullPtrType())
1771 return false;
1772
Douglas Gregorccb07762009-02-11 19:52:55 +00001773 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001774 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001775 // A template-argument for a non-type, non-template
1776 // template-parameter shall be one of: [...]
1777 //
1778 // -- a pointer to member expressed as described in 5.3.1.
1779 QualifiedDeclRefExpr *DRE = 0;
1780
1781 // Ignore (and complain about) any excess parentheses.
1782 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1783 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001784 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001785 diag::err_template_arg_extra_parens)
1786 << Arg->getSourceRange();
1787 Invalid = true;
1788 }
1789
1790 Arg = Parens->getSubExpr();
1791 }
1792
1793 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1794 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1795 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1796
1797 if (!DRE)
1798 return Diag(Arg->getSourceRange().getBegin(),
1799 diag::err_template_arg_not_pointer_to_member_form)
1800 << Arg->getSourceRange();
1801
1802 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1803 assert((isa<FieldDecl>(DRE->getDecl()) ||
1804 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1805 "Only non-static member pointers can make it here");
1806
1807 // Okay: this is the address of a non-static member, and therefore
1808 // a member pointer constant.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001809 Member = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00001810 return Invalid;
1811 }
1812
1813 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001814 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001815 diag::err_template_arg_not_pointer_to_member_form)
1816 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001817 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001818 diag::note_template_arg_refers_here);
1819 return true;
1820}
1821
Douglas Gregord32e0282009-02-09 23:23:08 +00001822/// \brief Check a template argument against its corresponding
1823/// non-type template parameter.
1824///
Douglas Gregor463421d2009-03-03 04:44:36 +00001825/// This routine implements the semantics of C++ [temp.arg.nontype].
1826/// It returns true if an error occurred, and false otherwise. \p
1827/// InstantiatedParamType is the type of the non-type template
1828/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001829///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001830/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00001831bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00001832 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001833 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001834 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1835
Douglas Gregor86560402009-02-10 23:36:10 +00001836 // If either the parameter has a dependent type or the argument is
1837 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001838 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00001839 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1840 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001841 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00001842 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001843 }
Douglas Gregor86560402009-02-10 23:36:10 +00001844
1845 // C++ [temp.arg.nontype]p5:
1846 // The following conversions are performed on each expression used
1847 // as a non-type template-argument. If a non-type
1848 // template-argument cannot be converted to the type of the
1849 // corresponding template-parameter then the program is
1850 // ill-formed.
1851 //
1852 // -- for a non-type template-parameter of integral or
1853 // enumeration type, integral promotions (4.5) and integral
1854 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00001855 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001856 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00001857 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00001858 // C++ [temp.arg.nontype]p1:
1859 // A template-argument for a non-type, non-template
1860 // template-parameter shall be one of:
1861 //
1862 // -- an integral constant-expression of integral or enumeration
1863 // type; or
1864 // -- the name of a non-type template-parameter; or
1865 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001866 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00001867 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001868 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001869 diag::err_template_arg_not_integral_or_enumeral)
1870 << ArgType << Arg->getSourceRange();
1871 Diag(Param->getLocation(), diag::note_template_param_here);
1872 return true;
1873 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001874 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00001875 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1876 << ArgType << Arg->getSourceRange();
1877 return true;
1878 }
1879
1880 // FIXME: We need some way to more easily get the unqualified form
1881 // of the types without going all the way to the
1882 // canonical type.
1883 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1884 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1885 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1886 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1887
1888 // Try to convert the argument to the parameter's type.
1889 if (ParamType == ArgType) {
1890 // Okay: no conversion necessary
1891 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1892 !ParamType->isEnumeralType()) {
1893 // This is an integral promotion or conversion.
1894 ImpCastExprToType(Arg, ParamType);
1895 } else {
1896 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00001897 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001898 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00001899 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00001900 Diag(Param->getLocation(), diag::note_template_param_here);
1901 return true;
1902 }
1903
Douglas Gregor52aba872009-03-14 00:20:21 +00001904 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00001905 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001906 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00001907
1908 if (!Arg->isValueDependent()) {
1909 // Check that an unsigned parameter does not receive a negative
1910 // value.
1911 if (IntegerType->isUnsignedIntegerType()
1912 && (Value.isSigned() && Value.isNegative())) {
1913 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1914 << Value.toString(10) << Param->getType()
1915 << Arg->getSourceRange();
1916 Diag(Param->getLocation(), diag::note_template_param_here);
1917 return true;
1918 }
1919
1920 // Check that we don't overflow the template parameter type.
1921 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1922 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00001923 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00001924 diag::err_template_arg_too_large)
1925 << Value.toString(10) << Param->getType()
1926 << Arg->getSourceRange();
1927 Diag(Param->getLocation(), diag::note_template_param_here);
1928 return true;
1929 }
1930
1931 if (Value.getBitWidth() != AllowedBits)
1932 Value.extOrTrunc(AllowedBits);
1933 Value.setIsSigned(IntegerType->isSignedIntegerType());
1934 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001935
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001936 // Add the value of this argument to the list of converted
1937 // arguments. We use the bitwidth and signedness of the template
1938 // parameter.
1939 if (Arg->isValueDependent()) {
1940 // The argument is value-dependent. Create a new
1941 // TemplateArgument with the converted expression.
1942 Converted = TemplateArgument(Arg);
1943 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001944 }
1945
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001946 Converted = TemplateArgument(StartLoc, Value,
Mike Stump11289f42009-09-09 15:08:12 +00001947 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001948 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00001949 return false;
1950 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001951
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001952 // Handle pointer-to-function, reference-to-function, and
1953 // pointer-to-member-function all in (roughly) the same way.
1954 if (// -- For a non-type template-parameter of type pointer to
1955 // function, only the function-to-pointer conversion (4.3) is
1956 // applied. If the template-argument represents a set of
1957 // overloaded functions (or a pointer to such), the matching
1958 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00001959 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001960 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001961 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001962 // -- For a non-type template-parameter of type reference to
1963 // function, no conversions apply. If the template-argument
1964 // represents a set of overloaded functions, the matching
1965 // function is selected from the set (13.4).
1966 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001967 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001968 // -- For a non-type template-parameter of type pointer to
1969 // member function, no conversions apply. If the
1970 // template-argument represents a set of overloaded member
1971 // functions, the matching member function is selected from
1972 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00001973 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001974 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001975 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001976 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00001977 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00001978 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001979 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00001980 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1981 ParamType->isMemberPointerType())) {
1982 ArgType = ParamType;
1983 ImpCastExprToType(Arg, ParamType);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001984 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001985 ArgType = Context.getPointerType(ArgType);
1986 ImpCastExprToType(Arg, ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001987 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001988 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00001989 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1990 return true;
1991
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001992 FixOverloadedFunctionReference(Arg, Fn);
1993 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001994 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001995 ArgType = Context.getPointerType(Arg->getType());
1996 ImpCastExprToType(Arg, ArgType);
1997 }
1998 }
1999
Mike Stump11289f42009-09-09 15:08:12 +00002000 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002001 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002002 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002003 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002004 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002005 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002006 Diag(Param->getLocation(), diag::note_template_param_here);
2007 return true;
2008 }
Mike Stump11289f42009-09-09 15:08:12 +00002009
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002010 if (ParamType->isMemberPointerType()) {
2011 NamedDecl *Member = 0;
2012 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2013 return true;
2014
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002015 if (Member)
2016 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002017 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002018 return false;
2019 }
Mike Stump11289f42009-09-09 15:08:12 +00002020
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002021 NamedDecl *Entity = 0;
2022 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2023 return true;
2024
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002025 if (Entity)
2026 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002027 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002028 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002029 }
2030
Chris Lattner696197c2009-02-20 21:37:53 +00002031 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002032 // -- for a non-type template-parameter of type pointer to
2033 // object, qualification conversions (4.4) and the
2034 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002035 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002036 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002037 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002038
Sebastian Redl576fd422009-05-10 18:38:11 +00002039 if (ArgType->isNullPtrType()) {
2040 ArgType = ParamType;
2041 ImpCastExprToType(Arg, ParamType);
2042 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002043 ArgType = Context.getArrayDecayedType(ArgType);
2044 ImpCastExprToType(Arg, ArgType);
Douglas Gregora9faa442009-02-11 00:44:29 +00002045 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002046
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002047 if (IsQualificationConversion(ArgType, ParamType)) {
2048 ArgType = ParamType;
2049 ImpCastExprToType(Arg, ParamType);
2050 }
Mike Stump11289f42009-09-09 15:08:12 +00002051
Douglas Gregor1515f762009-02-11 18:22:40 +00002052 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002053 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002054 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002055 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002056 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002057 Diag(Param->getLocation(), diag::note_template_param_here);
2058 return true;
2059 }
Mike Stump11289f42009-09-09 15:08:12 +00002060
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002061 NamedDecl *Entity = 0;
2062 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2063 return true;
2064
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002065 if (Entity)
2066 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002067 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002068 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002069 }
Mike Stump11289f42009-09-09 15:08:12 +00002070
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002071 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002072 // -- For a non-type template-parameter of type reference to
2073 // object, no conversions apply. The type referred to by the
2074 // reference may be more cv-qualified than the (otherwise
2075 // identical) type of the template-argument. The
2076 // template-parameter is bound directly to the
2077 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002078 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002079 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002080
Douglas Gregor1515f762009-02-11 18:22:40 +00002081 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002082 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002083 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002084 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002085 << Arg->getSourceRange();
2086 Diag(Param->getLocation(), diag::note_template_param_here);
2087 return true;
2088 }
2089
Mike Stump11289f42009-09-09 15:08:12 +00002090 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002091 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2092 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002093
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002094 if ((ParamQuals | ArgQuals) != ParamQuals) {
2095 Diag(Arg->getSourceRange().getBegin(),
2096 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002097 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002098 << Arg->getSourceRange();
2099 Diag(Param->getLocation(), diag::note_template_param_here);
2100 return true;
2101 }
Mike Stump11289f42009-09-09 15:08:12 +00002102
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002103 NamedDecl *Entity = 0;
2104 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2105 return true;
2106
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002107 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002108 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002109 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002110 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002111
2112 // -- For a non-type template-parameter of type pointer to data
2113 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002114 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002115 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2116
Douglas Gregor1515f762009-02-11 18:22:40 +00002117 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002118 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002119 } else if (ArgType->isNullPtrType()) {
2120 ImpCastExprToType(Arg, ParamType);
Douglas Gregor0e558532009-02-11 16:16:59 +00002121 } else if (IsQualificationConversion(ArgType, ParamType)) {
2122 ImpCastExprToType(Arg, ParamType);
2123 } else {
2124 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002125 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002126 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002127 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002128 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002129 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002130 }
2131
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002132 NamedDecl *Member = 0;
2133 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2134 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002135
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002136 if (Member)
2137 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002138 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002139 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00002140}
2141
2142/// \brief Check a template argument against its corresponding
2143/// template template parameter.
2144///
2145/// This routine implements the semantics of C++ [temp.arg.template].
2146/// It returns true if an error occurred, and false otherwise.
2147bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2148 DeclRefExpr *Arg) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002149 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2150 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2151
2152 // C++ [temp.arg.template]p1:
2153 // A template-argument for a template template-parameter shall be
2154 // the name of a class template, expressed as id-expression. Only
2155 // primary class templates are considered when matching the
2156 // template template argument with the corresponding parameter;
2157 // partial specializations are not considered even if their
2158 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002159 //
2160 // Note that we also allow template template parameters here, which
2161 // will happen when we are dealing with, e.g., class template
2162 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002163 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002164 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002165 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002166 "Only function templates are possible here");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002167 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2168 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002169 << Template;
2170 }
2171
2172 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2173 Param->getTemplateParameters(),
2174 true, true,
2175 Arg->getSourceRange().getBegin());
Douglas Gregord32e0282009-02-09 23:23:08 +00002176}
2177
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002178/// \brief Determine whether the given template parameter lists are
2179/// equivalent.
2180///
Mike Stump11289f42009-09-09 15:08:12 +00002181/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002182/// source code as part of a new template declaration.
2183///
2184/// \param Old The old template parameter list, typically found via
2185/// name lookup of the template declared with this template parameter
2186/// list.
2187///
2188/// \param Complain If true, this routine will produce a diagnostic if
2189/// the template parameter lists are not equivalent.
2190///
Douglas Gregor85e0f662009-02-10 00:24:35 +00002191/// \param IsTemplateTemplateParm If true, this routine is being
2192/// called to compare the template parameter lists of a template
2193/// template parameter.
2194///
2195/// \param TemplateArgLoc If this source location is valid, then we
2196/// are actually checking the template parameter list of a template
2197/// argument (New) against the template parameter list of its
2198/// corresponding template template parameter (Old). We produce
2199/// slightly different diagnostics in this scenario.
2200///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002201/// \returns True if the template parameter lists are equal, false
2202/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002203bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002204Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2205 TemplateParameterList *Old,
2206 bool Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002207 bool IsTemplateTemplateParm,
2208 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002209 if (Old->size() != New->size()) {
2210 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002211 unsigned NextDiag = diag::err_template_param_list_different_arity;
2212 if (TemplateArgLoc.isValid()) {
2213 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2214 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002215 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002216 Diag(New->getTemplateLoc(), NextDiag)
2217 << (New->size() > Old->size())
2218 << IsTemplateTemplateParm
2219 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002220 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2221 << IsTemplateTemplateParm
2222 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2223 }
2224
2225 return false;
2226 }
2227
2228 for (TemplateParameterList::iterator OldParm = Old->begin(),
2229 OldParmEnd = Old->end(), NewParm = New->begin();
2230 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2231 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002232 if (Complain) {
2233 unsigned NextDiag = diag::err_template_param_different_kind;
2234 if (TemplateArgLoc.isValid()) {
2235 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2236 NextDiag = diag::note_template_param_different_kind;
2237 }
2238 Diag((*NewParm)->getLocation(), NextDiag)
2239 << IsTemplateTemplateParm;
2240 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2241 << IsTemplateTemplateParm;
Douglas Gregor85e0f662009-02-10 00:24:35 +00002242 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002243 return false;
2244 }
2245
2246 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2247 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002248 // know we're at the same index).
2249#if 0
Mike Stump87c57ac2009-05-16 07:39:55 +00002250 // FIXME: Enable this code in debug mode *after* we properly go through
2251 // and "instantiate" the template parameter lists of template template
2252 // parameters. It's only after this instantiation that (1) any dependent
2253 // types within the template parameter list of the template template
2254 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregor85e0f662009-02-10 00:24:35 +00002255 // will match up.
Mike Stump11289f42009-09-09 15:08:12 +00002256 QualType OldParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002257 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
Mike Stump11289f42009-09-09 15:08:12 +00002258 QualType NewParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002259 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
Mike Stump11289f42009-09-09 15:08:12 +00002260 assert(Context.getCanonicalType(OldParmType) ==
2261 Context.getCanonicalType(NewParmType) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002262 "type parameter mismatch?");
2263#endif
Mike Stump11289f42009-09-09 15:08:12 +00002264 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002265 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2266 // The types of non-type template parameters must agree.
2267 NonTypeTemplateParmDecl *NewNTTP
2268 = cast<NonTypeTemplateParmDecl>(*NewParm);
2269 if (Context.getCanonicalType(OldNTTP->getType()) !=
2270 Context.getCanonicalType(NewNTTP->getType())) {
2271 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002272 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2273 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002274 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002275 diag::err_template_arg_template_params_mismatch);
2276 NextDiag = diag::note_template_nontype_parm_different_type;
2277 }
2278 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002279 << NewNTTP->getType()
2280 << IsTemplateTemplateParm;
Mike Stump11289f42009-09-09 15:08:12 +00002281 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002282 diag::note_template_nontype_parm_prev_declaration)
2283 << OldNTTP->getType();
2284 }
2285 return false;
2286 }
2287 } else {
2288 // The template parameter lists of template template
2289 // parameters must agree.
2290 // FIXME: Could we perform a faster "type" comparison here?
Mike Stump11289f42009-09-09 15:08:12 +00002291 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002292 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002293 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002294 = cast<TemplateTemplateParmDecl>(*OldParm);
2295 TemplateTemplateParmDecl *NewTTP
2296 = cast<TemplateTemplateParmDecl>(*NewParm);
2297 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2298 OldTTP->getTemplateParameters(),
2299 Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002300 /*IsTemplateTemplateParm=*/true,
2301 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002302 return false;
2303 }
2304 }
2305
2306 return true;
2307}
2308
2309/// \brief Check whether a template can be declared within this scope.
2310///
2311/// If the template declaration is valid in this scope, returns
2312/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002313bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002314Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002315 // Find the nearest enclosing declaration scope.
2316 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2317 (S->getFlags() & Scope::TemplateParamScope) != 0)
2318 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002319
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002320 // C++ [temp]p2:
2321 // A template-declaration can appear only as a namespace scope or
2322 // class scope declaration.
2323 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002324 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2325 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002326 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002327 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002328
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002329 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002330 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002331
2332 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2333 return false;
2334
Mike Stump11289f42009-09-09 15:08:12 +00002335 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002336 diag::err_template_outside_namespace_or_class_scope)
2337 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002338}
Douglas Gregor67a65642009-02-17 23:15:12 +00002339
Douglas Gregorf61eca92009-05-13 18:28:20 +00002340/// \brief Check whether a class template specialization or explicit
2341/// instantiation in the current context is well-formed.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002342///
Douglas Gregorf61eca92009-05-13 18:28:20 +00002343/// This routine determines whether a class template specialization or
Mike Stump11289f42009-09-09 15:08:12 +00002344/// explicit instantiation can be declared in the current context
2345/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2346/// appropriate diagnostics if there was an error. It returns true if
Douglas Gregorf61eca92009-05-13 18:28:20 +00002347// there was an error that we cannot recover from, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002348bool
Douglas Gregorf47b9112009-02-25 22:02:03 +00002349Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2350 ClassTemplateSpecializationDecl *PrevDecl,
2351 SourceLocation TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002352 SourceRange ScopeSpecifierRange,
Douglas Gregor30b01972009-06-12 22:21:45 +00002353 bool PartialSpecialization,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002354 bool ExplicitInstantiation) {
Douglas Gregorf47b9112009-02-25 22:02:03 +00002355 // C++ [temp.expl.spec]p2:
2356 // An explicit specialization shall be declared in the namespace
2357 // of which the template is a member, or, for member templates, in
2358 // the namespace of which the enclosing class or enclosing class
2359 // template is a member. An explicit specialization of a member
2360 // function, member class or static data member of a class
2361 // template shall be declared in the namespace of which the class
2362 // template is a member. Such a declaration may also be a
2363 // definition. If the declaration is not a definition, the
2364 // specialization may be defined later in the name- space in which
2365 // the explicit specialization was declared, or in a namespace
2366 // that encloses the one in which the explicit specialization was
2367 // declared.
2368 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor30b01972009-06-12 22:21:45 +00002369 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002370 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002371 << Kind << ClassTemplate;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002372 return true;
2373 }
2374
2375 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00002376 DeclContext *TemplateContext
Douglas Gregorf47b9112009-02-25 22:02:03 +00002377 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorf61eca92009-05-13 18:28:20 +00002378 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2379 !ExplicitInstantiation) {
Douglas Gregorf47b9112009-02-25 22:02:03 +00002380 // There is no prior declaration of this entity, so this
2381 // specialization must be in the same context as the template
2382 // itself.
2383 if (DC != TemplateContext) {
2384 if (isa<TranslationUnitDecl>(TemplateContext))
2385 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor30b01972009-06-12 22:21:45 +00002386 << PartialSpecialization
Douglas Gregorf47b9112009-02-25 22:02:03 +00002387 << ClassTemplate << ScopeSpecifierRange;
2388 else if (isa<NamespaceDecl>(TemplateContext))
2389 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Mike Stump11289f42009-09-09 15:08:12 +00002390 << PartialSpecialization << ClassTemplate
Douglas Gregor30b01972009-06-12 22:21:45 +00002391 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002392
2393 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2394 }
2395
2396 return false;
2397 }
2398
2399 // We have a previous declaration of this entity. Make sure that
2400 // this redeclaration (or definition) occurs in an enclosing namespace.
2401 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002402 // FIXME: In C++98, we would like to turn these errors into warnings,
2403 // dependent on a -Wc++0x flag.
Douglas Gregorf61eca92009-05-13 18:28:20 +00002404 bool SuppressedDiag = false;
Douglas Gregor30b01972009-06-12 22:21:45 +00002405 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorf61eca92009-05-13 18:28:20 +00002406 if (isa<TranslationUnitDecl>(TemplateContext)) {
2407 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2408 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002409 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorf61eca92009-05-13 18:28:20 +00002410 else
2411 SuppressedDiag = true;
2412 } else if (isa<NamespaceDecl>(TemplateContext)) {
2413 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2414 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002415 << Kind << ClassTemplate
Douglas Gregorf61eca92009-05-13 18:28:20 +00002416 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Mike Stump11289f42009-09-09 15:08:12 +00002417 else
Douglas Gregorf61eca92009-05-13 18:28:20 +00002418 SuppressedDiag = true;
2419 }
Mike Stump11289f42009-09-09 15:08:12 +00002420
Douglas Gregorf61eca92009-05-13 18:28:20 +00002421 if (!SuppressedDiag)
2422 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002423 }
2424
2425 return false;
2426}
2427
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002428/// \brief Check the non-type template arguments of a class template
2429/// partial specialization according to C++ [temp.class.spec]p9.
2430///
Douglas Gregor09a30232009-06-12 22:08:06 +00002431/// \param TemplateParams the template parameters of the primary class
2432/// template.
2433///
2434/// \param TemplateArg the template arguments of the class template
2435/// partial specialization.
2436///
2437/// \param MirrorsPrimaryTemplate will be set true if the class
2438/// template partial specialization arguments are identical to the
2439/// implicit template arguments of the primary template. This is not
2440/// necessarily an error (C++0x), and it is left to the caller to diagnose
2441/// this condition when it is an error.
2442///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002443/// \returns true if there was an error, false otherwise.
2444bool Sema::CheckClassTemplatePartialSpecializationArgs(
2445 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002446 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002447 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002448 // FIXME: the interface to this function will have to change to
2449 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002450 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002451
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002452 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002453
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002454 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002455 // Determine whether the template argument list of the partial
2456 // specialization is identical to the implicit argument list of
2457 // the primary template. The caller may need to diagnostic this as
2458 // an error per C++ [temp.class.spec]p9b3.
2459 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002460 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002461 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2462 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002463 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002464 MirrorsPrimaryTemplate = false;
2465 } else if (TemplateTemplateParmDecl *TTP
2466 = dyn_cast<TemplateTemplateParmDecl>(
2467 TemplateParams->getParam(I))) {
2468 // FIXME: We should settle on either Declaration storage or
2469 // Expression storage for template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002470 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor09a30232009-06-12 22:08:06 +00002471 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson40c1d492009-06-13 18:20:51 +00002472 ArgList[I].getAsDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002473 if (!ArgDecl)
Mike Stump11289f42009-09-09 15:08:12 +00002474 if (DeclRefExpr *DRE
Anders Carlsson40c1d492009-06-13 18:20:51 +00002475 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002476 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2477
2478 if (!ArgDecl ||
2479 ArgDecl->getIndex() != TTP->getIndex() ||
2480 ArgDecl->getDepth() != TTP->getDepth())
2481 MirrorsPrimaryTemplate = false;
2482 }
2483 }
2484
Mike Stump11289f42009-09-09 15:08:12 +00002485 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002486 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002487 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002488 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002489 }
2490
Anders Carlsson40c1d492009-06-13 18:20:51 +00002491 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002492 if (!ArgExpr) {
2493 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002494 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002495 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002496
2497 // C++ [temp.class.spec]p8:
2498 // A non-type argument is non-specialized if it is the name of a
2499 // non-type parameter. All other non-type arguments are
2500 // specialized.
2501 //
2502 // Below, we check the two conditions that only apply to
2503 // specialized non-type arguments, so skip any non-specialized
2504 // arguments.
2505 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002506 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002507 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002508 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002509 (Param->getIndex() != NTTP->getIndex() ||
2510 Param->getDepth() != NTTP->getDepth()))
2511 MirrorsPrimaryTemplate = false;
2512
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002513 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002514 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002515
2516 // C++ [temp.class.spec]p9:
2517 // Within the argument list of a class template partial
2518 // specialization, the following restrictions apply:
2519 // -- A partially specialized non-type argument expression
2520 // shall not involve a template parameter of the partial
2521 // specialization except when the argument expression is a
2522 // simple identifier.
2523 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002524 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002525 diag::err_dependent_non_type_arg_in_partial_spec)
2526 << ArgExpr->getSourceRange();
2527 return true;
2528 }
2529
2530 // -- The type of a template parameter corresponding to a
2531 // specialized non-type argument shall not be dependent on a
2532 // parameter of the specialization.
2533 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002534 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002535 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2536 << Param->getType()
2537 << ArgExpr->getSourceRange();
2538 Diag(Param->getLocation(), diag::note_template_param_here);
2539 return true;
2540 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002541
2542 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002543 }
2544
2545 return false;
2546}
2547
Douglas Gregorc08f4892009-03-25 00:13:59 +00002548Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002549Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2550 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002551 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002552 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002553 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002554 SourceLocation TemplateNameLoc,
2555 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002556 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002557 SourceLocation *TemplateArgLocs,
2558 SourceLocation RAngleLoc,
2559 AttributeList *Attr,
2560 MultiTemplateParamsArg TemplateParameterLists) {
John McCall06f6fe8d2009-09-04 01:14:41 +00002561 assert(TUK == TUK_Declaration || TUK == TUK_Definition);
2562
Douglas Gregor67a65642009-02-17 23:15:12 +00002563 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002564 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002565 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002566 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002567
Douglas Gregor2373c592009-05-31 09:31:02 +00002568 bool isPartialSpecialization = false;
2569
Douglas Gregorf47b9112009-02-25 22:02:03 +00002570 // Check the validity of the template headers that introduce this
2571 // template.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002572 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002573 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2574 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002575 TemplateParameterLists.size());
2576 if (TemplateParams && TemplateParams->size() > 0) {
2577 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002578
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002579 // C++ [temp.class.spec]p10:
2580 // The template parameter list of a specialization shall not
2581 // contain default template argument values.
2582 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2583 Decl *Param = TemplateParams->getParam(I);
2584 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2585 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002586 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002587 diag::err_default_arg_in_partial_spec);
2588 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2589 }
2590 } else if (NonTypeTemplateParmDecl *NTTP
2591 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2592 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002593 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002594 diag::err_default_arg_in_partial_spec)
2595 << DefArg->getSourceRange();
2596 NTTP->setDefaultArgument(0);
2597 DefArg->Destroy(Context);
2598 }
2599 } else {
2600 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2601 if (Expr *DefArg = TTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002602 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002603 diag::err_default_arg_in_partial_spec)
2604 << DefArg->getSourceRange();
2605 TTP->setDefaultArgument(0);
2606 DefArg->Destroy(Context);
Douglas Gregord5222052009-06-12 19:43:02 +00002607 }
2608 }
2609 }
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002610 } else if (!TemplateParams)
2611 Diag(KWLoc, diag::err_template_spec_needs_header)
2612 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregorf47b9112009-02-25 22:02:03 +00002613
Douglas Gregor67a65642009-02-17 23:15:12 +00002614 // Check that the specialization uses the same tag kind as the
2615 // original template.
2616 TagDecl::TagKind Kind;
2617 switch (TagSpec) {
2618 default: assert(0 && "Unknown tag type!");
2619 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2620 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2621 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2622 }
Douglas Gregord9034f02009-05-14 16:41:31 +00002623 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00002624 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00002625 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00002626 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00002627 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00002628 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00002629 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00002630 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00002631 diag::note_previous_use);
2632 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2633 }
2634
Douglas Gregorc40290e2009-03-09 23:48:35 +00002635 // Translate the parser's template argument list in our AST format.
2636 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2637 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2638
Douglas Gregor67a65642009-02-17 23:15:12 +00002639 // Check that the template argument list is well-formed for this
2640 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002641 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2642 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00002643 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002644 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00002645 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002646 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002647
Mike Stump11289f42009-09-09 15:08:12 +00002648 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00002649 ClassTemplate->getTemplateParameters()->size()) &&
2650 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00002651
Douglas Gregor2373c592009-05-31 09:31:02 +00002652 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00002653 // corresponds to these arguments.
2654 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00002655 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002656 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002657 if (CheckClassTemplatePartialSpecializationArgs(
2658 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002659 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002660 return true;
2661
Douglas Gregor09a30232009-06-12 22:08:06 +00002662 if (MirrorsPrimaryTemplate) {
2663 // C++ [temp.class.spec]p9b3:
2664 //
Mike Stump11289f42009-09-09 15:08:12 +00002665 // -- The argument list of the specialization shall not be identical
2666 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00002667 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00002668 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00002669 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00002670 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00002671 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00002672 ClassTemplate->getIdentifier(),
2673 TemplateNameLoc,
2674 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002675 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00002676 AS_none);
2677 }
2678
Douglas Gregor2373c592009-05-31 09:31:02 +00002679 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00002680 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002681 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002682 Converted.flatSize(),
2683 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002684 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002685 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002686 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002687 Converted.flatSize(),
2688 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00002689 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002690 ClassTemplateSpecializationDecl *PrevDecl = 0;
2691
2692 if (isPartialSpecialization)
2693 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00002694 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00002695 InsertPos);
2696 else
2697 PrevDecl
2698 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00002699
2700 ClassTemplateSpecializationDecl *Specialization = 0;
2701
Douglas Gregorf47b9112009-02-25 22:02:03 +00002702 // Check whether we can declare a class template specialization in
2703 // the current scope.
2704 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002705 TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002706 SS.getRange(),
Douglas Gregor30b01972009-06-12 22:21:45 +00002707 isPartialSpecialization,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002708 /*ExplicitInstantiation=*/false))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002709 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002710
Douglas Gregor15301382009-07-30 17:40:51 +00002711 // The canonical type
2712 QualType CanonType;
Douglas Gregor67a65642009-02-17 23:15:12 +00002713 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2714 // Since the only prior class template specialization with these
2715 // arguments was referenced but not declared, reuse that
2716 // declaration node as our own, updating its source location to
2717 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002718 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00002719 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00002720 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00002721 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00002722 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00002723 // Build the canonical type that describes the converted template
2724 // arguments of the class template partial specialization.
2725 CanonType = Context.getTemplateSpecializationType(
2726 TemplateName(ClassTemplate),
2727 Converted.getFlatArguments(),
2728 Converted.flatSize());
2729
Douglas Gregor2373c592009-05-31 09:31:02 +00002730 // Create a new class template partial specialization declaration node.
Mike Stump11289f42009-09-09 15:08:12 +00002731 TemplateParameterList *TemplateParams
Douglas Gregor2373c592009-05-31 09:31:02 +00002732 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2733 ClassTemplatePartialSpecializationDecl *PrevPartial
2734 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002735 ClassTemplatePartialSpecializationDecl *Partial
2736 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00002737 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002738 TemplateNameLoc,
2739 TemplateParams,
2740 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002741 Converted,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002742 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00002743
2744 if (PrevPartial) {
2745 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2746 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2747 } else {
2748 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2749 }
2750 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00002751
2752 // Check that all of the template parameters of the class template
2753 // partial specialization are deducible from the template
2754 // arguments. If not, this class template partial specialization
2755 // will never be used.
2756 llvm::SmallVector<bool, 8> DeducibleParams;
2757 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002758 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2759 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00002760 unsigned NumNonDeducible = 0;
2761 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2762 if (!DeducibleParams[I])
2763 ++NumNonDeducible;
2764
2765 if (NumNonDeducible) {
2766 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2767 << (NumNonDeducible > 1)
2768 << SourceRange(TemplateNameLoc, RAngleLoc);
2769 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2770 if (!DeducibleParams[I]) {
2771 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2772 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00002773 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002774 diag::note_partial_spec_unused_parameter)
2775 << Param->getDeclName();
2776 else
Mike Stump11289f42009-09-09 15:08:12 +00002777 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002778 diag::note_partial_spec_unused_parameter)
2779 << std::string("<anonymous>");
2780 }
2781 }
2782 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002783 } else {
2784 // Create a new class template specialization declaration node for
2785 // this explicit specialization.
2786 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00002787 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00002788 ClassTemplate->getDeclContext(),
2789 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002790 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002791 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00002792 PrevDecl);
2793
2794 if (PrevDecl) {
2795 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2796 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2797 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002798 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00002799 InsertPos);
2800 }
Douglas Gregor15301382009-07-30 17:40:51 +00002801
2802 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002803 }
2804
2805 // Note that this is an explicit specialization.
2806 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2807
2808 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002809 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002810 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002811 // FIXME: Should also handle explicit specialization after implicit
2812 // instantiation with a special diagnostic.
Douglas Gregor67a65642009-02-17 23:15:12 +00002813 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002814 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00002815 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00002816 Diag(Def->getLocation(), diag::note_previous_definition);
2817 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00002818 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002819 }
2820 }
2821
Douglas Gregord56a91e2009-02-26 22:19:44 +00002822 // Build the fully-sugared type for this class template
2823 // specialization as the user wrote in the specialization
2824 // itself. This means that we'll pretty-print the type retrieved
2825 // from the specialization's declaration the way that the user
2826 // actually wrote the specialization, rather than formatting the
2827 // name based on the "canonical" representation used to store the
2828 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002829 QualType WrittenTy
2830 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002831 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00002832 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00002833 CanonType);
Douglas Gregordc572a32009-03-30 22:58:21 +00002834 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002835 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00002836
Douglas Gregor1e249f82009-02-25 22:18:32 +00002837 // C++ [temp.expl.spec]p9:
2838 // A template explicit specialization is in the scope of the
2839 // namespace in which the template was defined.
2840 //
2841 // We actually implement this paragraph where we set the semantic
2842 // context (in the creation of the ClassTemplateSpecializationDecl),
2843 // but we also maintain the lexical context where the actual
2844 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00002845 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00002846
Douglas Gregor67a65642009-02-17 23:15:12 +00002847 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002848 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00002849 Specialization->startDefinition();
2850
2851 // Add the specialization into its lexical context, so that it can
2852 // be seen when iterating through the list of declarations in that
2853 // context. However, specializations are not found by name lookup.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002854 CurContext->addDecl(Specialization);
Chris Lattner83f095c2009-03-28 19:18:32 +00002855 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002856}
Douglas Gregor333489b2009-03-27 23:10:48 +00002857
Mike Stump11289f42009-09-09 15:08:12 +00002858Sema::DeclPtrTy
2859Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002860 MultiTemplateParamsArg TemplateParameterLists,
2861 Declarator &D) {
2862 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2863}
2864
Mike Stump11289f42009-09-09 15:08:12 +00002865Sema::DeclPtrTy
2866Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002867 MultiTemplateParamsArg TemplateParameterLists,
2868 Declarator &D) {
2869 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2870 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2871 "Not a function declarator!");
2872 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00002873
Douglas Gregor17a7c122009-06-24 00:54:41 +00002874 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00002875 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00002876 }
Mike Stump11289f42009-09-09 15:08:12 +00002877
Douglas Gregor17a7c122009-06-24 00:54:41 +00002878 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002879
2880 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002881 move(TemplateParameterLists),
2882 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002883 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00002884 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00002885 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002886 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00002887 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2888 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002889 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00002890}
2891
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002892/// \brief Perform semantic analysis for the given function template
2893/// specialization.
2894///
2895/// This routine performs all of the semantic analysis required for an
2896/// explicit function template specialization. On successful completion,
2897/// the function declaration \p FD will become a function template
2898/// specialization.
2899///
2900/// \param FD the function declaration, which will be updated to become a
2901/// function template specialization.
2902///
2903/// \param HasExplicitTemplateArgs whether any template arguments were
2904/// explicitly provided.
2905///
2906/// \param LAngleLoc the location of the left angle bracket ('<'), if
2907/// template arguments were explicitly provided.
2908///
2909/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
2910/// if any.
2911///
2912/// \param NumExplicitTemplateArgs the number of explicitly-provided template
2913/// arguments. This number may be zero even when HasExplicitTemplateArgs is
2914/// true as in, e.g., \c void sort<>(char*, char*);
2915///
2916/// \param RAngleLoc the location of the right angle bracket ('>'), if
2917/// template arguments were explicitly provided.
2918///
2919/// \param PrevDecl the set of declarations that
2920bool
2921Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
2922 bool HasExplicitTemplateArgs,
2923 SourceLocation LAngleLoc,
2924 const TemplateArgument *ExplicitTemplateArgs,
2925 unsigned NumExplicitTemplateArgs,
2926 SourceLocation RAngleLoc,
2927 NamedDecl *&PrevDecl) {
2928 // The set of function template specializations that could match this
2929 // explicit function template specialization.
2930 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
2931 CandidateSet Candidates;
2932
2933 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
2934 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2935 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
2936 // Only consider templates found within the same semantic lookup scope as
2937 // FD.
2938 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
2939 continue;
2940
2941 // C++ [temp.expl.spec]p11:
2942 // A trailing template-argument can be left unspecified in the
2943 // template-id naming an explicit function template specialization
2944 // provided it can be deduced from the function argument type.
2945 // Perform template argument deduction to determine whether we may be
2946 // specializing this template.
2947 // FIXME: It is somewhat wasteful to build
2948 TemplateDeductionInfo Info(Context);
2949 FunctionDecl *Specialization = 0;
2950 if (TemplateDeductionResult TDK
2951 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
2952 ExplicitTemplateArgs,
2953 NumExplicitTemplateArgs,
2954 FD->getType(),
2955 Specialization,
2956 Info)) {
2957 // FIXME: Template argument deduction failed; record why it failed, so
2958 // that we can provide nifty diagnostics.
2959 (void)TDK;
2960 continue;
2961 }
2962
2963 // Record this candidate.
2964 Candidates.push_back(Specialization);
2965 }
2966 }
2967
Douglas Gregor5de279c2009-09-26 03:41:46 +00002968 // Find the most specialized function template.
2969 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
2970 Candidates.size(),
2971 TPOC_Other,
2972 FD->getLocation(),
2973 PartialDiagnostic(diag::err_function_template_spec_no_match)
2974 << FD->getDeclName(),
2975 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
2976 << FD->getDeclName() << HasExplicitTemplateArgs,
2977 PartialDiagnostic(diag::note_function_template_spec_matched));
2978 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002979 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002980
2981 // FIXME: Check if the prior specialization has a point of instantiation.
2982 // If so, we have run afoul of C++ [temp.expl.spec]p6.
2983
2984 // Mark the prior declaration as an explicit specialization, so that later
2985 // clients know that this is an explicit specialization.
2986 // FIXME: Check for prior explicit instantiations?
2987 Specialization->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
2988
2989 // Turn the given function declaration into a function template
2990 // specialization, with the template arguments from the previous
2991 // specialization.
2992 FD->setFunctionTemplateSpecialization(Context,
2993 Specialization->getPrimaryTemplate(),
2994 new (Context) TemplateArgumentList(
2995 *Specialization->getTemplateSpecializationArgs()),
2996 /*InsertPos=*/0,
2997 TSK_ExplicitSpecialization);
2998
2999 // The "previous declaration" for this function template specialization is
3000 // the prior function template specialization.
3001 PrevDecl = Specialization;
3002 return false;
3003}
3004
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003005// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003006// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003007Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003008Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003009 SourceLocation ExternLoc,
3010 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003011 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003012 SourceLocation KWLoc,
3013 const CXXScopeSpec &SS,
3014 TemplateTy TemplateD,
3015 SourceLocation TemplateNameLoc,
3016 SourceLocation LAngleLoc,
3017 ASTTemplateArgsPtr TemplateArgsIn,
3018 SourceLocation *TemplateArgLocs,
3019 SourceLocation RAngleLoc,
3020 AttributeList *Attr) {
3021 // Find the class template we're specializing
3022 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003023 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003024 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3025
3026 // Check that the specialization uses the same tag kind as the
3027 // original template.
3028 TagDecl::TagKind Kind;
3029 switch (TagSpec) {
3030 default: assert(0 && "Unknown tag type!");
3031 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3032 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3033 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3034 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003035 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003036 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003037 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003038 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003039 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003040 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003041 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003042 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003043 diag::note_previous_use);
3044 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3045 }
3046
Douglas Gregorf61eca92009-05-13 18:28:20 +00003047 // C++0x [temp.explicit]p2:
3048 // [...] An explicit instantiation shall appear in an enclosing
3049 // namespace of its template. [...]
3050 //
3051 // This is C++ DR 275.
3052 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
Mike Stump11289f42009-09-09 15:08:12 +00003053 TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003054 SS.getRange(),
Douglas Gregor30b01972009-06-12 22:21:45 +00003055 /*PartialSpecialization=*/false,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003056 /*ExplicitInstantiation=*/true))
3057 return true;
3058
Douglas Gregora1f49972009-05-13 00:25:59 +00003059 // Translate the parser's template argument list in our AST format.
3060 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3061 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3062
3063 // Check that the template argument list is well-formed for this
3064 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003065 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3066 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003067 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003068 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003069 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003070 return true;
3071
Mike Stump11289f42009-09-09 15:08:12 +00003072 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003073 ClassTemplate->getTemplateParameters()->size()) &&
3074 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003075
Douglas Gregora1f49972009-05-13 00:25:59 +00003076 // Find the class template specialization declaration that
3077 // corresponds to these arguments.
3078 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003079 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003080 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003081 Converted.flatSize(),
3082 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003083 void *InsertPos = 0;
3084 ClassTemplateSpecializationDecl *PrevDecl
3085 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3086
3087 ClassTemplateSpecializationDecl *Specialization = 0;
3088
Douglas Gregorf61eca92009-05-13 18:28:20 +00003089 bool SpecializationRequiresInstantiation = true;
Douglas Gregora1f49972009-05-13 00:25:59 +00003090 if (PrevDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003091 if (PrevDecl->getSpecializationKind()
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003092 == TSK_ExplicitInstantiationDefinition) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003093 // This particular specialization has already been declared or
3094 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorf61eca92009-05-13 18:28:20 +00003095 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
3096 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003097 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003098 diag::note_previous_explicit_instantiation);
Douglas Gregora1f49972009-05-13 00:25:59 +00003099 return DeclPtrTy::make(PrevDecl);
3100 }
3101
Douglas Gregorf61eca92009-05-13 18:28:20 +00003102 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003103 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorf61eca92009-05-13 18:28:20 +00003104 // For a given set of template parameters, if an explicit
3105 // instantiation of a template appears after a declaration of
3106 // an explicit specialization for that template, the explicit
3107 // instantiation has no effect.
3108 if (!getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00003109 Diag(TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003110 diag::ext_explicit_instantiation_after_specialization)
3111 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003112 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003113 diag::note_previous_template_specialization);
3114 }
3115
3116 // Create a new class template specialization declaration node
3117 // for this explicit specialization. This node is only used to
3118 // record the existence of this explicit instantiation for
3119 // accurate reproduction of the source code; we don't actually
3120 // use it for anything, since it is semantically irrelevant.
3121 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003122 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003123 ClassTemplate->getDeclContext(),
3124 TemplateNameLoc,
3125 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003126 Converted, 0);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003127 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003128 CurContext->addDecl(Specialization);
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003129 return DeclPtrTy::make(PrevDecl);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003130 }
3131
3132 // If we have already (implicitly) instantiated this
3133 // specialization, there is less work to do.
3134 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
3135 SpecializationRequiresInstantiation = false;
3136
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003137 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3138 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3139 // Since the only prior class template specialization with these
3140 // arguments was referenced but not declared, reuse that
3141 // declaration node as our own, updating its source location to
3142 // reflect our new declaration.
3143 Specialization = PrevDecl;
3144 Specialization->setLocation(TemplateNameLoc);
3145 PrevDecl = 0;
3146 }
3147 }
3148
3149 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003150 // Create a new class template specialization declaration node for
3151 // this explicit specialization.
3152 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003153 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003154 ClassTemplate->getDeclContext(),
3155 TemplateNameLoc,
3156 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003157 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003158
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003159 if (PrevDecl) {
3160 // Remove the previous declaration from the folding set, since we want
3161 // to introduce a new declaration.
3162 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3163 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3164 }
3165
3166 // Insert the new specialization.
3167 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003168 }
3169
3170 // Build the fully-sugared type for this explicit instantiation as
3171 // the user wrote in the explicit instantiation itself. This means
3172 // that we'll pretty-print the type retrieved from the
3173 // specialization's declaration the way that the user actually wrote
3174 // the explicit instantiation, rather than formatting the name based
3175 // on the "canonical" representation used to store the template
3176 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003177 QualType WrittenTy
3178 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003179 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003180 TemplateArgs.size(),
3181 Context.getTypeDeclType(Specialization));
3182 Specialization->setTypeAsWritten(WrittenTy);
3183 TemplateArgsIn.release();
3184
3185 // Add the explicit instantiation into its lexical context. However,
3186 // since explicit instantiations are never found by name lookup, we
3187 // just put it into the declaration context directly.
3188 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003189 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003190
John McCall1806c272009-09-11 07:25:08 +00003191 Specialization->setPointOfInstantiation(TemplateNameLoc);
3192
Douglas Gregora1f49972009-05-13 00:25:59 +00003193 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003194 // A definition of a class template or class member template
3195 // shall be in scope at the point of the explicit instantiation of
3196 // the class template or class member template.
3197 //
3198 // This check comes when we actually try to perform the
3199 // instantiation.
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003200 TemplateSpecializationKind TSK
Mike Stump11289f42009-09-09 15:08:12 +00003201 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003202 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor67da0d92009-05-15 17:59:04 +00003203 if (SpecializationRequiresInstantiation)
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003204 InstantiateClassTemplateSpecialization(Specialization, TSK);
Douglas Gregor85673582009-05-18 17:01:57 +00003205 else // Instantiate the members of this class template specialization.
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003206 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization,
3207 TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003208
3209 return DeclPtrTy::make(Specialization);
3210}
3211
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003212// Explicit instantiation of a member class of a class template.
3213Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003214Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003215 SourceLocation ExternLoc,
3216 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003217 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003218 SourceLocation KWLoc,
3219 const CXXScopeSpec &SS,
3220 IdentifierInfo *Name,
3221 SourceLocation NameLoc,
3222 AttributeList *Attr) {
3223
Douglas Gregord6ab8742009-05-28 23:31:59 +00003224 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003225 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00003226 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00003227 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00003228 MultiTemplateParamsArg(*this, 0, 0),
3229 Owned, IsDependent);
3230 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3231
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003232 if (!TagD)
3233 return true;
3234
3235 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3236 if (Tag->isEnum()) {
3237 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3238 << Context.getTypeDeclType(Tag);
3239 return true;
3240 }
3241
Douglas Gregorb8006faf2009-05-27 17:30:49 +00003242 if (Tag->isInvalidDecl())
3243 return true;
3244
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003245 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3246 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3247 if (!Pattern) {
3248 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3249 << Context.getTypeDeclType(Record);
3250 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3251 return true;
3252 }
3253
3254 // C++0x [temp.explicit]p2:
3255 // [...] An explicit instantiation shall appear in an enclosing
3256 // namespace of its template. [...]
3257 //
3258 // This is C++ DR 275.
3259 if (getLangOptions().CPlusPlus0x) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003260 // FIXME: In C++98, we would like to turn these errors into warnings,
3261 // dependent on a -Wc++0x flag.
Mike Stump11289f42009-09-09 15:08:12 +00003262 DeclContext *PatternContext
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003263 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
3264 if (!CurContext->Encloses(PatternContext)) {
3265 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
3266 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
3267 Diag(Pattern->getLocation(), diag::note_previous_declaration);
3268 }
3269 }
3270
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003271 TemplateSpecializationKind TSK
Mike Stump11289f42009-09-09 15:08:12 +00003272 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003273 : TSK_ExplicitInstantiationDeclaration;
Mike Stump11289f42009-09-09 15:08:12 +00003274
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003275 if (!Record->getDefinition(Context)) {
3276 // If the class has a definition, instantiate it (and all of its
3277 // members, recursively).
3278 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
Mike Stump11289f42009-09-09 15:08:12 +00003279 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregorb4850462009-05-14 23:26:13 +00003280 getTemplateInstantiationArgs(Record),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003281 TSK))
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003282 return true;
John McCall76d824f2009-08-25 22:02:44 +00003283 } else // Instantiate all of the members of the class.
Mike Stump11289f42009-09-09 15:08:12 +00003284 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003285 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003286
Mike Stump87c57ac2009-05-16 07:39:55 +00003287 // FIXME: We don't have any representation for explicit instantiations of
3288 // member classes. Such a representation is not needed for compilation, but it
3289 // should be available for clients that want to see all of the declarations in
3290 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003291 return TagD;
3292}
3293
Douglas Gregor450f00842009-09-25 18:43:00 +00003294Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
3295 SourceLocation ExternLoc,
3296 SourceLocation TemplateLoc,
3297 Declarator &D) {
3298 // Explicit instantiations always require a name.
3299 DeclarationName Name = GetNameForDeclarator(D);
3300 if (!Name) {
3301 if (!D.isInvalidType())
3302 Diag(D.getDeclSpec().getSourceRange().getBegin(),
3303 diag::err_explicit_instantiation_requires_name)
3304 << D.getDeclSpec().getSourceRange()
3305 << D.getSourceRange();
3306
3307 return true;
3308 }
3309
3310 // The scope passed in may not be a decl scope. Zip up the scope tree until
3311 // we find one that is.
3312 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3313 (S->getFlags() & Scope::TemplateParamScope) != 0)
3314 S = S->getParent();
3315
3316 // Determine the type of the declaration.
3317 QualType R = GetTypeForDeclarator(D, S, 0);
3318 if (R.isNull())
3319 return true;
3320
3321 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3322 // Cannot explicitly instantiate a typedef.
3323 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
3324 << Name;
3325 return true;
3326 }
3327
3328 // Determine what kind of explicit instantiation we have.
3329 TemplateSpecializationKind TSK
3330 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3331 : TSK_ExplicitInstantiationDeclaration;
3332
3333 LookupResult Previous = LookupParsedName(S, &D.getCXXScopeSpec(),
3334 Name, LookupOrdinaryName);
3335
3336 if (!R->isFunctionType()) {
3337 // C++ [temp.explicit]p1:
3338 // A [...] static data member of a class template can be explicitly
3339 // instantiated from the member definition associated with its class
3340 // template.
3341 if (Previous.isAmbiguous()) {
3342 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
3343 D.getSourceRange());
3344 }
3345
3346 VarDecl *Prev = dyn_cast_or_null<VarDecl>(Previous.getAsDecl());
3347 if (!Prev || !Prev->isStaticDataMember()) {
3348 // We expect to see a data data member here.
3349 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
3350 << Name;
3351 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3352 P != PEnd; ++P)
3353 Diag(P->getLocation(), diag::note_explicit_instantiation_here);
3354 return true;
3355 }
3356
3357 if (!Prev->getInstantiatedFromStaticDataMember()) {
3358 // FIXME: Check for explicit specialization?
3359 Diag(D.getIdentifierLoc(),
3360 diag::err_explicit_instantiation_data_member_not_instantiated)
3361 << Prev;
3362 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
3363 // FIXME: Can we provide a note showing where this was declared?
3364 return true;
3365 }
3366
3367 // Instantiate static data member.
3368 // FIXME: Note that this is an explicit instantiation.
3369 if (TSK == TSK_ExplicitInstantiationDefinition)
3370 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false);
3371
3372 // FIXME: Create an ExplicitInstantiation node?
3373 return DeclPtrTy();
3374 }
3375
Douglas Gregor0e876e02009-09-25 23:53:26 +00003376 // If the declarator is a template-id, translate the parser's template
3377 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00003378 bool HasExplicitTemplateArgs = false;
3379 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3380 if (D.getKind() == Declarator::DK_TemplateId) {
3381 TemplateIdAnnotation *TemplateId = D.getTemplateId();
3382 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3383 TemplateId->getTemplateArgs(),
3384 TemplateId->getTemplateArgIsType(),
3385 TemplateId->NumArgs);
3386 translateTemplateArguments(TemplateArgsPtr,
3387 TemplateId->getTemplateArgLocations(),
3388 TemplateArgs);
3389 HasExplicitTemplateArgs = true;
3390 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00003391
Douglas Gregor450f00842009-09-25 18:43:00 +00003392 // C++ [temp.explicit]p1:
3393 // A [...] function [...] can be explicitly instantiated from its template.
3394 // A member function [...] of a class template can be explicitly
3395 // instantiated from the member definition associated with its class
3396 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00003397 llvm::SmallVector<FunctionDecl *, 8> Matches;
3398 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3399 P != PEnd; ++P) {
3400 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00003401 if (!HasExplicitTemplateArgs) {
3402 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
3403 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
3404 Matches.clear();
3405 Matches.push_back(Method);
3406 break;
3407 }
Douglas Gregor450f00842009-09-25 18:43:00 +00003408 }
3409 }
3410
3411 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
3412 if (!FunTmpl)
3413 continue;
3414
3415 TemplateDeductionInfo Info(Context);
3416 FunctionDecl *Specialization = 0;
3417 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00003418 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3419 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00003420 R, Specialization, Info)) {
3421 // FIXME: Keep track of almost-matches?
3422 (void)TDK;
3423 continue;
3424 }
3425
3426 Matches.push_back(Specialization);
3427 }
3428
3429 // Find the most specialized function template specialization.
3430 FunctionDecl *Specialization
3431 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
3432 D.getIdentifierLoc(),
3433 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
3434 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
3435 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
3436
3437 if (!Specialization)
3438 return true;
3439
3440 switch (Specialization->getTemplateSpecializationKind()) {
3441 case TSK_Undeclared:
3442 Diag(D.getIdentifierLoc(),
3443 diag::err_explicit_instantiation_member_function_not_instantiated)
3444 << Specialization
3445 << (Specialization->getTemplateSpecializationKind() ==
3446 TSK_ExplicitSpecialization);
3447 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
3448 return true;
3449
3450 case TSK_ExplicitSpecialization:
3451 // C++ [temp.explicit]p4:
3452 // For a given set of template parameters, if an explicit instantiation
3453 // of a template appears after a declaration of an explicit
3454 // specialization for that template, the explicit instantiation has no
3455 // effect.
3456 break;
3457
3458 case TSK_ExplicitInstantiationDefinition:
3459 // FIXME: Check that we aren't trying to perform an explicit instantiation
3460 // declaration now.
3461 // Fall through
3462
3463 case TSK_ImplicitInstantiation:
3464 case TSK_ExplicitInstantiationDeclaration:
3465 // Instantiate the function, if this is an explicit instantiation
3466 // definition.
3467 if (TSK == TSK_ExplicitInstantiationDefinition)
3468 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
3469 false);
3470
3471 // FIXME: setTemplateSpecializationKind doesn't (yet) work for
3472 // non-templated member functions.
3473 if (!Specialization->getPrimaryTemplate())
3474 break;
3475
3476 Specialization->setTemplateSpecializationKind(TSK);
3477 break;
3478 }
3479
3480 // FIXME: Create some kind of ExplicitInstantiationDecl here.
3481 return DeclPtrTy();
3482}
3483
Douglas Gregor333489b2009-03-27 23:10:48 +00003484Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00003485Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3486 const CXXScopeSpec &SS, IdentifierInfo *Name,
3487 SourceLocation TagLoc, SourceLocation NameLoc) {
3488 // This has to hold, because SS is expected to be defined.
3489 assert(Name && "Expected a name in a dependent tag");
3490
3491 NestedNameSpecifier *NNS
3492 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3493 if (!NNS)
3494 return true;
3495
3496 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
3497 if (T.isNull())
3498 return true;
3499
3500 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
3501 QualType ElabType = Context.getElaboratedType(T, TagKind);
3502
3503 return ElabType.getAsOpaquePtr();
3504}
3505
3506Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00003507Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3508 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00003509 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00003510 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3511 if (!NNS)
3512 return true;
3513
3514 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003515 if (T.isNull())
3516 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00003517 return T.getAsOpaquePtr();
3518}
3519
Douglas Gregordce2b622009-04-01 00:28:59 +00003520Sema::TypeResult
3521Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3522 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003523 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003524 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00003525 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00003526 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00003527 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00003528 assert(TemplateId && "Expected a template specialization type");
3529
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003530 if (computeDeclContext(SS, false)) {
3531 // If we can compute a declaration context, then the "typename"
3532 // keyword was superfluous. Just build a QualifiedNameType to keep
3533 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00003534
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003535 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
3536 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
3537 }
Mike Stump11289f42009-09-09 15:08:12 +00003538
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003539 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00003540}
3541
Douglas Gregor333489b2009-03-27 23:10:48 +00003542/// \brief Build the type that describes a C++ typename specifier,
3543/// e.g., "typename T::type".
3544QualType
3545Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
3546 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003547 CXXRecordDecl *CurrentInstantiation = 0;
3548 if (NNS->isDependent()) {
3549 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00003550
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003551 // If the nested-name-specifier does not refer to the current
3552 // instantiation, then build a typename type.
3553 if (!CurrentInstantiation)
3554 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00003555
Douglas Gregorc707da62009-09-02 13:12:51 +00003556 // The nested-name-specifier refers to the current instantiation, so the
3557 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00003558 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00003559 // extraneous "typename" keywords, and we retroactively apply this DR to
3560 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003561 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003562
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003563 DeclContext *Ctx = 0;
3564
3565 if (CurrentInstantiation)
3566 Ctx = CurrentInstantiation;
3567 else {
3568 CXXScopeSpec SS;
3569 SS.setScopeRep(NNS);
3570 SS.setRange(Range);
3571 if (RequireCompleteDeclContext(SS))
3572 return QualType();
3573
3574 Ctx = computeDeclContext(SS);
3575 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003576 assert(Ctx && "No declaration context?");
3577
3578 DeclarationName Name(&II);
Mike Stump11289f42009-09-09 15:08:12 +00003579 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
Douglas Gregor333489b2009-03-27 23:10:48 +00003580 false);
3581 unsigned DiagID = 0;
3582 Decl *Referenced = 0;
3583 switch (Result.getKind()) {
3584 case LookupResult::NotFound:
3585 if (Ctx->isTranslationUnit())
3586 DiagID = diag::err_typename_nested_not_found_global;
3587 else
3588 DiagID = diag::err_typename_nested_not_found;
3589 break;
3590
3591 case LookupResult::Found:
3592 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3593 // We found a type. Build a QualifiedNameType, since the
3594 // typename-specifier was just sugar. FIXME: Tell
3595 // QualifiedNameType that it has a "typename" prefix.
3596 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3597 }
3598
3599 DiagID = diag::err_typename_nested_not_type;
3600 Referenced = Result.getAsDecl();
3601 break;
3602
3603 case LookupResult::FoundOverloaded:
3604 DiagID = diag::err_typename_nested_not_type;
3605 Referenced = *Result.begin();
3606 break;
3607
3608 case LookupResult::AmbiguousBaseSubobjectTypes:
3609 case LookupResult::AmbiguousBaseSubobjects:
3610 case LookupResult::AmbiguousReference:
3611 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3612 return QualType();
3613 }
3614
3615 // If we get here, it's because name lookup did not find a
3616 // type. Emit an appropriate diagnostic and return an error.
3617 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3618 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3619 else
3620 Diag(Range.getEnd(), DiagID) << Range << Name;
3621 if (Referenced)
3622 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3623 << Name;
3624 return QualType();
3625}
Douglas Gregor15acfb92009-08-06 16:20:37 +00003626
3627namespace {
3628 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00003629 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3630 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00003631 SourceLocation Loc;
3632 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00003633
Douglas Gregor15acfb92009-08-06 16:20:37 +00003634 public:
Mike Stump11289f42009-09-09 15:08:12 +00003635 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00003636 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003637 DeclarationName Entity)
3638 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00003639 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00003640
3641 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00003642 /// transformed.
3643 ///
3644 /// For the purposes of type reconstruction, a type has already been
3645 /// transformed if it is NULL or if it is not dependent.
3646 bool AlreadyTransformed(QualType T) {
3647 return T.isNull() || !T->isDependentType();
3648 }
Mike Stump11289f42009-09-09 15:08:12 +00003649
3650 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00003651 /// rebuilt.
3652 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00003653
Douglas Gregor15acfb92009-08-06 16:20:37 +00003654 /// \brief Returns the name of the entity whose type is being rebuilt.
3655 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00003656
Douglas Gregor15acfb92009-08-06 16:20:37 +00003657 /// \brief Transforms an expression by returning the expression itself
3658 /// (an identity function).
3659 ///
3660 /// FIXME: This is completely unsafe; we will need to actually clone the
3661 /// expressions.
3662 Sema::OwningExprResult TransformExpr(Expr *E) {
3663 return getSema().Owned(E);
3664 }
Mike Stump11289f42009-09-09 15:08:12 +00003665
Douglas Gregor15acfb92009-08-06 16:20:37 +00003666 /// \brief Transforms a typename type by determining whether the type now
3667 /// refers to a member of the current instantiation, and then
3668 /// type-checking and building a QualifiedNameType (when possible).
3669 QualType TransformTypenameType(const TypenameType *T);
3670 };
3671}
3672
Mike Stump11289f42009-09-09 15:08:12 +00003673QualType
Douglas Gregor15acfb92009-08-06 16:20:37 +00003674CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3675 NestedNameSpecifier *NNS
3676 = TransformNestedNameSpecifier(T->getQualifier(),
3677 /*FIXME:*/SourceRange(getBaseLocation()));
3678 if (!NNS)
3679 return QualType();
3680
3681 // If the nested-name-specifier did not change, and we cannot compute the
3682 // context corresponding to the nested-name-specifier, then this
3683 // typename type will not change; exit early.
3684 CXXScopeSpec SS;
3685 SS.setRange(SourceRange(getBaseLocation()));
3686 SS.setScopeRep(NNS);
3687 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3688 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003689
3690 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00003691 // QualifiedNameType.
3692 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00003693 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00003694 = TransformType(QualType(TemplateId, 0));
3695 if (NewTemplateId.isNull())
3696 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003697
Douglas Gregor15acfb92009-08-06 16:20:37 +00003698 if (NNS == T->getQualifier() &&
3699 NewTemplateId == QualType(TemplateId, 0))
3700 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003701
Douglas Gregor15acfb92009-08-06 16:20:37 +00003702 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3703 }
Mike Stump11289f42009-09-09 15:08:12 +00003704
Douglas Gregor15acfb92009-08-06 16:20:37 +00003705 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3706}
3707
3708/// \brief Rebuilds a type within the context of the current instantiation.
3709///
Mike Stump11289f42009-09-09 15:08:12 +00003710/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00003711/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00003712/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00003713/// partial specialization thereof). This routine will rebuild that type now
3714/// that we have entered the declarator's scope, which may produce different
3715/// canonical types, e.g.,
3716///
3717/// \code
3718/// template<typename T>
3719/// struct X {
3720/// typedef T* pointer;
3721/// pointer data();
3722/// };
3723///
3724/// template<typename T>
3725/// typename X<T>::pointer X<T>::data() { ... }
3726/// \endcode
3727///
3728/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3729/// since we do not know that we can look into X<T> when we parsed the type.
3730/// This function will rebuild the type, performing the lookup of "pointer"
3731/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3732/// as the canonical type of T*, allowing the return types of the out-of-line
3733/// definition and the declaration to match.
3734QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3735 DeclarationName Name) {
3736 if (T.isNull() || !T->isDependentType())
3737 return T;
Mike Stump11289f42009-09-09 15:08:12 +00003738
Douglas Gregor15acfb92009-08-06 16:20:37 +00003739 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3740 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00003741}
Douglas Gregorbe999392009-09-15 16:23:51 +00003742
3743/// \brief Produces a formatted string that describes the binding of
3744/// template parameters to template arguments.
3745std::string
3746Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3747 const TemplateArgumentList &Args) {
3748 std::string Result;
3749
3750 if (!Params || Params->size() == 0)
3751 return Result;
3752
3753 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3754 if (I == 0)
3755 Result += "[with ";
3756 else
3757 Result += ", ";
3758
3759 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
3760 Result += Id->getName();
3761 } else {
3762 Result += '$';
3763 Result += llvm::utostr(I);
3764 }
3765
3766 Result += " = ";
3767
3768 switch (Args[I].getKind()) {
3769 case TemplateArgument::Null:
3770 Result += "<no value>";
3771 break;
3772
3773 case TemplateArgument::Type: {
3774 std::string TypeStr;
3775 Args[I].getAsType().getAsStringInternal(TypeStr,
3776 Context.PrintingPolicy);
3777 Result += TypeStr;
3778 break;
3779 }
3780
3781 case TemplateArgument::Declaration: {
3782 bool Unnamed = true;
3783 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
3784 if (ND->getDeclName()) {
3785 Unnamed = false;
3786 Result += ND->getNameAsString();
3787 }
3788 }
3789
3790 if (Unnamed) {
3791 Result += "<anonymous>";
3792 }
3793 break;
3794 }
3795
3796 case TemplateArgument::Integral: {
3797 Result += Args[I].getAsIntegral()->toString(10);
3798 break;
3799 }
3800
3801 case TemplateArgument::Expression: {
3802 assert(false && "No expressions in deduced template arguments!");
3803 Result += "<expression>";
3804 break;
3805 }
3806
3807 case TemplateArgument::Pack:
3808 // FIXME: Format template argument packs
3809 Result += "<template argument pack>";
3810 break;
3811 }
3812 }
3813
3814 Result += ']';
3815 return Result;
3816}