blob: d5fb7e82a8d35a3bc7f1836c03085735133eb145 [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000020#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000021#include "llvm/Support/Compiler.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000022#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000023using namespace clang;
24
Douglas Gregorb7bfe792009-09-02 22:59:36 +000025/// \brief Determine whether the declaration found is acceptable as the name
26/// of a template and, if so, return that template declaration. Otherwise,
27/// returns NULL.
28static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
29 if (!D)
30 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000031
Douglas Gregorb7bfe792009-09-02 22:59:36 +000032 if (isa<TemplateDecl>(D))
33 return D;
Mike Stump11289f42009-09-09 15:08:12 +000034
Douglas Gregorb7bfe792009-09-02 22:59:36 +000035 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
36 // C++ [temp.local]p1:
37 // Like normal (non-template) classes, class templates have an
38 // injected-class-name (Clause 9). The injected-class-name
39 // can be used with or without a template-argument-list. When
40 // it is used without a template-argument-list, it is
41 // equivalent to the injected-class-name followed by the
42 // template-parameters of the class template enclosed in
43 // <>. When it is used with a template-argument-list, it
44 // refers to the specified class template specialization,
45 // which could be the current specialization or another
46 // specialization.
47 if (Record->isInjectedClassName()) {
48 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
49 if (Record->getDescribedClassTemplate())
50 return Record->getDescribedClassTemplate();
51
52 if (ClassTemplateSpecializationDecl *Spec
53 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
54 return Spec->getSpecializedTemplate();
55 }
Mike Stump11289f42009-09-09 15:08:12 +000056
Douglas Gregorb7bfe792009-09-02 22:59:36 +000057 return 0;
58 }
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregorb7bfe792009-09-02 22:59:36 +000060 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
61 if (!Ovl)
62 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000063
Douglas Gregorb7bfe792009-09-02 22:59:36 +000064 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
65 FEnd = Ovl->function_end();
66 F != FEnd; ++F) {
67 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
68 // We've found a function template. Determine whether there are
69 // any other function templates we need to bundle together in an
70 // OverloadedFunctionDecl
71 for (++F; F != FEnd; ++F) {
72 if (isa<FunctionTemplateDecl>(*F))
73 break;
74 }
Mike Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregorb7bfe792009-09-02 22:59:36 +000076 if (F != FEnd) {
77 // Build an overloaded function decl containing only the
78 // function templates in Ovl.
Mike Stump11289f42009-09-09 15:08:12 +000079 OverloadedFunctionDecl *OvlTemplate
Douglas Gregorb7bfe792009-09-02 22:59:36 +000080 = OverloadedFunctionDecl::Create(Context,
81 Ovl->getDeclContext(),
82 Ovl->getDeclName());
83 OvlTemplate->addOverload(FuncTmpl);
84 OvlTemplate->addOverload(*F);
85 for (++F; F != FEnd; ++F) {
86 if (isa<FunctionTemplateDecl>(*F))
87 OvlTemplate->addOverload(*F);
88 }
Mike Stump11289f42009-09-09 15:08:12 +000089
Douglas Gregorb7bfe792009-09-02 22:59:36 +000090 return OvlTemplate;
91 }
92
93 return FuncTmpl;
94 }
95 }
Mike Stump11289f42009-09-09 15:08:12 +000096
Douglas Gregorb7bfe792009-09-02 22:59:36 +000097 return 0;
98}
99
100TemplateNameKind Sema::isTemplateName(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +0000101 const IdentifierInfo &II,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000102 SourceLocation IdLoc,
Douglas Gregore861bac2009-08-25 22:51:20 +0000103 const CXXScopeSpec *SS,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000104 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000105 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000106 TemplateTy &TemplateResult) {
107 // Determine where to perform name lookup
108 DeclContext *LookupCtx = 0;
109 bool isDependent = false;
110 if (ObjectTypePtr) {
111 // This nested-name-specifier occurs in a member access expression, e.g.,
112 // x->B::f, and we are looking into the type of the object.
Mike Stump11289f42009-09-09 15:08:12 +0000113 assert((!SS || !SS->isSet()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000114 "ObjectType and scope specifier cannot coexist");
115 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
116 LookupCtx = computeDeclContext(ObjectType);
117 isDependent = ObjectType->isDependentType();
118 } else if (SS && SS->isSet()) {
119 // This nested-name-specifier occurs after another nested-name-specifier,
120 // so long into the context associated with the prior nested-name-specifier.
121
122 LookupCtx = computeDeclContext(*SS, EnteringContext);
123 isDependent = isDependentScopeSpecifier(*SS);
124 }
Mike Stump11289f42009-09-09 15:08:12 +0000125
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000126 LookupResult Found;
127 bool ObjectTypeSearchedInScope = false;
128 if (LookupCtx) {
129 // Perform "qualified" name lookup into the declaration context we
130 // computed, which is either the type of the base of a member access
Mike Stump11289f42009-09-09 15:08:12 +0000131 // expression or the declaration context associated with a prior
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000132 // nested-name-specifier.
133
134 // The declaration context must be complete.
135 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
136 return TNK_Non_template;
Mike Stump11289f42009-09-09 15:08:12 +0000137
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000138 Found = LookupQualifiedName(LookupCtx, &II, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +0000139
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000140 if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
141 // C++ [basic.lookup.classref]p1:
142 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump11289f42009-09-09 15:08:12 +0000143 // immediately followed by an identifier followed by a <, the
144 // identifier must be looked up to determine whether the < is the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000145 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump11289f42009-09-09 15:08:12 +0000146 // The identifier is first looked up in the class of the object
147 // expression. If the identifier is not found, it is then looked up in
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000148 // the context of the entire postfix-expression and shall name a class
149 // or function template.
150 //
151 // FIXME: When we're instantiating a template, do we actually have to
152 // look in the scope of the template? Seems fishy...
153 Found = LookupName(S, &II, LookupOrdinaryName);
154 ObjectTypeSearchedInScope = true;
155 }
156 } else if (isDependent) {
Mike Stump11289f42009-09-09 15:08:12 +0000157 // We cannot look into a dependent object type or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158 return TNK_Non_template;
159 } else {
160 // Perform unqualified name lookup in the current scope.
161 Found = LookupName(S, &II, LookupOrdinaryName);
162 }
Mike Stump11289f42009-09-09 15:08:12 +0000163
Douglas Gregore861bac2009-08-25 22:51:20 +0000164 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump11289f42009-09-09 15:08:12 +0000165 assert(!Found.isAmbiguous() &&
Douglas Gregore861bac2009-08-25 22:51:20 +0000166 "Cannot handle template name-lookup ambiguities");
Douglas Gregordc572a32009-03-30 22:58:21 +0000167
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000168 NamedDecl *Template = isAcceptableTemplateName(Context, Found);
169 if (!Template)
170 return TNK_Non_template;
171
172 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
173 // C++ [basic.lookup.classref]p1:
Mike Stump11289f42009-09-09 15:08:12 +0000174 // [...] If the lookup in the class of the object expression finds a
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000175 // template, the name is also looked up in the context of the entire
176 // postfix-expression and [...]
177 //
178 LookupResult FoundOuter = LookupName(S, &II, LookupOrdinaryName);
179 // FIXME: Handle ambiguities in this lookup better
180 NamedDecl *OuterTemplate = isAcceptableTemplateName(Context, FoundOuter);
Mike Stump11289f42009-09-09 15:08:12 +0000181
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000182 if (!OuterTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +0000183 // - if the name is not found, the name found in the class of the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000184 // object expression is used, otherwise
185 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump11289f42009-09-09 15:08:12 +0000186 // - if the name is found in the context of the entire
187 // postfix-expression and does not name a class template, the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000188 // found in the class of the object expression is used, otherwise
189 } else {
190 // - if the name found is a class template, it must refer to the same
Mike Stump11289f42009-09-09 15:08:12 +0000191 // entity as the one found in the class of the object expression,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000192 // otherwise the program is ill-formed.
193 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
194 Diag(IdLoc, diag::err_nested_name_member_ref_lookup_ambiguous)
195 << &II;
196 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
197 << QualType::getFromOpaquePtr(ObjectTypePtr);
198 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump11289f42009-09-09 15:08:12 +0000199
200 // Recover by taking the template that we found in the object
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000201 // expression's type.
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000202 }
Mike Stump11289f42009-09-09 15:08:12 +0000203 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000204 }
Mike Stump11289f42009-09-09 15:08:12 +0000205
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000206 if (SS && SS->isSet() && !SS->isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000207 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000208 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000209 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000210 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000211 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000212 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
213 Ovl));
214 else
Mike Stump11289f42009-09-09 15:08:12 +0000215 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000216 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000217 cast<TemplateDecl>(Template)));
218 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000219 = dyn_cast<OverloadedFunctionDecl>(Template)) {
220 TemplateResult = TemplateTy::make(TemplateName(Ovl));
221 } else {
222 TemplateResult = TemplateTy::make(
223 TemplateName(cast<TemplateDecl>(Template)));
224 }
Mike Stump11289f42009-09-09 15:08:12 +0000225
226 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000227 isa<TemplateTemplateParmDecl>(Template))
228 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000229
230 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000231 isa<OverloadedFunctionDecl>(Template)) &&
232 "Unhandled template kind in Sema::isTemplateName");
233 return TNK_Function_template;
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000234}
235
Douglas Gregor5101c242008-12-05 18:15:24 +0000236/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
237/// that the template parameter 'PrevDecl' is being shadowed by a new
238/// declaration at location Loc. Returns true to indicate that this is
239/// an error, and false otherwise.
240bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000241 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000242
243 // Microsoft Visual C++ permits template parameters to be shadowed.
244 if (getLangOptions().Microsoft)
245 return false;
246
247 // C++ [temp.local]p4:
248 // A template-parameter shall not be redeclared within its
249 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000250 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000251 << cast<NamedDecl>(PrevDecl)->getDeclName();
252 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
253 return true;
254}
255
Douglas Gregor463421d2009-03-03 04:44:36 +0000256/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000257/// the parameter D to reference the templated declaration and return a pointer
258/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000259TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
260 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
261 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000262 return Temp;
263 }
264 return 0;
265}
266
Douglas Gregor5101c242008-12-05 18:15:24 +0000267/// ActOnTypeParameter - Called when a C++ template type parameter
268/// (e.g., "typename T") has been parsed. Typename specifies whether
269/// the keyword "typename" was used to declare the type parameter
270/// (otherwise, "class" was used), and KeyLoc is the location of the
271/// "class" or "typename" keyword. ParamName is the name of the
272/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000273/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000274/// If the type parameter has a default argument, it will be added
275/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000276Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000277 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000278 SourceLocation KeyLoc,
279 IdentifierInfo *ParamName,
280 SourceLocation ParamNameLoc,
281 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000282 assert(S->isTemplateParamScope() &&
283 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000284 bool Invalid = false;
285
286 if (ParamName) {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000287 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000288 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000289 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000290 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000291 }
292
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000293 SourceLocation Loc = ParamNameLoc;
294 if (!ParamName)
295 Loc = KeyLoc;
296
Douglas Gregor5101c242008-12-05 18:15:24 +0000297 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000298 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
299 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000300 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000301 if (Invalid)
302 Param->setInvalidDecl();
303
304 if (ParamName) {
305 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000306 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000307 IdResolver.AddDecl(Param);
308 }
309
Chris Lattner83f095c2009-03-28 19:18:32 +0000310 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000311}
312
Douglas Gregordba32632009-02-10 19:49:53 +0000313/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000314/// Default) to the given template type parameter (TypeParam).
315void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000316 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000317 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000318 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000319 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000320 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000321 // FIXME: Preserve type source info.
322 QualType Default = GetTypeFromParser(DefaultT);
Douglas Gregordba32632009-02-10 19:49:53 +0000323
Anders Carlssond3824352009-06-12 22:30:13 +0000324 // C++0x [temp.param]p9:
325 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000326 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000327 if (Parm->isParameterPack()) {
328 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000329 return;
330 }
Mike Stump11289f42009-09-09 15:08:12 +0000331
Douglas Gregordba32632009-02-10 19:49:53 +0000332 // C++ [temp.param]p14:
333 // A template-parameter shall not be used in its own default argument.
334 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000335
Douglas Gregordba32632009-02-10 19:49:53 +0000336 // Check the template argument itself.
337 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
338 Parm->setInvalidDecl();
339 return;
340 }
341
342 Parm->setDefaultArgument(Default, DefaultLoc, false);
343}
344
Douglas Gregor463421d2009-03-03 04:44:36 +0000345/// \brief Check that the type of a non-type template parameter is
346/// well-formed.
347///
348/// \returns the (possibly-promoted) parameter type if valid;
349/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000350QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000351Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
352 // C++ [temp.param]p4:
353 //
354 // A non-type template-parameter shall have one of the following
355 // (optionally cv-qualified) types:
356 //
357 // -- integral or enumeration type,
358 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000359 // -- pointer to object or pointer to function,
360 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000361 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
362 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000363 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000364 T->isReferenceType() ||
365 // -- pointer to member.
366 T->isMemberPointerType() ||
367 // If T is a dependent type, we can't do the check now, so we
368 // assume that it is well-formed.
369 T->isDependentType())
370 return T;
371 // C++ [temp.param]p8:
372 //
373 // A non-type template-parameter of type "array of T" or
374 // "function returning T" is adjusted to be of type "pointer to
375 // T" or "pointer to function returning T", respectively.
376 else if (T->isArrayType())
377 // FIXME: Keep the type prior to promotion?
378 return Context.getArrayDecayedType(T);
379 else if (T->isFunctionType())
380 // FIXME: Keep the type prior to promotion?
381 return Context.getPointerType(T);
382
383 Diag(Loc, diag::err_template_nontype_parm_bad_type)
384 << T;
385
386 return QualType();
387}
388
Douglas Gregor5101c242008-12-05 18:15:24 +0000389/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
390/// template parameter (e.g., "int Size" in "template<int Size>
391/// class Array") has been parsed. S is the current scope and D is
392/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000393Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000394 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000395 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000396 DeclaratorInfo *DInfo = 0;
397 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000398
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000399 assert(S->isTemplateParamScope() &&
400 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000401 bool Invalid = false;
402
403 IdentifierInfo *ParamName = D.getIdentifier();
404 if (ParamName) {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000405 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000406 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000407 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000408 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000409 }
410
Douglas Gregor463421d2009-03-03 04:44:36 +0000411 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000412 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000413 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000414 Invalid = true;
415 }
Douglas Gregor81338792009-02-10 17:43:50 +0000416
Douglas Gregor5101c242008-12-05 18:15:24 +0000417 NonTypeTemplateParmDecl *Param
418 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000419 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000420 if (Invalid)
421 Param->setInvalidDecl();
422
423 if (D.getIdentifier()) {
424 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000425 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000426 IdResolver.AddDecl(Param);
427 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000428 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000429}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000430
Douglas Gregordba32632009-02-10 19:49:53 +0000431/// \brief Adds a default argument to the given non-type template
432/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000433void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000434 SourceLocation EqualLoc,
435 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000436 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000437 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000438 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000439
Douglas Gregordba32632009-02-10 19:49:53 +0000440 // C++ [temp.param]p14:
441 // A template-parameter shall not be used in its own default argument.
442 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000443
Douglas Gregordba32632009-02-10 19:49:53 +0000444 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000445 TemplateArgument Converted;
446 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
447 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000448 TemplateParm->setInvalidDecl();
449 return;
450 }
451
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000452 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000453}
454
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000455
456/// ActOnTemplateTemplateParameter - Called when a C++ template template
457/// parameter (e.g. T in template <template <typename> class T> class array)
458/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000459Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
460 SourceLocation TmpLoc,
461 TemplateParamsTy *Params,
462 IdentifierInfo *Name,
463 SourceLocation NameLoc,
464 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000465 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000466 assert(S->isTemplateParamScope() &&
467 "Template template parameter not in template parameter scope!");
468
469 // Construct the parameter object.
470 TemplateTemplateParmDecl *Param =
471 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
472 Position, Name,
473 (TemplateParameterList*)Params);
474
475 // Make sure the parameter is valid.
476 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
477 // do anything yet. However, if the template parameter list or (eventual)
478 // default value is ever invalidated, that will propagate here.
479 bool Invalid = false;
480 if (Invalid) {
481 Param->setInvalidDecl();
482 }
483
484 // If the tt-param has a name, then link the identifier into the scope
485 // and lookup mechanisms.
486 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000487 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000488 IdResolver.AddDecl(Param);
489 }
490
Chris Lattner83f095c2009-03-28 19:18:32 +0000491 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000492}
493
Douglas Gregordba32632009-02-10 19:49:53 +0000494/// \brief Adds a default argument to the given template template
495/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000496void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000497 SourceLocation EqualLoc,
498 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000499 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000500 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000501
502 // Since a template-template parameter's default argument is an
503 // id-expression, it must be a DeclRefExpr.
Mike Stump11289f42009-09-09 15:08:12 +0000504 DeclRefExpr *Default
Douglas Gregordba32632009-02-10 19:49:53 +0000505 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
506
507 // C++ [temp.param]p14:
508 // A template-parameter shall not be used in its own default argument.
509 // FIXME: Implement this check! Needs a recursive walk over the types.
510
511 // Check the well-formedness of the template argument.
512 if (!isa<TemplateDecl>(Default->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +0000513 Diag(Default->getSourceRange().getBegin(),
Douglas Gregordba32632009-02-10 19:49:53 +0000514 diag::err_template_arg_must_be_template)
515 << Default->getSourceRange();
516 TemplateParm->setInvalidDecl();
517 return;
Mike Stump11289f42009-09-09 15:08:12 +0000518 }
Douglas Gregordba32632009-02-10 19:49:53 +0000519 if (CheckTemplateArgument(TemplateParm, Default)) {
520 TemplateParm->setInvalidDecl();
521 return;
522 }
523
524 DefaultE.release();
525 TemplateParm->setDefaultArgument(Default);
526}
527
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000528/// ActOnTemplateParameterList - Builds a TemplateParameterList that
529/// contains the template parameters in Params/NumParams.
530Sema::TemplateParamsTy *
531Sema::ActOnTemplateParameterList(unsigned Depth,
532 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000533 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000534 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000535 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000536 SourceLocation RAngleLoc) {
537 if (ExportLoc.isValid())
538 Diag(ExportLoc, diag::note_template_export_unsupported);
539
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000540 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000541 (NamedDecl**)Params, NumParams,
542 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000543}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000544
Douglas Gregorc08f4892009-03-25 00:13:59 +0000545Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000546Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000547 SourceLocation KWLoc, const CXXScopeSpec &SS,
548 IdentifierInfo *Name, SourceLocation NameLoc,
549 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000550 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000551 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000552 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000553 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000554 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000555 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000556
557 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000558 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000559 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000560
John McCall27b5c252009-09-14 21:59:20 +0000561 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
562 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000563
564 // There is no such thing as an unnamed class template.
565 if (!Name) {
566 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000567 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000568 }
569
570 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000571 DeclContext *SemanticContext;
572 LookupResult Previous;
573 if (SS.isNotEmpty() && !SS.isInvalid()) {
574 SemanticContext = computeDeclContext(SS, true);
575 if (!SemanticContext) {
576 // FIXME: Produce a reasonable diagnostic here
577 return true;
578 }
Mike Stump11289f42009-09-09 15:08:12 +0000579
580 Previous = LookupQualifiedName(SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000581 true);
582 } else {
583 SemanticContext = CurContext;
584 Previous = LookupName(S, Name, LookupOrdinaryName, true);
585 }
Mike Stump11289f42009-09-09 15:08:12 +0000586
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000587 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
588 NamedDecl *PrevDecl = 0;
589 if (Previous.begin() != Previous.end())
590 PrevDecl = *Previous.begin();
591
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000592 if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000593 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000594
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000595 // If there is a previous declaration with the same name, check
596 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000597 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000598 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
599 if (PrevClassTemplate) {
600 // Ensure that the template parameter lists are compatible.
601 if (!TemplateParameterListsAreEqual(TemplateParams,
602 PrevClassTemplate->getTemplateParameters(),
603 /*Complain=*/true))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000604 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000605
606 // C++ [temp.class]p4:
607 // In a redeclaration, partial specialization, explicit
608 // specialization or explicit instantiation of a class template,
609 // the class-key shall agree in kind with the original class
610 // template declaration (7.1.5.3).
611 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000612 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000613 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000614 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000615 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000616 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000617 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000618 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000619 }
620
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000621 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000622 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000623 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
624 Diag(NameLoc, diag::err_redefinition) << Name;
625 Diag(Def->getLocation(), diag::note_previous_definition);
626 // FIXME: Would it make sense to try to "forget" the previous
627 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000628 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000629 }
630 }
631 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
632 // Maybe we will complain about the shadowed template parameter.
633 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
634 // Just pretend that we didn't see the previous declaration.
635 PrevDecl = 0;
636 } else if (PrevDecl) {
637 // C++ [temp]p5:
638 // A class template shall not have the same name as any other
639 // template, class, function, object, enumeration, enumerator,
640 // namespace, or type in the same scope (3.3), except as specified
641 // in (14.5.4).
642 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
643 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000644 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000645 }
646
Douglas Gregordba32632009-02-10 19:49:53 +0000647 // Check the template parameter list of this declaration, possibly
648 // merging in the template parameter list from the previous class
649 // template declaration.
650 if (CheckTemplateParameterList(TemplateParams,
651 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
652 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000653
Douglas Gregore362cea2009-05-10 22:57:19 +0000654 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000655 // declaration!
656
John McCall27b5c252009-09-14 21:59:20 +0000657 // If this is a friend declaration of an undeclared template,
658 // create the template in the innermost namespace scope.
659 if (TUK == TUK_Friend && !PrevClassTemplate) {
660 while (!SemanticContext->isFileContext())
661 SemanticContext = SemanticContext->getParent();
662 }
663
Mike Stump11289f42009-09-09 15:08:12 +0000664 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000665 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000666 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000667 PrevClassTemplate->getTemplatedDecl() : 0,
668 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000669
670 ClassTemplateDecl *NewTemplate
671 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
672 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000673 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000674 NewClass->setDescribedClassTemplate(NewTemplate);
675
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000676 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000677 QualType T =
678 Context.getTypeDeclType(NewClass,
679 PrevClassTemplate?
680 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000681 assert(T->isDependentType() && "Class template type is not dependent?");
682 (void)T;
683
Anders Carlsson137108d2009-03-26 01:24:28 +0000684 // Set the access specifier.
John McCall27b5c252009-09-14 21:59:20 +0000685 if (TUK == TUK_Friend)
686 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
687 PrevClassTemplate != NULL);
688 else
689 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000690
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000691 // Set the lexical context of these templates
692 NewClass->setLexicalDeclContext(CurContext);
693 NewTemplate->setLexicalDeclContext(CurContext);
694
John McCall9bb74a52009-07-31 02:45:11 +0000695 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000696 NewClass->startDefinition();
697
698 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000699 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000700
John McCall27b5c252009-09-14 21:59:20 +0000701 if (TUK != TUK_Friend)
702 PushOnScopeChains(NewTemplate, S);
703 else {
704 // We might be replacing an existing declaration in the lookup tables;
705 // if so, borrow its access specifier.
706 if (PrevClassTemplate)
707 NewTemplate->setAccess(PrevClassTemplate->getAccess());
708
709 // Friend templates are visible in fairly strange ways.
710 if (!CurContext->isDependentContext()) {
711 DeclContext *DC = SemanticContext->getLookupContext();
712 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
713 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
714 PushOnScopeChains(NewTemplate, EnclosingScope,
715 /* AddToContext = */ false);
716 }
717 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000718
Douglas Gregordba32632009-02-10 19:49:53 +0000719 if (Invalid) {
720 NewTemplate->setInvalidDecl();
721 NewClass->setInvalidDecl();
722 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000723 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000724}
725
Douglas Gregordba32632009-02-10 19:49:53 +0000726/// \brief Checks the validity of a template parameter list, possibly
727/// considering the template parameter list from a previous
728/// declaration.
729///
730/// If an "old" template parameter list is provided, it must be
731/// equivalent (per TemplateParameterListsAreEqual) to the "new"
732/// template parameter list.
733///
734/// \param NewParams Template parameter list for a new template
735/// declaration. This template parameter list will be updated with any
736/// default arguments that are carried through from the previous
737/// template parameter list.
738///
739/// \param OldParams If provided, template parameter list from a
740/// previous declaration of the same template. Default template
741/// arguments will be merged from the old template parameter list to
742/// the new template parameter list.
743///
744/// \returns true if an error occurred, false otherwise.
745bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
746 TemplateParameterList *OldParams) {
747 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000748
Douglas Gregordba32632009-02-10 19:49:53 +0000749 // C++ [temp.param]p10:
750 // The set of default template-arguments available for use with a
751 // template declaration or definition is obtained by merging the
752 // default arguments from the definition (if in scope) and all
753 // declarations in scope in the same way default function
754 // arguments are (8.3.6).
755 bool SawDefaultArgument = false;
756 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000757
Anders Carlsson327865d2009-06-12 23:20:15 +0000758 bool SawParameterPack = false;
759 SourceLocation ParameterPackLoc;
760
Mike Stumpc89c8e32009-02-11 23:03:27 +0000761 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000762 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000763 if (OldParams)
764 OldParam = OldParams->begin();
765
766 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
767 NewParamEnd = NewParams->end();
768 NewParam != NewParamEnd; ++NewParam) {
769 // Variables used to diagnose redundant default arguments
770 bool RedundantDefaultArg = false;
771 SourceLocation OldDefaultLoc;
772 SourceLocation NewDefaultLoc;
773
774 // Variables used to diagnose missing default arguments
775 bool MissingDefaultArg = false;
776
Anders Carlsson327865d2009-06-12 23:20:15 +0000777 // C++0x [temp.param]p11:
778 // If a template parameter of a class template is a template parameter pack,
779 // it must be the last template parameter.
780 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +0000781 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +0000782 diag::err_template_param_pack_must_be_last_template_parameter);
783 Invalid = true;
784 }
785
Douglas Gregordba32632009-02-10 19:49:53 +0000786 // Merge default arguments for template type parameters.
787 if (TemplateTypeParmDecl *NewTypeParm
788 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump11289f42009-09-09 15:08:12 +0000789 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000790 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000791
Anders Carlsson327865d2009-06-12 23:20:15 +0000792 if (NewTypeParm->isParameterPack()) {
793 assert(!NewTypeParm->hasDefaultArgument() &&
794 "Parameter packs can't have a default argument!");
795 SawParameterPack = true;
796 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000797 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000798 NewTypeParm->hasDefaultArgument()) {
799 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
800 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
801 SawDefaultArgument = true;
802 RedundantDefaultArg = true;
803 PreviousDefaultArgLoc = NewDefaultLoc;
804 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
805 // Merge the default argument from the old declaration to the
806 // new declaration.
807 SawDefaultArgument = true;
808 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
809 OldTypeParm->getDefaultArgumentLoc(),
810 true);
811 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
812 } else if (NewTypeParm->hasDefaultArgument()) {
813 SawDefaultArgument = true;
814 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
815 } else if (SawDefaultArgument)
816 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000817 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000818 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000819 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000820 NonTypeTemplateParmDecl *OldNonTypeParm
821 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000822 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000823 NewNonTypeParm->hasDefaultArgument()) {
824 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
825 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
826 SawDefaultArgument = true;
827 RedundantDefaultArg = true;
828 PreviousDefaultArgLoc = NewDefaultLoc;
829 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
830 // Merge the default argument from the old declaration to the
831 // new declaration.
832 SawDefaultArgument = true;
833 // FIXME: We need to create a new kind of "default argument"
834 // expression that points to a previous template template
835 // parameter.
836 NewNonTypeParm->setDefaultArgument(
837 OldNonTypeParm->getDefaultArgument());
838 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
839 } else if (NewNonTypeParm->hasDefaultArgument()) {
840 SawDefaultArgument = true;
841 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
842 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000843 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000844 } else {
Douglas Gregordba32632009-02-10 19:49:53 +0000845 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000846 TemplateTemplateParmDecl *NewTemplateParm
847 = cast<TemplateTemplateParmDecl>(*NewParam);
848 TemplateTemplateParmDecl *OldTemplateParm
849 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000850 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000851 NewTemplateParm->hasDefaultArgument()) {
852 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
853 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
854 SawDefaultArgument = true;
855 RedundantDefaultArg = true;
856 PreviousDefaultArgLoc = NewDefaultLoc;
857 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
858 // Merge the default argument from the old declaration to the
859 // new declaration.
860 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +0000861 // FIXME: We need to create a new kind of "default argument" expression
862 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +0000863 NewTemplateParm->setDefaultArgument(
864 OldTemplateParm->getDefaultArgument());
865 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
866 } else if (NewTemplateParm->hasDefaultArgument()) {
867 SawDefaultArgument = true;
868 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
869 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000870 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +0000871 }
872
873 if (RedundantDefaultArg) {
874 // C++ [temp.param]p12:
875 // A template-parameter shall not be given default arguments
876 // by two different declarations in the same scope.
877 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
878 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
879 Invalid = true;
880 } else if (MissingDefaultArg) {
881 // C++ [temp.param]p11:
882 // If a template-parameter has a default template-argument,
883 // all subsequent template-parameters shall have a default
884 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +0000885 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +0000886 diag::err_template_param_default_arg_missing);
887 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
888 Invalid = true;
889 }
890
891 // If we have an old template parameter list that we're merging
892 // in, move on to the next parameter.
893 if (OldParams)
894 ++OldParam;
895 }
896
897 return Invalid;
898}
Douglas Gregord32e0282009-02-09 23:23:08 +0000899
Mike Stump11289f42009-09-09 15:08:12 +0000900/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +0000901/// specifier, returning the template parameter list that applies to the
902/// name.
903///
904/// \param DeclStartLoc the start of the declaration that has a scope
905/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +0000906///
Douglas Gregord8d297c2009-07-21 23:53:31 +0000907/// \param SS the scope specifier that will be matched to the given template
908/// parameter lists. This scope specifier precedes a qualified name that is
909/// being declared.
910///
911/// \param ParamLists the template parameter lists, from the outermost to the
912/// innermost template parameter lists.
913///
914/// \param NumParamLists the number of template parameter lists in ParamLists.
915///
Mike Stump11289f42009-09-09 15:08:12 +0000916/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +0000917/// name that is preceded by the scope specifier @p SS. This template
918/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +0000919/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +0000920/// template specialization), or may be NULL (if we were's declaring isn't
921/// itself a template).
922TemplateParameterList *
923Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
924 const CXXScopeSpec &SS,
925 TemplateParameterList **ParamLists,
926 unsigned NumParamLists) {
Douglas Gregord8d297c2009-07-21 23:53:31 +0000927 // Find the template-ids that occur within the nested-name-specifier. These
928 // template-ids will match up with the template parameter lists.
929 llvm::SmallVector<const TemplateSpecializationType *, 4>
930 TemplateIdsInSpecifier;
931 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
932 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +0000933 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +0000934 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
935 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
936 if (!Template)
937 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +0000938
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000939 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +0000940 ClassTemplateSpecializationDecl *SpecDecl
941 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
942 // If the nested name specifier refers to an explicit specialization,
943 // we don't need a template<> header.
Douglas Gregor82e22862009-09-16 00:01:48 +0000944 // FIXME: revisit this approach once we cope with specializations
Douglas Gregor15301382009-07-30 17:40:51 +0000945 // properly.
Douglas Gregord8d297c2009-07-21 23:53:31 +0000946 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
947 continue;
948 }
Mike Stump11289f42009-09-09 15:08:12 +0000949
Douglas Gregord8d297c2009-07-21 23:53:31 +0000950 TemplateIdsInSpecifier.push_back(SpecType);
951 }
952 }
Mike Stump11289f42009-09-09 15:08:12 +0000953
Douglas Gregord8d297c2009-07-21 23:53:31 +0000954 // Reverse the list of template-ids in the scope specifier, so that we can
955 // more easily match up the template-ids and the template parameter lists.
956 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +0000957
Douglas Gregord8d297c2009-07-21 23:53:31 +0000958 SourceLocation FirstTemplateLoc = DeclStartLoc;
959 if (NumParamLists)
960 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000961
Douglas Gregord8d297c2009-07-21 23:53:31 +0000962 // Match the template-ids found in the specifier to the template parameter
963 // lists.
964 unsigned Idx = 0;
965 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
966 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +0000967 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
968 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +0000969 if (Idx >= NumParamLists) {
970 // We have a template-id without a corresponding template parameter
971 // list.
972 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +0000973 // FIXME: the location information here isn't great.
974 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +0000975 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +0000976 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +0000977 << SS.getRange();
978 } else {
979 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
980 << SS.getRange()
981 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
982 "template<> ");
983 }
984 return 0;
985 }
Mike Stump11289f42009-09-09 15:08:12 +0000986
Douglas Gregord8d297c2009-07-21 23:53:31 +0000987 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +0000988 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +0000989 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +0000990 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
991
Mike Stump11289f42009-09-09 15:08:12 +0000992 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +0000993 = dyn_cast<ClassTemplateDecl>(Template)) {
994 TemplateParameterList *ExpectedTemplateParams = 0;
995 // Is this template-id naming the primary template?
996 if (Context.hasSameType(TemplateId,
997 ClassTemplate->getInjectedClassNameType(Context)))
998 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
999 // ... or a partial specialization?
1000 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1001 = ClassTemplate->findPartialSpecialization(TemplateId))
1002 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1003
1004 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001005 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001006 ExpectedTemplateParams,
1007 true);
Mike Stump11289f42009-09-09 15:08:12 +00001008 }
Douglas Gregor15301382009-07-30 17:40:51 +00001009 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001010 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001011 diag::err_template_param_list_matches_nontemplate)
1012 << TemplateId
1013 << ParamLists[Idx]->getSourceRange();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001014 }
Mike Stump11289f42009-09-09 15:08:12 +00001015
Douglas Gregord8d297c2009-07-21 23:53:31 +00001016 // If there were at least as many template-ids as there were template
1017 // parameter lists, then there are no template parameter lists remaining for
1018 // the declaration itself.
1019 if (Idx >= NumParamLists)
1020 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001021
Douglas Gregord8d297c2009-07-21 23:53:31 +00001022 // If there were too many template parameter lists, complain about that now.
1023 if (Idx != NumParamLists - 1) {
1024 while (Idx < NumParamLists - 1) {
Mike Stump11289f42009-09-09 15:08:12 +00001025 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001026 diag::err_template_spec_extra_headers)
1027 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1028 ParamLists[Idx]->getRAngleLoc());
1029 ++Idx;
1030 }
1031 }
Mike Stump11289f42009-09-09 15:08:12 +00001032
Douglas Gregord8d297c2009-07-21 23:53:31 +00001033 // Return the last template parameter list, which corresponds to the
1034 // entity being declared.
1035 return ParamLists[NumParamLists - 1];
1036}
1037
Douglas Gregorc40290e2009-03-09 23:48:35 +00001038/// \brief Translates template arguments as provided by the parser
1039/// into template arguments used by semantic analysis.
Douglas Gregor0e876e02009-09-25 23:53:26 +00001040void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
1041 SourceLocation *TemplateArgLocs,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001042 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
1043 TemplateArgs.reserve(TemplateArgsIn.size());
1044
1045 void **Args = TemplateArgsIn.getArgs();
1046 bool *ArgIsType = TemplateArgsIn.getArgIsType();
1047 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
1048 TemplateArgs.push_back(
1049 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001050 //FIXME: Preserve type source info.
1051 Sema::GetTypeFromParser(Args[Arg]))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001052 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
1053 }
1054}
1055
Douglas Gregordc572a32009-03-30 22:58:21 +00001056QualType Sema::CheckTemplateIdType(TemplateName Name,
1057 SourceLocation TemplateLoc,
1058 SourceLocation LAngleLoc,
1059 const TemplateArgument *TemplateArgs,
1060 unsigned NumTemplateArgs,
1061 SourceLocation RAngleLoc) {
1062 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001063 if (!Template) {
1064 // The template name does not resolve to a template, so we just
1065 // build a dependent template-id type.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001066 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001067 NumTemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001068 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001069
Douglas Gregorc40290e2009-03-09 23:48:35 +00001070 // Check that the template argument list is well-formed for this
1071 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001072 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1073 NumTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001074 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001075 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001076 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001077 return QualType();
1078
Mike Stump11289f42009-09-09 15:08:12 +00001079 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001080 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001081 "Converted template argument list is too short!");
1082
1083 QualType CanonType;
1084
Douglas Gregordc572a32009-03-30 22:58:21 +00001085 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorc40290e2009-03-09 23:48:35 +00001086 TemplateArgs,
1087 NumTemplateArgs)) {
1088 // This class template specialization is a dependent
1089 // type. Therefore, its canonical type is another class template
1090 // specialization type that contains all of the converted
1091 // arguments in canonical form. This ensures that, e.g., A<T> and
1092 // A<T, T> have identical types when A is declared as:
1093 //
1094 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001095 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001096 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001097 Converted.getFlatArguments(),
1098 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001099
Douglas Gregora8e02e72009-07-28 23:00:59 +00001100 // FIXME: CanonType is not actually the canonical type, and unfortunately
1101 // it is a TemplateTypeSpecializationType that we will never use again.
1102 // In the future, we need to teach getTemplateSpecializationType to only
1103 // build the canonical type and return that to us.
1104 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001105 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001106 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001107 // Find the class template specialization declaration that
1108 // corresponds to these arguments.
1109 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001110 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001111 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001112 Converted.flatSize(),
1113 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001114 void *InsertPos = 0;
1115 ClassTemplateSpecializationDecl *Decl
1116 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1117 if (!Decl) {
1118 // This is the first time we have referenced this class template
1119 // specialization. Create the canonical declaration and add it to
1120 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001121 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001122 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001123 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001124 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001125 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001126 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1127 Decl->setLexicalDeclContext(CurContext);
1128 }
1129
1130 CanonType = Context.getTypeDeclType(Decl);
1131 }
Mike Stump11289f42009-09-09 15:08:12 +00001132
Douglas Gregorc40290e2009-03-09 23:48:35 +00001133 // Build the fully-sugared type for this class template
1134 // specialization, which refers back to the class template
1135 // specialization we created or found.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001136 //FIXME: Preserve type source info.
Douglas Gregordc572a32009-03-30 22:58:21 +00001137 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1138 NumTemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001139}
1140
Douglas Gregor67a65642009-02-17 23:15:12 +00001141Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001142Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001143 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001144 ASTTemplateArgsPtr TemplateArgsIn,
1145 SourceLocation *TemplateArgLocs,
John McCalld8fe9af2009-09-08 17:47:29 +00001146 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001147 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001148
Douglas Gregorc40290e2009-03-09 23:48:35 +00001149 // Translate the parser's template argument list in our AST format.
1150 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1151 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001152
Douglas Gregordc572a32009-03-30 22:58:21 +00001153 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +00001154 TemplateArgs.data(),
1155 TemplateArgs.size(),
Douglas Gregordc572a32009-03-30 22:58:21 +00001156 RAngleLoc);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001157 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001158
1159 if (Result.isNull())
1160 return true;
1161
John McCalld8fe9af2009-09-08 17:47:29 +00001162 return Result.getAsOpaquePtr();
1163}
John McCall06f6fe8d2009-09-04 01:14:41 +00001164
John McCalld8fe9af2009-09-08 17:47:29 +00001165Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1166 TagUseKind TUK,
1167 DeclSpec::TST TagSpec,
1168 SourceLocation TagLoc) {
1169 if (TypeResult.isInvalid())
1170 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001171
John McCalld8fe9af2009-09-08 17:47:29 +00001172 QualType Type = QualType::getFromOpaquePtr(TypeResult.get());
John McCall06f6fe8d2009-09-04 01:14:41 +00001173
John McCalld8fe9af2009-09-08 17:47:29 +00001174 // Verify the tag specifier.
1175 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001176
John McCalld8fe9af2009-09-08 17:47:29 +00001177 if (const RecordType *RT = Type->getAs<RecordType>()) {
1178 RecordDecl *D = RT->getDecl();
1179
1180 IdentifierInfo *Id = D->getIdentifier();
1181 assert(Id && "templated class must have an identifier");
1182
1183 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1184 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001185 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001186 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1187 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001188 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001189 }
1190 }
1191
John McCalld8fe9af2009-09-08 17:47:29 +00001192 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1193
1194 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001195}
1196
Douglas Gregora727cb92009-06-30 22:34:41 +00001197Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1198 SourceLocation TemplateNameLoc,
1199 SourceLocation LAngleLoc,
1200 const TemplateArgument *TemplateArgs,
1201 unsigned NumTemplateArgs,
1202 SourceLocation RAngleLoc) {
1203 // FIXME: Can we do any checking at this point? I guess we could check the
1204 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001205 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001206 // though.
Mike Stump11289f42009-09-09 15:08:12 +00001207 return Owned(TemplateIdRefExpr::Create(Context,
Douglas Gregora727cb92009-06-30 22:34:41 +00001208 /*FIXME: New type?*/Context.OverloadTy,
1209 /*FIXME: Necessary?*/0,
1210 /*FIXME: Necessary?*/SourceRange(),
1211 Template, TemplateNameLoc, LAngleLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001212 TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001213 NumTemplateArgs, RAngleLoc));
1214}
1215
1216Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1217 SourceLocation TemplateNameLoc,
1218 SourceLocation LAngleLoc,
1219 ASTTemplateArgsPtr TemplateArgsIn,
1220 SourceLocation *TemplateArgLocs,
1221 SourceLocation RAngleLoc) {
1222 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001223
Douglas Gregora727cb92009-06-30 22:34:41 +00001224 // Translate the parser's template argument list in our AST format.
1225 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1226 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001227 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001228
Douglas Gregora727cb92009-06-30 22:34:41 +00001229 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1230 TemplateArgs.data(), TemplateArgs.size(),
1231 RAngleLoc);
1232}
1233
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001234Sema::OwningExprResult
1235Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base,
1236 SourceLocation OpLoc,
1237 tok::TokenKind OpKind,
1238 const CXXScopeSpec &SS,
1239 TemplateTy TemplateD,
1240 SourceLocation TemplateNameLoc,
1241 SourceLocation LAngleLoc,
1242 ASTTemplateArgsPtr TemplateArgsIn,
1243 SourceLocation *TemplateArgLocs,
1244 SourceLocation RAngleLoc) {
1245 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001246
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001247 // FIXME: We're going to end up looking up the template based on its name,
1248 // twice!
1249 DeclarationName Name;
1250 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
1251 Name = ActualTemplate->getDeclName();
1252 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
1253 Name = Ovl->getDeclName();
1254 else
Douglas Gregor308047d2009-09-09 00:23:06 +00001255 Name = Template.getAsDependentTemplateName()->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001256
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001257 // Translate the parser's template argument list in our AST format.
1258 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1259 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1260 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001261
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001262 // Do we have the save the actual template name? We might need it...
1263 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc,
1264 Name, true, LAngleLoc,
1265 TemplateArgs.data(), TemplateArgs.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001266 RAngleLoc, DeclPtrTy(), &SS);
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001267}
1268
Douglas Gregorb67535d2009-03-31 00:43:58 +00001269/// \brief Form a dependent template name.
1270///
1271/// This action forms a dependent template name given the template
1272/// name and its (presumably dependent) scope specifier. For
1273/// example, given "MetaFun::template apply", the scope specifier \p
1274/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1275/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001276Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001277Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1278 const IdentifierInfo &Name,
1279 SourceLocation NameLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001280 const CXXScopeSpec &SS,
1281 TypeTy *ObjectType) {
Mike Stump11289f42009-09-09 15:08:12 +00001282 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001283 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1284 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001285 // C++0x [temp.names]p5:
1286 // If a name prefixed by the keyword template is not the name of
1287 // a template, the program is ill-formed. [Note: the keyword
1288 // template may not be applied to non-template members of class
1289 // templates. -end note ] [ Note: as is the case with the
1290 // typename prefix, the template prefix is allowed in cases
1291 // where it is not strictly necessary; i.e., when the
1292 // nested-name-specifier or the expression on the left of the ->
1293 // or . is not dependent on a template-parameter, or the use
1294 // does not appear in the scope of a template. -end note]
1295 //
1296 // Note: C++03 was more strict here, because it banned the use of
1297 // the "template" keyword prior to a template-name that was not a
1298 // dependent name. C++ DR468 relaxed this requirement (the
1299 // "template" keyword is now permitted). We follow the C++0x
1300 // rules, even in C++03 mode, retroactively applying the DR.
1301 TemplateTy Template;
Mike Stump11289f42009-09-09 15:08:12 +00001302 TemplateNameKind TNK = isTemplateName(0, Name, NameLoc, &SS, ObjectType,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001303 false, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001304 if (TNK == TNK_Non_template) {
1305 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1306 << &Name;
1307 return TemplateTy();
1308 }
1309
1310 return Template;
1311 }
1312
Mike Stump11289f42009-09-09 15:08:12 +00001313 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001314 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorb67535d2009-03-31 00:43:58 +00001315 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1316}
1317
Mike Stump11289f42009-09-09 15:08:12 +00001318bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001319 const TemplateArgument &Arg,
1320 TemplateArgumentListBuilder &Converted) {
1321 // Check template type parameter.
1322 if (Arg.getKind() != TemplateArgument::Type) {
1323 // C++ [temp.arg.type]p1:
1324 // A template-argument for a template-parameter which is a
1325 // type shall be a type-id.
1326
1327 // We have a template type parameter but the template argument
1328 // is not a type.
1329 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1330 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001331
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001332 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001333 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001334
1335 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1336 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001337
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001338 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001339 Converted.Append(
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001340 TemplateArgument(Arg.getLocation(),
1341 Context.getCanonicalType(Arg.getAsType())));
1342 return false;
1343}
1344
Douglas Gregord32e0282009-02-09 23:23:08 +00001345/// \brief Check that the given template argument list is well-formed
1346/// for specializing the given template.
1347bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1348 SourceLocation TemplateLoc,
1349 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001350 const TemplateArgument *TemplateArgs,
1351 unsigned NumTemplateArgs,
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001352 SourceLocation RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001353 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001354 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001355 TemplateParameterList *Params = Template->getTemplateParameters();
1356 unsigned NumParams = Params->size();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001357 unsigned NumArgs = NumTemplateArgs;
Douglas Gregord32e0282009-02-09 23:23:08 +00001358 bool Invalid = false;
1359
Mike Stump11289f42009-09-09 15:08:12 +00001360 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001361 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001362
Anders Carlsson15201f12009-06-13 02:08:00 +00001363 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001364 (NumArgs < Params->getMinRequiredArguments() &&
1365 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001366 // FIXME: point at either the first arg beyond what we can handle,
1367 // or the '>', depending on whether we have too many or too few
1368 // arguments.
1369 SourceRange Range;
1370 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001371 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001372 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1373 << (NumArgs > NumParams)
1374 << (isa<ClassTemplateDecl>(Template)? 0 :
1375 isa<FunctionTemplateDecl>(Template)? 1 :
1376 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1377 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001378 Diag(Template->getLocation(), diag::note_template_decl_here)
1379 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001380 Invalid = true;
1381 }
Mike Stump11289f42009-09-09 15:08:12 +00001382
1383 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001384 // [...] The type and form of each template-argument specified in
1385 // a template-id shall match the type and form specified for the
1386 // corresponding parameter declared by the template in its
1387 // template-parameter-list.
1388 unsigned ArgIdx = 0;
1389 for (TemplateParameterList::iterator Param = Params->begin(),
1390 ParamEnd = Params->end();
1391 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001392 if (ArgIdx > NumArgs && PartialTemplateArgs)
1393 break;
Mike Stump11289f42009-09-09 15:08:12 +00001394
Douglas Gregord32e0282009-02-09 23:23:08 +00001395 // Decode the template argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001396 TemplateArgument Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00001397 if (ArgIdx >= NumArgs) {
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001398 // Retrieve the default template argument from the template
1399 // parameter.
1400 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001401 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001402 // We have an empty argument pack.
1403 Converted.BeginPack();
1404 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001405 break;
1406 }
Mike Stump11289f42009-09-09 15:08:12 +00001407
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001408 if (!TTP->hasDefaultArgument())
1409 break;
1410
Douglas Gregorc40290e2009-03-09 23:48:35 +00001411 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001412
1413 // If the argument type is dependent, instantiate it now based
1414 // on the previously-computed template arguments.
Douglas Gregor79cf6032009-03-10 20:44:00 +00001415 if (ArgType->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001416 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001417 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001418 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001419 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregord002c7b2009-05-11 23:53:27 +00001420
Anders Carlssonc8e71132009-06-05 04:47:51 +00001421 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001422 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001423 ArgType = SubstType(ArgType,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001424 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001425 TTP->getDefaultArgumentLoc(),
1426 TTP->getDeclName());
Douglas Gregor79cf6032009-03-10 20:44:00 +00001427 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001428
1429 if (ArgType.isNull())
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001430 return true;
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001431
Douglas Gregorc40290e2009-03-09 23:48:35 +00001432 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001433 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001434 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1435 if (!NTTP->hasDefaultArgument())
1436 break;
1437
Mike Stump11289f42009-09-09 15:08:12 +00001438 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001439 Template, Converted.getFlatArguments(),
Anders Carlsson40ed3442009-06-11 16:06:49 +00001440 Converted.flatSize(),
1441 SourceRange(TemplateLoc, RAngleLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001442
Anders Carlsson40ed3442009-06-11 16:06:49 +00001443 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001444 /*TakeArgs=*/false);
Anders Carlsson40ed3442009-06-11 16:06:49 +00001445
Mike Stump11289f42009-09-09 15:08:12 +00001446 Sema::OwningExprResult E
1447 = SubstExpr(NTTP->getDefaultArgument(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00001448 MultiLevelTemplateArgumentList(TemplateArgs));
Anders Carlsson40ed3442009-06-11 16:06:49 +00001449 if (E.isInvalid())
1450 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001451
Anders Carlsson40ed3442009-06-11 16:06:49 +00001452 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001453 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001454 TemplateTemplateParmDecl *TempParm
1455 = cast<TemplateTemplateParmDecl>(*Param);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001456
1457 if (!TempParm->hasDefaultArgument())
1458 break;
1459
John McCall76d824f2009-08-25 22:02:44 +00001460 // FIXME: Subst default argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001461 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001462 }
1463 } else {
1464 // Retrieve the template argument produced by the user.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001465 Arg = TemplateArgs[ArgIdx];
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001466 }
1467
Douglas Gregord32e0282009-02-09 23:23:08 +00001468
1469 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001470 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001471 Converted.BeginPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001472 // Check all the remaining arguments (if any).
1473 for (; ArgIdx < NumArgs; ++ArgIdx) {
1474 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1475 Invalid = true;
1476 }
Mike Stump11289f42009-09-09 15:08:12 +00001477
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001478 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001479 } else {
1480 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1481 Invalid = true;
1482 }
Mike Stump11289f42009-09-09 15:08:12 +00001483 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord32e0282009-02-09 23:23:08 +00001484 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1485 // Check non-type template parameters.
Douglas Gregor463421d2009-03-03 04:44:36 +00001486
John McCall76d824f2009-08-25 22:02:44 +00001487 // Do substitution on the type of the non-type template parameter
1488 // with the template arguments we've seen thus far.
Douglas Gregor463421d2009-03-03 04:44:36 +00001489 QualType NTTPType = NTTP->getType();
1490 if (NTTPType->isDependentType()) {
John McCall76d824f2009-08-25 22:02:44 +00001491 // Do substitution on the type of the non-type template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001492 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001493 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001494 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001495 SourceRange(TemplateLoc, RAngleLoc));
1496
Anders Carlssonc8e71132009-06-05 04:47:51 +00001497 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001498 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001499 NTTPType = SubstType(NTTPType,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00001500 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001501 NTTP->getLocation(),
1502 NTTP->getDeclName());
Douglas Gregor463421d2009-03-03 04:44:36 +00001503 // If that worked, check the non-type template parameter type
1504 // for validity.
1505 if (!NTTPType.isNull())
Mike Stump11289f42009-09-09 15:08:12 +00001506 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
Douglas Gregor463421d2009-03-03 04:44:36 +00001507 NTTP->getLocation());
Douglas Gregor463421d2009-03-03 04:44:36 +00001508 if (NTTPType.isNull()) {
1509 Invalid = true;
1510 break;
1511 }
1512 }
1513
Douglas Gregorc40290e2009-03-09 23:48:35 +00001514 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001515 case TemplateArgument::Null:
1516 assert(false && "Should never see a NULL template argument here");
1517 break;
Mike Stump11289f42009-09-09 15:08:12 +00001518
Douglas Gregorc40290e2009-03-09 23:48:35 +00001519 case TemplateArgument::Expression: {
1520 Expr *E = Arg.getAsExpr();
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001521 TemplateArgument Result;
1522 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregord32e0282009-02-09 23:23:08 +00001523 Invalid = true;
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001524 else
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001525 Converted.Append(Result);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001526 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001527 }
1528
Douglas Gregorc40290e2009-03-09 23:48:35 +00001529 case TemplateArgument::Declaration:
1530 case TemplateArgument::Integral:
1531 // We've already checked this template argument, so just copy
1532 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001533 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001534 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001535
Douglas Gregorc40290e2009-03-09 23:48:35 +00001536 case TemplateArgument::Type:
1537 // We have a non-type template parameter but the template
1538 // argument is a type.
Mike Stump11289f42009-09-09 15:08:12 +00001539
Douglas Gregorc40290e2009-03-09 23:48:35 +00001540 // C++ [temp.arg]p2:
1541 // In a template-argument, an ambiguity between a type-id and
1542 // an expression is resolved to a type-id, regardless of the
1543 // form of the corresponding template-parameter.
1544 //
1545 // We warn specifically about this case, since it can be rather
1546 // confusing for users.
1547 if (Arg.getAsType()->isFunctionType())
1548 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1549 << Arg.getAsType();
1550 else
1551 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1552 Diag((*Param)->getLocation(), diag::note_template_param_here);
1553 Invalid = true;
Anders Carlssonbc343912009-06-15 17:04:53 +00001554 break;
Mike Stump11289f42009-09-09 15:08:12 +00001555
Anders Carlssonbc343912009-06-15 17:04:53 +00001556 case TemplateArgument::Pack:
1557 assert(0 && "FIXME: Implement!");
1558 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001559 }
Mike Stump11289f42009-09-09 15:08:12 +00001560 } else {
Douglas Gregord32e0282009-02-09 23:23:08 +00001561 // Check template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001562 TemplateTemplateParmDecl *TempParm
Douglas Gregord32e0282009-02-09 23:23:08 +00001563 = cast<TemplateTemplateParmDecl>(*Param);
Mike Stump11289f42009-09-09 15:08:12 +00001564
Douglas Gregorc40290e2009-03-09 23:48:35 +00001565 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001566 case TemplateArgument::Null:
1567 assert(false && "Should never see a NULL template argument here");
1568 break;
Mike Stump11289f42009-09-09 15:08:12 +00001569
Douglas Gregorc40290e2009-03-09 23:48:35 +00001570 case TemplateArgument::Expression: {
1571 Expr *ArgExpr = Arg.getAsExpr();
1572 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1573 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1574 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1575 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001576
Douglas Gregorc40290e2009-03-09 23:48:35 +00001577 // Add the converted template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001578 Decl *D
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00001579 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001580 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorc40290e2009-03-09 23:48:35 +00001581 continue;
1582 }
1583 }
1584 // fall through
Mike Stump11289f42009-09-09 15:08:12 +00001585
Douglas Gregorc40290e2009-03-09 23:48:35 +00001586 case TemplateArgument::Type: {
1587 // We have a template template parameter but the template
1588 // argument does not refer to a template.
1589 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1590 Invalid = true;
1591 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001592 }
1593
Douglas Gregorc40290e2009-03-09 23:48:35 +00001594 case TemplateArgument::Declaration:
1595 // We've already checked this template argument, so just copy
1596 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001597 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001598 break;
Mike Stump11289f42009-09-09 15:08:12 +00001599
Douglas Gregorc40290e2009-03-09 23:48:35 +00001600 case TemplateArgument::Integral:
1601 assert(false && "Integral argument with template template parameter");
1602 break;
Mike Stump11289f42009-09-09 15:08:12 +00001603
Anders Carlssonbc343912009-06-15 17:04:53 +00001604 case TemplateArgument::Pack:
1605 assert(0 && "FIXME: Implement!");
1606 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001607 }
Douglas Gregord32e0282009-02-09 23:23:08 +00001608 }
1609 }
1610
1611 return Invalid;
1612}
1613
1614/// \brief Check a template argument against its corresponding
1615/// template type parameter.
1616///
1617/// This routine implements the semantics of C++ [temp.arg.type]. It
1618/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001619bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
Douglas Gregord32e0282009-02-09 23:23:08 +00001620 QualType Arg, SourceLocation ArgLoc) {
1621 // C++ [temp.arg.type]p2:
1622 // A local type, a type with no linkage, an unnamed type or a type
1623 // compounded from any of these types shall not be used as a
1624 // template-argument for a template type-parameter.
1625 //
1626 // FIXME: Perform the recursive and no-linkage type checks.
1627 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001628 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001629 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001630 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001631 Tag = RecordT;
1632 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1633 return Diag(ArgLoc, diag::err_template_arg_local_type)
1634 << QualType(Tag, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001635 else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001636 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001637 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1638 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1639 return true;
1640 }
1641
1642 return false;
1643}
1644
Douglas Gregorccb07762009-02-11 19:52:55 +00001645/// \brief Checks whether the given template argument is the address
1646/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001647bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1648 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001649 bool Invalid = false;
1650
1651 // See through any implicit casts we added to fix the type.
1652 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1653 Arg = Cast->getSubExpr();
1654
Sebastian Redl576fd422009-05-10 18:38:11 +00001655 // C++0x allows nullptr, and there's no further checking to be done for that.
1656 if (Arg->getType()->isNullPtrType())
1657 return false;
1658
Douglas Gregorccb07762009-02-11 19:52:55 +00001659 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001660 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001661 // A template-argument for a non-type, non-template
1662 // template-parameter shall be one of: [...]
1663 //
1664 // -- the address of an object or function with external
1665 // linkage, including function templates and function
1666 // template-ids but excluding non-static class members,
1667 // expressed as & id-expression where the & is optional if
1668 // the name refers to a function or array, or if the
1669 // corresponding template-parameter is a reference; or
1670 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001671
Douglas Gregorccb07762009-02-11 19:52:55 +00001672 // Ignore (and complain about) any excess parentheses.
1673 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1674 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001675 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001676 diag::err_template_arg_extra_parens)
1677 << Arg->getSourceRange();
1678 Invalid = true;
1679 }
1680
1681 Arg = Parens->getSubExpr();
1682 }
1683
1684 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1685 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1686 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1687 } else
1688 DRE = dyn_cast<DeclRefExpr>(Arg);
1689
1690 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00001691 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001692 diag::err_template_arg_not_object_or_func_form)
1693 << Arg->getSourceRange();
1694
1695 // Cannot refer to non-static data members
1696 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1697 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1698 << Field << Arg->getSourceRange();
1699
1700 // Cannot refer to non-static member functions
1701 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1702 if (!Method->isStatic())
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_method)
1705 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001706
Douglas Gregorccb07762009-02-11 19:52:55 +00001707 // Functions must have external linkage.
1708 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1709 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00001710 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001711 diag::err_template_arg_function_not_extern)
1712 << Func << Arg->getSourceRange();
1713 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1714 << true;
1715 return true;
1716 }
1717
1718 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001719 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00001720 return Invalid;
1721 }
1722
1723 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1724 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00001725 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001726 diag::err_template_arg_object_not_extern)
1727 << Var << Arg->getSourceRange();
1728 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1729 << true;
1730 return true;
1731 }
1732
1733 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001734 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00001735 return Invalid;
1736 }
Mike Stump11289f42009-09-09 15:08:12 +00001737
Douglas Gregorccb07762009-02-11 19:52:55 +00001738 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001739 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001740 diag::err_template_arg_not_object_or_func)
1741 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001742 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001743 diag::note_template_arg_refers_here);
1744 return true;
1745}
1746
1747/// \brief Checks whether the given template argument is a pointer to
1748/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump11289f42009-09-09 15:08:12 +00001749bool
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001750Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001751 bool Invalid = false;
1752
1753 // See through any implicit casts we added to fix the type.
1754 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1755 Arg = Cast->getSubExpr();
1756
Sebastian Redl576fd422009-05-10 18:38:11 +00001757 // C++0x allows nullptr, and there's no further checking to be done for that.
1758 if (Arg->getType()->isNullPtrType())
1759 return false;
1760
Douglas Gregorccb07762009-02-11 19:52:55 +00001761 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001762 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001763 // A template-argument for a non-type, non-template
1764 // template-parameter shall be one of: [...]
1765 //
1766 // -- a pointer to member expressed as described in 5.3.1.
1767 QualifiedDeclRefExpr *DRE = 0;
1768
1769 // Ignore (and complain about) any excess parentheses.
1770 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1771 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001772 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001773 diag::err_template_arg_extra_parens)
1774 << Arg->getSourceRange();
1775 Invalid = true;
1776 }
1777
1778 Arg = Parens->getSubExpr();
1779 }
1780
1781 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1782 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1783 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1784
1785 if (!DRE)
1786 return Diag(Arg->getSourceRange().getBegin(),
1787 diag::err_template_arg_not_pointer_to_member_form)
1788 << Arg->getSourceRange();
1789
1790 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1791 assert((isa<FieldDecl>(DRE->getDecl()) ||
1792 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1793 "Only non-static member pointers can make it here");
1794
1795 // Okay: this is the address of a non-static member, and therefore
1796 // a member pointer constant.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001797 Member = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00001798 return Invalid;
1799 }
1800
1801 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001802 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001803 diag::err_template_arg_not_pointer_to_member_form)
1804 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001805 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001806 diag::note_template_arg_refers_here);
1807 return true;
1808}
1809
Douglas Gregord32e0282009-02-09 23:23:08 +00001810/// \brief Check a template argument against its corresponding
1811/// non-type template parameter.
1812///
Douglas Gregor463421d2009-03-03 04:44:36 +00001813/// This routine implements the semantics of C++ [temp.arg.nontype].
1814/// It returns true if an error occurred, and false otherwise. \p
1815/// InstantiatedParamType is the type of the non-type template
1816/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001817///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001818/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00001819bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00001820 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001821 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001822 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1823
Douglas Gregor86560402009-02-10 23:36:10 +00001824 // If either the parameter has a dependent type or the argument is
1825 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001826 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00001827 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1828 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001829 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00001830 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001831 }
Douglas Gregor86560402009-02-10 23:36:10 +00001832
1833 // C++ [temp.arg.nontype]p5:
1834 // The following conversions are performed on each expression used
1835 // as a non-type template-argument. If a non-type
1836 // template-argument cannot be converted to the type of the
1837 // corresponding template-parameter then the program is
1838 // ill-formed.
1839 //
1840 // -- for a non-type template-parameter of integral or
1841 // enumeration type, integral promotions (4.5) and integral
1842 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00001843 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001844 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00001845 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00001846 // C++ [temp.arg.nontype]p1:
1847 // A template-argument for a non-type, non-template
1848 // template-parameter shall be one of:
1849 //
1850 // -- an integral constant-expression of integral or enumeration
1851 // type; or
1852 // -- the name of a non-type template-parameter; or
1853 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001854 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00001855 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001856 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001857 diag::err_template_arg_not_integral_or_enumeral)
1858 << ArgType << Arg->getSourceRange();
1859 Diag(Param->getLocation(), diag::note_template_param_here);
1860 return true;
1861 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001862 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00001863 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1864 << ArgType << Arg->getSourceRange();
1865 return true;
1866 }
1867
1868 // FIXME: We need some way to more easily get the unqualified form
1869 // of the types without going all the way to the
1870 // canonical type.
1871 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1872 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1873 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1874 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1875
1876 // Try to convert the argument to the parameter's type.
1877 if (ParamType == ArgType) {
1878 // Okay: no conversion necessary
1879 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1880 !ParamType->isEnumeralType()) {
1881 // This is an integral promotion or conversion.
1882 ImpCastExprToType(Arg, ParamType);
1883 } else {
1884 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00001885 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001886 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00001887 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00001888 Diag(Param->getLocation(), diag::note_template_param_here);
1889 return true;
1890 }
1891
Douglas Gregor52aba872009-03-14 00:20:21 +00001892 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00001893 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001894 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00001895
1896 if (!Arg->isValueDependent()) {
1897 // Check that an unsigned parameter does not receive a negative
1898 // value.
1899 if (IntegerType->isUnsignedIntegerType()
1900 && (Value.isSigned() && Value.isNegative())) {
1901 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1902 << Value.toString(10) << Param->getType()
1903 << Arg->getSourceRange();
1904 Diag(Param->getLocation(), diag::note_template_param_here);
1905 return true;
1906 }
1907
1908 // Check that we don't overflow the template parameter type.
1909 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1910 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00001911 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00001912 diag::err_template_arg_too_large)
1913 << Value.toString(10) << Param->getType()
1914 << Arg->getSourceRange();
1915 Diag(Param->getLocation(), diag::note_template_param_here);
1916 return true;
1917 }
1918
1919 if (Value.getBitWidth() != AllowedBits)
1920 Value.extOrTrunc(AllowedBits);
1921 Value.setIsSigned(IntegerType->isSignedIntegerType());
1922 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001923
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001924 // Add the value of this argument to the list of converted
1925 // arguments. We use the bitwidth and signedness of the template
1926 // parameter.
1927 if (Arg->isValueDependent()) {
1928 // The argument is value-dependent. Create a new
1929 // TemplateArgument with the converted expression.
1930 Converted = TemplateArgument(Arg);
1931 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001932 }
1933
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001934 Converted = TemplateArgument(StartLoc, Value,
Mike Stump11289f42009-09-09 15:08:12 +00001935 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001936 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00001937 return false;
1938 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001939
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001940 // Handle pointer-to-function, reference-to-function, and
1941 // pointer-to-member-function all in (roughly) the same way.
1942 if (// -- For a non-type template-parameter of type pointer to
1943 // function, only the function-to-pointer conversion (4.3) is
1944 // applied. If the template-argument represents a set of
1945 // overloaded functions (or a pointer to such), the matching
1946 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00001947 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001948 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001949 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001950 // -- For a non-type template-parameter of type reference to
1951 // function, no conversions apply. If the template-argument
1952 // represents a set of overloaded functions, the matching
1953 // function is selected from the set (13.4).
1954 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001955 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001956 // -- For a non-type template-parameter of type pointer to
1957 // member function, no conversions apply. If the
1958 // template-argument represents a set of overloaded member
1959 // functions, the matching member function is selected from
1960 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00001961 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001962 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001963 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001964 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00001965 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00001966 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001967 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00001968 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1969 ParamType->isMemberPointerType())) {
1970 ArgType = ParamType;
1971 ImpCastExprToType(Arg, ParamType);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001972 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001973 ArgType = Context.getPointerType(ArgType);
1974 ImpCastExprToType(Arg, ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001975 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001976 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00001977 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1978 return true;
1979
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001980 FixOverloadedFunctionReference(Arg, Fn);
1981 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001982 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001983 ArgType = Context.getPointerType(Arg->getType());
1984 ImpCastExprToType(Arg, ArgType);
1985 }
1986 }
1987
Mike Stump11289f42009-09-09 15:08:12 +00001988 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00001989 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001990 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00001991 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001992 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00001993 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001994 Diag(Param->getLocation(), diag::note_template_param_here);
1995 return true;
1996 }
Mike Stump11289f42009-09-09 15:08:12 +00001997
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001998 if (ParamType->isMemberPointerType()) {
1999 NamedDecl *Member = 0;
2000 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2001 return true;
2002
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002003 if (Member)
2004 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002005 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002006 return false;
2007 }
Mike Stump11289f42009-09-09 15:08:12 +00002008
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002009 NamedDecl *Entity = 0;
2010 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2011 return true;
2012
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002013 if (Entity)
2014 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002015 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002016 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002017 }
2018
Chris Lattner696197c2009-02-20 21:37:53 +00002019 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002020 // -- for a non-type template-parameter of type pointer to
2021 // object, qualification conversions (4.4) and the
2022 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002023 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002024 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002025 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002026
Sebastian Redl576fd422009-05-10 18:38:11 +00002027 if (ArgType->isNullPtrType()) {
2028 ArgType = ParamType;
2029 ImpCastExprToType(Arg, ParamType);
2030 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002031 ArgType = Context.getArrayDecayedType(ArgType);
2032 ImpCastExprToType(Arg, ArgType);
Douglas Gregora9faa442009-02-11 00:44:29 +00002033 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002034
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002035 if (IsQualificationConversion(ArgType, ParamType)) {
2036 ArgType = ParamType;
2037 ImpCastExprToType(Arg, ParamType);
2038 }
Mike Stump11289f42009-09-09 15:08:12 +00002039
Douglas Gregor1515f762009-02-11 18:22:40 +00002040 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002041 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002042 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002043 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002044 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002045 Diag(Param->getLocation(), diag::note_template_param_here);
2046 return true;
2047 }
Mike Stump11289f42009-09-09 15:08:12 +00002048
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002049 NamedDecl *Entity = 0;
2050 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2051 return true;
2052
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002053 if (Entity)
2054 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002055 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002056 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002057 }
Mike Stump11289f42009-09-09 15:08:12 +00002058
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002059 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002060 // -- For a non-type template-parameter of type reference to
2061 // object, no conversions apply. The type referred to by the
2062 // reference may be more cv-qualified than the (otherwise
2063 // identical) type of the template-argument. The
2064 // template-parameter is bound directly to the
2065 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002066 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002067 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002068
Douglas Gregor1515f762009-02-11 18:22:40 +00002069 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002070 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002071 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002072 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002073 << Arg->getSourceRange();
2074 Diag(Param->getLocation(), diag::note_template_param_here);
2075 return true;
2076 }
2077
Mike Stump11289f42009-09-09 15:08:12 +00002078 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002079 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2080 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002081
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002082 if ((ParamQuals | ArgQuals) != ParamQuals) {
2083 Diag(Arg->getSourceRange().getBegin(),
2084 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002085 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002086 << Arg->getSourceRange();
2087 Diag(Param->getLocation(), diag::note_template_param_here);
2088 return true;
2089 }
Mike Stump11289f42009-09-09 15:08:12 +00002090
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002091 NamedDecl *Entity = 0;
2092 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2093 return true;
2094
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002095 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002096 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002097 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002098 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002099
2100 // -- For a non-type template-parameter of type pointer to data
2101 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002102 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002103 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2104
Douglas Gregor1515f762009-02-11 18:22:40 +00002105 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002106 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002107 } else if (ArgType->isNullPtrType()) {
2108 ImpCastExprToType(Arg, ParamType);
Douglas Gregor0e558532009-02-11 16:16:59 +00002109 } else if (IsQualificationConversion(ArgType, ParamType)) {
2110 ImpCastExprToType(Arg, ParamType);
2111 } else {
2112 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002113 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002114 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002115 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002116 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002117 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002118 }
2119
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002120 NamedDecl *Member = 0;
2121 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2122 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002123
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002124 if (Member)
2125 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002126 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002127 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00002128}
2129
2130/// \brief Check a template argument against its corresponding
2131/// template template parameter.
2132///
2133/// This routine implements the semantics of C++ [temp.arg.template].
2134/// It returns true if an error occurred, and false otherwise.
2135bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2136 DeclRefExpr *Arg) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002137 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2138 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2139
2140 // C++ [temp.arg.template]p1:
2141 // A template-argument for a template template-parameter shall be
2142 // the name of a class template, expressed as id-expression. Only
2143 // primary class templates are considered when matching the
2144 // template template argument with the corresponding parameter;
2145 // partial specializations are not considered even if their
2146 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002147 //
2148 // Note that we also allow template template parameters here, which
2149 // will happen when we are dealing with, e.g., class template
2150 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002151 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002152 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002153 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002154 "Only function templates are possible here");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002155 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2156 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002157 << Template;
2158 }
2159
2160 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2161 Param->getTemplateParameters(),
2162 true, true,
2163 Arg->getSourceRange().getBegin());
Douglas Gregord32e0282009-02-09 23:23:08 +00002164}
2165
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002166/// \brief Determine whether the given template parameter lists are
2167/// equivalent.
2168///
Mike Stump11289f42009-09-09 15:08:12 +00002169/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002170/// source code as part of a new template declaration.
2171///
2172/// \param Old The old template parameter list, typically found via
2173/// name lookup of the template declared with this template parameter
2174/// list.
2175///
2176/// \param Complain If true, this routine will produce a diagnostic if
2177/// the template parameter lists are not equivalent.
2178///
Douglas Gregor85e0f662009-02-10 00:24:35 +00002179/// \param IsTemplateTemplateParm If true, this routine is being
2180/// called to compare the template parameter lists of a template
2181/// template parameter.
2182///
2183/// \param TemplateArgLoc If this source location is valid, then we
2184/// are actually checking the template parameter list of a template
2185/// argument (New) against the template parameter list of its
2186/// corresponding template template parameter (Old). We produce
2187/// slightly different diagnostics in this scenario.
2188///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002189/// \returns True if the template parameter lists are equal, false
2190/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002191bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002192Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2193 TemplateParameterList *Old,
2194 bool Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002195 bool IsTemplateTemplateParm,
2196 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002197 if (Old->size() != New->size()) {
2198 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002199 unsigned NextDiag = diag::err_template_param_list_different_arity;
2200 if (TemplateArgLoc.isValid()) {
2201 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2202 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002203 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002204 Diag(New->getTemplateLoc(), NextDiag)
2205 << (New->size() > Old->size())
2206 << IsTemplateTemplateParm
2207 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002208 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2209 << IsTemplateTemplateParm
2210 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2211 }
2212
2213 return false;
2214 }
2215
2216 for (TemplateParameterList::iterator OldParm = Old->begin(),
2217 OldParmEnd = Old->end(), NewParm = New->begin();
2218 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2219 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002220 if (Complain) {
2221 unsigned NextDiag = diag::err_template_param_different_kind;
2222 if (TemplateArgLoc.isValid()) {
2223 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2224 NextDiag = diag::note_template_param_different_kind;
2225 }
2226 Diag((*NewParm)->getLocation(), NextDiag)
2227 << IsTemplateTemplateParm;
2228 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2229 << IsTemplateTemplateParm;
Douglas Gregor85e0f662009-02-10 00:24:35 +00002230 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002231 return false;
2232 }
2233
2234 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2235 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002236 // know we're at the same index).
2237#if 0
Mike Stump87c57ac2009-05-16 07:39:55 +00002238 // FIXME: Enable this code in debug mode *after* we properly go through
2239 // and "instantiate" the template parameter lists of template template
2240 // parameters. It's only after this instantiation that (1) any dependent
2241 // types within the template parameter list of the template template
2242 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregor85e0f662009-02-10 00:24:35 +00002243 // will match up.
Mike Stump11289f42009-09-09 15:08:12 +00002244 QualType OldParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002245 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
Mike Stump11289f42009-09-09 15:08:12 +00002246 QualType NewParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002247 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
Mike Stump11289f42009-09-09 15:08:12 +00002248 assert(Context.getCanonicalType(OldParmType) ==
2249 Context.getCanonicalType(NewParmType) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002250 "type parameter mismatch?");
2251#endif
Mike Stump11289f42009-09-09 15:08:12 +00002252 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002253 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2254 // The types of non-type template parameters must agree.
2255 NonTypeTemplateParmDecl *NewNTTP
2256 = cast<NonTypeTemplateParmDecl>(*NewParm);
2257 if (Context.getCanonicalType(OldNTTP->getType()) !=
2258 Context.getCanonicalType(NewNTTP->getType())) {
2259 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002260 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2261 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002262 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002263 diag::err_template_arg_template_params_mismatch);
2264 NextDiag = diag::note_template_nontype_parm_different_type;
2265 }
2266 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002267 << NewNTTP->getType()
2268 << IsTemplateTemplateParm;
Mike Stump11289f42009-09-09 15:08:12 +00002269 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002270 diag::note_template_nontype_parm_prev_declaration)
2271 << OldNTTP->getType();
2272 }
2273 return false;
2274 }
2275 } else {
2276 // The template parameter lists of template template
2277 // parameters must agree.
2278 // FIXME: Could we perform a faster "type" comparison here?
Mike Stump11289f42009-09-09 15:08:12 +00002279 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002280 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002281 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002282 = cast<TemplateTemplateParmDecl>(*OldParm);
2283 TemplateTemplateParmDecl *NewTTP
2284 = cast<TemplateTemplateParmDecl>(*NewParm);
2285 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2286 OldTTP->getTemplateParameters(),
2287 Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002288 /*IsTemplateTemplateParm=*/true,
2289 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002290 return false;
2291 }
2292 }
2293
2294 return true;
2295}
2296
2297/// \brief Check whether a template can be declared within this scope.
2298///
2299/// If the template declaration is valid in this scope, returns
2300/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002301bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002302Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002303 // Find the nearest enclosing declaration scope.
2304 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2305 (S->getFlags() & Scope::TemplateParamScope) != 0)
2306 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002307
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002308 // C++ [temp]p2:
2309 // A template-declaration can appear only as a namespace scope or
2310 // class scope declaration.
2311 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002312 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2313 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002314 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002315 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002316
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002317 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002318 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002319
2320 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2321 return false;
2322
Mike Stump11289f42009-09-09 15:08:12 +00002323 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002324 diag::err_template_outside_namespace_or_class_scope)
2325 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002326}
Douglas Gregor67a65642009-02-17 23:15:12 +00002327
Douglas Gregorf61eca92009-05-13 18:28:20 +00002328/// \brief Check whether a class template specialization or explicit
2329/// instantiation in the current context is well-formed.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002330///
Douglas Gregorf61eca92009-05-13 18:28:20 +00002331/// This routine determines whether a class template specialization or
Mike Stump11289f42009-09-09 15:08:12 +00002332/// explicit instantiation can be declared in the current context
2333/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2334/// appropriate diagnostics if there was an error. It returns true if
Douglas Gregorf61eca92009-05-13 18:28:20 +00002335// there was an error that we cannot recover from, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002336bool
Douglas Gregorf47b9112009-02-25 22:02:03 +00002337Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2338 ClassTemplateSpecializationDecl *PrevDecl,
2339 SourceLocation TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002340 SourceRange ScopeSpecifierRange,
Douglas Gregor30b01972009-06-12 22:21:45 +00002341 bool PartialSpecialization,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002342 bool ExplicitInstantiation) {
Douglas Gregorf47b9112009-02-25 22:02:03 +00002343 // C++ [temp.expl.spec]p2:
2344 // An explicit specialization shall be declared in the namespace
2345 // of which the template is a member, or, for member templates, in
2346 // the namespace of which the enclosing class or enclosing class
2347 // template is a member. An explicit specialization of a member
2348 // function, member class or static data member of a class
2349 // template shall be declared in the namespace of which the class
2350 // template is a member. Such a declaration may also be a
2351 // definition. If the declaration is not a definition, the
2352 // specialization may be defined later in the name- space in which
2353 // the explicit specialization was declared, or in a namespace
2354 // that encloses the one in which the explicit specialization was
2355 // declared.
2356 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor30b01972009-06-12 22:21:45 +00002357 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002358 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002359 << Kind << ClassTemplate;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002360 return true;
2361 }
2362
2363 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00002364 DeclContext *TemplateContext
Douglas Gregorf47b9112009-02-25 22:02:03 +00002365 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorf61eca92009-05-13 18:28:20 +00002366 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2367 !ExplicitInstantiation) {
Douglas Gregorf47b9112009-02-25 22:02:03 +00002368 // There is no prior declaration of this entity, so this
2369 // specialization must be in the same context as the template
2370 // itself.
2371 if (DC != TemplateContext) {
2372 if (isa<TranslationUnitDecl>(TemplateContext))
2373 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor30b01972009-06-12 22:21:45 +00002374 << PartialSpecialization
Douglas Gregorf47b9112009-02-25 22:02:03 +00002375 << ClassTemplate << ScopeSpecifierRange;
2376 else if (isa<NamespaceDecl>(TemplateContext))
2377 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Mike Stump11289f42009-09-09 15:08:12 +00002378 << PartialSpecialization << ClassTemplate
Douglas Gregor30b01972009-06-12 22:21:45 +00002379 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002380
2381 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2382 }
2383
2384 return false;
2385 }
2386
2387 // We have a previous declaration of this entity. Make sure that
2388 // this redeclaration (or definition) occurs in an enclosing namespace.
2389 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002390 // FIXME: In C++98, we would like to turn these errors into warnings,
2391 // dependent on a -Wc++0x flag.
Douglas Gregorf61eca92009-05-13 18:28:20 +00002392 bool SuppressedDiag = false;
Douglas Gregor30b01972009-06-12 22:21:45 +00002393 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorf61eca92009-05-13 18:28:20 +00002394 if (isa<TranslationUnitDecl>(TemplateContext)) {
2395 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2396 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002397 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorf61eca92009-05-13 18:28:20 +00002398 else
2399 SuppressedDiag = true;
2400 } else if (isa<NamespaceDecl>(TemplateContext)) {
2401 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2402 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002403 << Kind << ClassTemplate
Douglas Gregorf61eca92009-05-13 18:28:20 +00002404 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Mike Stump11289f42009-09-09 15:08:12 +00002405 else
Douglas Gregorf61eca92009-05-13 18:28:20 +00002406 SuppressedDiag = true;
2407 }
Mike Stump11289f42009-09-09 15:08:12 +00002408
Douglas Gregorf61eca92009-05-13 18:28:20 +00002409 if (!SuppressedDiag)
2410 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002411 }
2412
2413 return false;
2414}
2415
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002416/// \brief Check the non-type template arguments of a class template
2417/// partial specialization according to C++ [temp.class.spec]p9.
2418///
Douglas Gregor09a30232009-06-12 22:08:06 +00002419/// \param TemplateParams the template parameters of the primary class
2420/// template.
2421///
2422/// \param TemplateArg the template arguments of the class template
2423/// partial specialization.
2424///
2425/// \param MirrorsPrimaryTemplate will be set true if the class
2426/// template partial specialization arguments are identical to the
2427/// implicit template arguments of the primary template. This is not
2428/// necessarily an error (C++0x), and it is left to the caller to diagnose
2429/// this condition when it is an error.
2430///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002431/// \returns true if there was an error, false otherwise.
2432bool Sema::CheckClassTemplatePartialSpecializationArgs(
2433 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002434 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002435 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002436 // FIXME: the interface to this function will have to change to
2437 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002438 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002439
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002440 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002441
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002442 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002443 // Determine whether the template argument list of the partial
2444 // specialization is identical to the implicit argument list of
2445 // the primary template. The caller may need to diagnostic this as
2446 // an error per C++ [temp.class.spec]p9b3.
2447 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002448 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002449 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2450 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002451 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002452 MirrorsPrimaryTemplate = false;
2453 } else if (TemplateTemplateParmDecl *TTP
2454 = dyn_cast<TemplateTemplateParmDecl>(
2455 TemplateParams->getParam(I))) {
2456 // FIXME: We should settle on either Declaration storage or
2457 // Expression storage for template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002458 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor09a30232009-06-12 22:08:06 +00002459 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson40c1d492009-06-13 18:20:51 +00002460 ArgList[I].getAsDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002461 if (!ArgDecl)
Mike Stump11289f42009-09-09 15:08:12 +00002462 if (DeclRefExpr *DRE
Anders Carlsson40c1d492009-06-13 18:20:51 +00002463 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002464 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2465
2466 if (!ArgDecl ||
2467 ArgDecl->getIndex() != TTP->getIndex() ||
2468 ArgDecl->getDepth() != TTP->getDepth())
2469 MirrorsPrimaryTemplate = false;
2470 }
2471 }
2472
Mike Stump11289f42009-09-09 15:08:12 +00002473 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002474 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002475 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002476 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002477 }
2478
Anders Carlsson40c1d492009-06-13 18:20:51 +00002479 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002480 if (!ArgExpr) {
2481 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002482 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002483 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002484
2485 // C++ [temp.class.spec]p8:
2486 // A non-type argument is non-specialized if it is the name of a
2487 // non-type parameter. All other non-type arguments are
2488 // specialized.
2489 //
2490 // Below, we check the two conditions that only apply to
2491 // specialized non-type arguments, so skip any non-specialized
2492 // arguments.
2493 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002494 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002495 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002496 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002497 (Param->getIndex() != NTTP->getIndex() ||
2498 Param->getDepth() != NTTP->getDepth()))
2499 MirrorsPrimaryTemplate = false;
2500
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002501 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002502 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002503
2504 // C++ [temp.class.spec]p9:
2505 // Within the argument list of a class template partial
2506 // specialization, the following restrictions apply:
2507 // -- A partially specialized non-type argument expression
2508 // shall not involve a template parameter of the partial
2509 // specialization except when the argument expression is a
2510 // simple identifier.
2511 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002512 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002513 diag::err_dependent_non_type_arg_in_partial_spec)
2514 << ArgExpr->getSourceRange();
2515 return true;
2516 }
2517
2518 // -- The type of a template parameter corresponding to a
2519 // specialized non-type argument shall not be dependent on a
2520 // parameter of the specialization.
2521 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002522 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002523 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2524 << Param->getType()
2525 << ArgExpr->getSourceRange();
2526 Diag(Param->getLocation(), diag::note_template_param_here);
2527 return true;
2528 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002529
2530 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002531 }
2532
2533 return false;
2534}
2535
Douglas Gregorc08f4892009-03-25 00:13:59 +00002536Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002537Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2538 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002539 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002540 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002541 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002542 SourceLocation TemplateNameLoc,
2543 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002544 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002545 SourceLocation *TemplateArgLocs,
2546 SourceLocation RAngleLoc,
2547 AttributeList *Attr,
2548 MultiTemplateParamsArg TemplateParameterLists) {
John McCall06f6fe8d2009-09-04 01:14:41 +00002549 assert(TUK == TUK_Declaration || TUK == TUK_Definition);
2550
Douglas Gregor67a65642009-02-17 23:15:12 +00002551 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002552 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002553 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002554 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002555
Douglas Gregor2373c592009-05-31 09:31:02 +00002556 bool isPartialSpecialization = false;
2557
Douglas Gregorf47b9112009-02-25 22:02:03 +00002558 // Check the validity of the template headers that introduce this
2559 // template.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002560 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002561 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2562 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002563 TemplateParameterLists.size());
2564 if (TemplateParams && TemplateParams->size() > 0) {
2565 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002566
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002567 // C++ [temp.class.spec]p10:
2568 // The template parameter list of a specialization shall not
2569 // contain default template argument values.
2570 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2571 Decl *Param = TemplateParams->getParam(I);
2572 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2573 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002574 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002575 diag::err_default_arg_in_partial_spec);
2576 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2577 }
2578 } else if (NonTypeTemplateParmDecl *NTTP
2579 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2580 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002581 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002582 diag::err_default_arg_in_partial_spec)
2583 << DefArg->getSourceRange();
2584 NTTP->setDefaultArgument(0);
2585 DefArg->Destroy(Context);
2586 }
2587 } else {
2588 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2589 if (Expr *DefArg = TTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002590 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002591 diag::err_default_arg_in_partial_spec)
2592 << DefArg->getSourceRange();
2593 TTP->setDefaultArgument(0);
2594 DefArg->Destroy(Context);
Douglas Gregord5222052009-06-12 19:43:02 +00002595 }
2596 }
2597 }
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002598 } else if (!TemplateParams)
2599 Diag(KWLoc, diag::err_template_spec_needs_header)
2600 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregorf47b9112009-02-25 22:02:03 +00002601
Douglas Gregor67a65642009-02-17 23:15:12 +00002602 // Check that the specialization uses the same tag kind as the
2603 // original template.
2604 TagDecl::TagKind Kind;
2605 switch (TagSpec) {
2606 default: assert(0 && "Unknown tag type!");
2607 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2608 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2609 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2610 }
Douglas Gregord9034f02009-05-14 16:41:31 +00002611 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00002612 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00002613 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00002614 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00002615 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00002616 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00002617 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00002618 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00002619 diag::note_previous_use);
2620 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2621 }
2622
Douglas Gregorc40290e2009-03-09 23:48:35 +00002623 // Translate the parser's template argument list in our AST format.
2624 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2625 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2626
Douglas Gregor67a65642009-02-17 23:15:12 +00002627 // Check that the template argument list is well-formed for this
2628 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002629 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2630 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00002631 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002632 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00002633 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002634 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002635
Mike Stump11289f42009-09-09 15:08:12 +00002636 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00002637 ClassTemplate->getTemplateParameters()->size()) &&
2638 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00002639
Douglas Gregor2373c592009-05-31 09:31:02 +00002640 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00002641 // corresponds to these arguments.
2642 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00002643 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002644 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002645 if (CheckClassTemplatePartialSpecializationArgs(
2646 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002647 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002648 return true;
2649
Douglas Gregor09a30232009-06-12 22:08:06 +00002650 if (MirrorsPrimaryTemplate) {
2651 // C++ [temp.class.spec]p9b3:
2652 //
Mike Stump11289f42009-09-09 15:08:12 +00002653 // -- The argument list of the specialization shall not be identical
2654 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00002655 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00002656 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00002657 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00002658 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00002659 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00002660 ClassTemplate->getIdentifier(),
2661 TemplateNameLoc,
2662 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002663 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00002664 AS_none);
2665 }
2666
Douglas Gregor2373c592009-05-31 09:31:02 +00002667 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00002668 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002669 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002670 Converted.flatSize(),
2671 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002672 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002673 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002674 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002675 Converted.flatSize(),
2676 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00002677 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002678 ClassTemplateSpecializationDecl *PrevDecl = 0;
2679
2680 if (isPartialSpecialization)
2681 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00002682 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00002683 InsertPos);
2684 else
2685 PrevDecl
2686 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00002687
2688 ClassTemplateSpecializationDecl *Specialization = 0;
2689
Douglas Gregorf47b9112009-02-25 22:02:03 +00002690 // Check whether we can declare a class template specialization in
2691 // the current scope.
2692 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002693 TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002694 SS.getRange(),
Douglas Gregor30b01972009-06-12 22:21:45 +00002695 isPartialSpecialization,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002696 /*ExplicitInstantiation=*/false))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002697 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002698
Douglas Gregor15301382009-07-30 17:40:51 +00002699 // The canonical type
2700 QualType CanonType;
Douglas Gregor67a65642009-02-17 23:15:12 +00002701 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2702 // Since the only prior class template specialization with these
2703 // arguments was referenced but not declared, reuse that
2704 // declaration node as our own, updating its source location to
2705 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002706 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00002707 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00002708 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00002709 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00002710 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00002711 // Build the canonical type that describes the converted template
2712 // arguments of the class template partial specialization.
2713 CanonType = Context.getTemplateSpecializationType(
2714 TemplateName(ClassTemplate),
2715 Converted.getFlatArguments(),
2716 Converted.flatSize());
2717
Douglas Gregor2373c592009-05-31 09:31:02 +00002718 // Create a new class template partial specialization declaration node.
Mike Stump11289f42009-09-09 15:08:12 +00002719 TemplateParameterList *TemplateParams
Douglas Gregor2373c592009-05-31 09:31:02 +00002720 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2721 ClassTemplatePartialSpecializationDecl *PrevPartial
2722 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002723 ClassTemplatePartialSpecializationDecl *Partial
2724 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00002725 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002726 TemplateNameLoc,
2727 TemplateParams,
2728 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002729 Converted,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002730 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00002731
2732 if (PrevPartial) {
2733 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2734 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2735 } else {
2736 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2737 }
2738 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00002739
2740 // Check that all of the template parameters of the class template
2741 // partial specialization are deducible from the template
2742 // arguments. If not, this class template partial specialization
2743 // will never be used.
2744 llvm::SmallVector<bool, 8> DeducibleParams;
2745 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002746 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2747 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00002748 unsigned NumNonDeducible = 0;
2749 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2750 if (!DeducibleParams[I])
2751 ++NumNonDeducible;
2752
2753 if (NumNonDeducible) {
2754 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2755 << (NumNonDeducible > 1)
2756 << SourceRange(TemplateNameLoc, RAngleLoc);
2757 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2758 if (!DeducibleParams[I]) {
2759 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2760 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00002761 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002762 diag::note_partial_spec_unused_parameter)
2763 << Param->getDeclName();
2764 else
Mike Stump11289f42009-09-09 15:08:12 +00002765 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002766 diag::note_partial_spec_unused_parameter)
2767 << std::string("<anonymous>");
2768 }
2769 }
2770 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002771 } else {
2772 // Create a new class template specialization declaration node for
2773 // this explicit specialization.
2774 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00002775 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00002776 ClassTemplate->getDeclContext(),
2777 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002778 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002779 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00002780 PrevDecl);
2781
2782 if (PrevDecl) {
2783 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2784 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2785 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002786 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00002787 InsertPos);
2788 }
Douglas Gregor15301382009-07-30 17:40:51 +00002789
2790 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002791 }
2792
2793 // Note that this is an explicit specialization.
2794 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2795
2796 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002797 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002798 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002799 // FIXME: Should also handle explicit specialization after implicit
2800 // instantiation with a special diagnostic.
Douglas Gregor67a65642009-02-17 23:15:12 +00002801 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002802 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00002803 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00002804 Diag(Def->getLocation(), diag::note_previous_definition);
2805 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00002806 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002807 }
2808 }
2809
Douglas Gregord56a91e2009-02-26 22:19:44 +00002810 // Build the fully-sugared type for this class template
2811 // specialization as the user wrote in the specialization
2812 // itself. This means that we'll pretty-print the type retrieved
2813 // from the specialization's declaration the way that the user
2814 // actually wrote the specialization, rather than formatting the
2815 // name based on the "canonical" representation used to store the
2816 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002817 QualType WrittenTy
2818 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002819 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00002820 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00002821 CanonType);
Douglas Gregordc572a32009-03-30 22:58:21 +00002822 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002823 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00002824
Douglas Gregor1e249f82009-02-25 22:18:32 +00002825 // C++ [temp.expl.spec]p9:
2826 // A template explicit specialization is in the scope of the
2827 // namespace in which the template was defined.
2828 //
2829 // We actually implement this paragraph where we set the semantic
2830 // context (in the creation of the ClassTemplateSpecializationDecl),
2831 // but we also maintain the lexical context where the actual
2832 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00002833 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00002834
Douglas Gregor67a65642009-02-17 23:15:12 +00002835 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002836 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00002837 Specialization->startDefinition();
2838
2839 // Add the specialization into its lexical context, so that it can
2840 // be seen when iterating through the list of declarations in that
2841 // context. However, specializations are not found by name lookup.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002842 CurContext->addDecl(Specialization);
Chris Lattner83f095c2009-03-28 19:18:32 +00002843 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002844}
Douglas Gregor333489b2009-03-27 23:10:48 +00002845
Mike Stump11289f42009-09-09 15:08:12 +00002846Sema::DeclPtrTy
2847Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002848 MultiTemplateParamsArg TemplateParameterLists,
2849 Declarator &D) {
2850 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2851}
2852
Mike Stump11289f42009-09-09 15:08:12 +00002853Sema::DeclPtrTy
2854Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002855 MultiTemplateParamsArg TemplateParameterLists,
2856 Declarator &D) {
2857 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2858 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2859 "Not a function declarator!");
2860 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00002861
Douglas Gregor17a7c122009-06-24 00:54:41 +00002862 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00002863 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00002864 }
Mike Stump11289f42009-09-09 15:08:12 +00002865
Douglas Gregor17a7c122009-06-24 00:54:41 +00002866 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002867
2868 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002869 move(TemplateParameterLists),
2870 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002871 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00002872 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00002873 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002874 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00002875 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2876 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002877 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00002878}
2879
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002880/// \brief Perform semantic analysis for the given function template
2881/// specialization.
2882///
2883/// This routine performs all of the semantic analysis required for an
2884/// explicit function template specialization. On successful completion,
2885/// the function declaration \p FD will become a function template
2886/// specialization.
2887///
2888/// \param FD the function declaration, which will be updated to become a
2889/// function template specialization.
2890///
2891/// \param HasExplicitTemplateArgs whether any template arguments were
2892/// explicitly provided.
2893///
2894/// \param LAngleLoc the location of the left angle bracket ('<'), if
2895/// template arguments were explicitly provided.
2896///
2897/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
2898/// if any.
2899///
2900/// \param NumExplicitTemplateArgs the number of explicitly-provided template
2901/// arguments. This number may be zero even when HasExplicitTemplateArgs is
2902/// true as in, e.g., \c void sort<>(char*, char*);
2903///
2904/// \param RAngleLoc the location of the right angle bracket ('>'), if
2905/// template arguments were explicitly provided.
2906///
2907/// \param PrevDecl the set of declarations that
2908bool
2909Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
2910 bool HasExplicitTemplateArgs,
2911 SourceLocation LAngleLoc,
2912 const TemplateArgument *ExplicitTemplateArgs,
2913 unsigned NumExplicitTemplateArgs,
2914 SourceLocation RAngleLoc,
2915 NamedDecl *&PrevDecl) {
2916 // The set of function template specializations that could match this
2917 // explicit function template specialization.
2918 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
2919 CandidateSet Candidates;
2920
2921 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
2922 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2923 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
2924 // Only consider templates found within the same semantic lookup scope as
2925 // FD.
2926 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
2927 continue;
2928
2929 // C++ [temp.expl.spec]p11:
2930 // A trailing template-argument can be left unspecified in the
2931 // template-id naming an explicit function template specialization
2932 // provided it can be deduced from the function argument type.
2933 // Perform template argument deduction to determine whether we may be
2934 // specializing this template.
2935 // FIXME: It is somewhat wasteful to build
2936 TemplateDeductionInfo Info(Context);
2937 FunctionDecl *Specialization = 0;
2938 if (TemplateDeductionResult TDK
2939 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
2940 ExplicitTemplateArgs,
2941 NumExplicitTemplateArgs,
2942 FD->getType(),
2943 Specialization,
2944 Info)) {
2945 // FIXME: Template argument deduction failed; record why it failed, so
2946 // that we can provide nifty diagnostics.
2947 (void)TDK;
2948 continue;
2949 }
2950
2951 // Record this candidate.
2952 Candidates.push_back(Specialization);
2953 }
2954 }
2955
Douglas Gregor5de279c2009-09-26 03:41:46 +00002956 // Find the most specialized function template.
2957 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
2958 Candidates.size(),
2959 TPOC_Other,
2960 FD->getLocation(),
2961 PartialDiagnostic(diag::err_function_template_spec_no_match)
2962 << FD->getDeclName(),
2963 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
2964 << FD->getDeclName() << HasExplicitTemplateArgs,
2965 PartialDiagnostic(diag::note_function_template_spec_matched));
2966 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002967 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002968
2969 // FIXME: Check if the prior specialization has a point of instantiation.
2970 // If so, we have run afoul of C++ [temp.expl.spec]p6.
2971
2972 // Mark the prior declaration as an explicit specialization, so that later
2973 // clients know that this is an explicit specialization.
2974 // FIXME: Check for prior explicit instantiations?
2975 Specialization->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
2976
2977 // Turn the given function declaration into a function template
2978 // specialization, with the template arguments from the previous
2979 // specialization.
2980 FD->setFunctionTemplateSpecialization(Context,
2981 Specialization->getPrimaryTemplate(),
2982 new (Context) TemplateArgumentList(
2983 *Specialization->getTemplateSpecializationArgs()),
2984 /*InsertPos=*/0,
2985 TSK_ExplicitSpecialization);
2986
2987 // The "previous declaration" for this function template specialization is
2988 // the prior function template specialization.
2989 PrevDecl = Specialization;
2990 return false;
2991}
2992
Douglas Gregor2ec748c2009-05-14 00:28:11 +00002993// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00002994// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00002995Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00002996Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00002997 SourceLocation ExternLoc,
2998 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002999 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003000 SourceLocation KWLoc,
3001 const CXXScopeSpec &SS,
3002 TemplateTy TemplateD,
3003 SourceLocation TemplateNameLoc,
3004 SourceLocation LAngleLoc,
3005 ASTTemplateArgsPtr TemplateArgsIn,
3006 SourceLocation *TemplateArgLocs,
3007 SourceLocation RAngleLoc,
3008 AttributeList *Attr) {
3009 // Find the class template we're specializing
3010 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003011 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003012 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3013
3014 // Check that the specialization uses the same tag kind as the
3015 // original template.
3016 TagDecl::TagKind Kind;
3017 switch (TagSpec) {
3018 default: assert(0 && "Unknown tag type!");
3019 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3020 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3021 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3022 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003023 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003024 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003025 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003026 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003027 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003028 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003029 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003030 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003031 diag::note_previous_use);
3032 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3033 }
3034
Douglas Gregorf61eca92009-05-13 18:28:20 +00003035 // C++0x [temp.explicit]p2:
3036 // [...] An explicit instantiation shall appear in an enclosing
3037 // namespace of its template. [...]
3038 //
3039 // This is C++ DR 275.
3040 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
Mike Stump11289f42009-09-09 15:08:12 +00003041 TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003042 SS.getRange(),
Douglas Gregor30b01972009-06-12 22:21:45 +00003043 /*PartialSpecialization=*/false,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003044 /*ExplicitInstantiation=*/true))
3045 return true;
3046
Douglas Gregora1f49972009-05-13 00:25:59 +00003047 // Translate the parser's template argument list in our AST format.
3048 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3049 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3050
3051 // Check that the template argument list is well-formed for this
3052 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003053 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3054 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003055 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003056 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003057 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003058 return true;
3059
Mike Stump11289f42009-09-09 15:08:12 +00003060 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003061 ClassTemplate->getTemplateParameters()->size()) &&
3062 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003063
Douglas Gregora1f49972009-05-13 00:25:59 +00003064 // Find the class template specialization declaration that
3065 // corresponds to these arguments.
3066 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003067 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003068 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003069 Converted.flatSize(),
3070 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003071 void *InsertPos = 0;
3072 ClassTemplateSpecializationDecl *PrevDecl
3073 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3074
3075 ClassTemplateSpecializationDecl *Specialization = 0;
3076
Douglas Gregorf61eca92009-05-13 18:28:20 +00003077 bool SpecializationRequiresInstantiation = true;
Douglas Gregora1f49972009-05-13 00:25:59 +00003078 if (PrevDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003079 if (PrevDecl->getSpecializationKind()
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003080 == TSK_ExplicitInstantiationDefinition) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003081 // This particular specialization has already been declared or
3082 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorf61eca92009-05-13 18:28:20 +00003083 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
3084 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003085 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003086 diag::note_previous_explicit_instantiation);
Douglas Gregora1f49972009-05-13 00:25:59 +00003087 return DeclPtrTy::make(PrevDecl);
3088 }
3089
Douglas Gregorf61eca92009-05-13 18:28:20 +00003090 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003091 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorf61eca92009-05-13 18:28:20 +00003092 // For a given set of template parameters, if an explicit
3093 // instantiation of a template appears after a declaration of
3094 // an explicit specialization for that template, the explicit
3095 // instantiation has no effect.
3096 if (!getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00003097 Diag(TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003098 diag::ext_explicit_instantiation_after_specialization)
3099 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003100 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003101 diag::note_previous_template_specialization);
3102 }
3103
3104 // Create a new class template specialization declaration node
3105 // for this explicit specialization. This node is only used to
3106 // record the existence of this explicit instantiation for
3107 // accurate reproduction of the source code; we don't actually
3108 // use it for anything, since it is semantically irrelevant.
3109 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003110 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003111 ClassTemplate->getDeclContext(),
3112 TemplateNameLoc,
3113 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003114 Converted, 0);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003115 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003116 CurContext->addDecl(Specialization);
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003117 return DeclPtrTy::make(PrevDecl);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003118 }
3119
3120 // If we have already (implicitly) instantiated this
3121 // specialization, there is less work to do.
3122 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
3123 SpecializationRequiresInstantiation = false;
3124
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003125 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3126 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3127 // Since the only prior class template specialization with these
3128 // arguments was referenced but not declared, reuse that
3129 // declaration node as our own, updating its source location to
3130 // reflect our new declaration.
3131 Specialization = PrevDecl;
3132 Specialization->setLocation(TemplateNameLoc);
3133 PrevDecl = 0;
3134 }
3135 }
3136
3137 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003138 // Create a new class template specialization declaration node for
3139 // this explicit specialization.
3140 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003141 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003142 ClassTemplate->getDeclContext(),
3143 TemplateNameLoc,
3144 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003145 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003146
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003147 if (PrevDecl) {
3148 // Remove the previous declaration from the folding set, since we want
3149 // to introduce a new declaration.
3150 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3151 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3152 }
3153
3154 // Insert the new specialization.
3155 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003156 }
3157
3158 // Build the fully-sugared type for this explicit instantiation as
3159 // the user wrote in the explicit instantiation itself. This means
3160 // that we'll pretty-print the type retrieved from the
3161 // specialization's declaration the way that the user actually wrote
3162 // the explicit instantiation, rather than formatting the name based
3163 // on the "canonical" representation used to store the template
3164 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003165 QualType WrittenTy
3166 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003167 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003168 TemplateArgs.size(),
3169 Context.getTypeDeclType(Specialization));
3170 Specialization->setTypeAsWritten(WrittenTy);
3171 TemplateArgsIn.release();
3172
3173 // Add the explicit instantiation into its lexical context. However,
3174 // since explicit instantiations are never found by name lookup, we
3175 // just put it into the declaration context directly.
3176 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003177 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003178
John McCall1806c272009-09-11 07:25:08 +00003179 Specialization->setPointOfInstantiation(TemplateNameLoc);
3180
Douglas Gregora1f49972009-05-13 00:25:59 +00003181 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003182 // A definition of a class template or class member template
3183 // shall be in scope at the point of the explicit instantiation of
3184 // the class template or class member template.
3185 //
3186 // This check comes when we actually try to perform the
3187 // instantiation.
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003188 TemplateSpecializationKind TSK
Mike Stump11289f42009-09-09 15:08:12 +00003189 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003190 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor67da0d92009-05-15 17:59:04 +00003191 if (SpecializationRequiresInstantiation)
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003192 InstantiateClassTemplateSpecialization(Specialization, TSK);
Douglas Gregor85673582009-05-18 17:01:57 +00003193 else // Instantiate the members of this class template specialization.
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003194 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization,
3195 TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003196
3197 return DeclPtrTy::make(Specialization);
3198}
3199
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003200// Explicit instantiation of a member class of a class template.
3201Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003202Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003203 SourceLocation ExternLoc,
3204 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003205 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003206 SourceLocation KWLoc,
3207 const CXXScopeSpec &SS,
3208 IdentifierInfo *Name,
3209 SourceLocation NameLoc,
3210 AttributeList *Attr) {
3211
Douglas Gregord6ab8742009-05-28 23:31:59 +00003212 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003213 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00003214 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00003215 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00003216 MultiTemplateParamsArg(*this, 0, 0),
3217 Owned, IsDependent);
3218 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3219
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003220 if (!TagD)
3221 return true;
3222
3223 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3224 if (Tag->isEnum()) {
3225 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3226 << Context.getTypeDeclType(Tag);
3227 return true;
3228 }
3229
Douglas Gregorb8006faf2009-05-27 17:30:49 +00003230 if (Tag->isInvalidDecl())
3231 return true;
3232
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003233 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3234 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3235 if (!Pattern) {
3236 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3237 << Context.getTypeDeclType(Record);
3238 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3239 return true;
3240 }
3241
3242 // C++0x [temp.explicit]p2:
3243 // [...] An explicit instantiation shall appear in an enclosing
3244 // namespace of its template. [...]
3245 //
3246 // This is C++ DR 275.
3247 if (getLangOptions().CPlusPlus0x) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003248 // FIXME: In C++98, we would like to turn these errors into warnings,
3249 // dependent on a -Wc++0x flag.
Mike Stump11289f42009-09-09 15:08:12 +00003250 DeclContext *PatternContext
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003251 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
3252 if (!CurContext->Encloses(PatternContext)) {
3253 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
3254 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
3255 Diag(Pattern->getLocation(), diag::note_previous_declaration);
3256 }
3257 }
3258
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003259 TemplateSpecializationKind TSK
Mike Stump11289f42009-09-09 15:08:12 +00003260 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003261 : TSK_ExplicitInstantiationDeclaration;
Mike Stump11289f42009-09-09 15:08:12 +00003262
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003263 if (!Record->getDefinition(Context)) {
3264 // If the class has a definition, instantiate it (and all of its
3265 // members, recursively).
3266 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
Mike Stump11289f42009-09-09 15:08:12 +00003267 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregorb4850462009-05-14 23:26:13 +00003268 getTemplateInstantiationArgs(Record),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003269 TSK))
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003270 return true;
John McCall76d824f2009-08-25 22:02:44 +00003271 } else // Instantiate all of the members of the class.
Mike Stump11289f42009-09-09 15:08:12 +00003272 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003273 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003274
Mike Stump87c57ac2009-05-16 07:39:55 +00003275 // FIXME: We don't have any representation for explicit instantiations of
3276 // member classes. Such a representation is not needed for compilation, but it
3277 // should be available for clients that want to see all of the declarations in
3278 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003279 return TagD;
3280}
3281
Douglas Gregor450f00842009-09-25 18:43:00 +00003282Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
3283 SourceLocation ExternLoc,
3284 SourceLocation TemplateLoc,
3285 Declarator &D) {
3286 // Explicit instantiations always require a name.
3287 DeclarationName Name = GetNameForDeclarator(D);
3288 if (!Name) {
3289 if (!D.isInvalidType())
3290 Diag(D.getDeclSpec().getSourceRange().getBegin(),
3291 diag::err_explicit_instantiation_requires_name)
3292 << D.getDeclSpec().getSourceRange()
3293 << D.getSourceRange();
3294
3295 return true;
3296 }
3297
3298 // The scope passed in may not be a decl scope. Zip up the scope tree until
3299 // we find one that is.
3300 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3301 (S->getFlags() & Scope::TemplateParamScope) != 0)
3302 S = S->getParent();
3303
3304 // Determine the type of the declaration.
3305 QualType R = GetTypeForDeclarator(D, S, 0);
3306 if (R.isNull())
3307 return true;
3308
3309 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3310 // Cannot explicitly instantiate a typedef.
3311 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
3312 << Name;
3313 return true;
3314 }
3315
3316 // Determine what kind of explicit instantiation we have.
3317 TemplateSpecializationKind TSK
3318 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3319 : TSK_ExplicitInstantiationDeclaration;
3320
3321 LookupResult Previous = LookupParsedName(S, &D.getCXXScopeSpec(),
3322 Name, LookupOrdinaryName);
3323
3324 if (!R->isFunctionType()) {
3325 // C++ [temp.explicit]p1:
3326 // A [...] static data member of a class template can be explicitly
3327 // instantiated from the member definition associated with its class
3328 // template.
3329 if (Previous.isAmbiguous()) {
3330 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
3331 D.getSourceRange());
3332 }
3333
3334 VarDecl *Prev = dyn_cast_or_null<VarDecl>(Previous.getAsDecl());
3335 if (!Prev || !Prev->isStaticDataMember()) {
3336 // We expect to see a data data member here.
3337 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
3338 << Name;
3339 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3340 P != PEnd; ++P)
3341 Diag(P->getLocation(), diag::note_explicit_instantiation_here);
3342 return true;
3343 }
3344
3345 if (!Prev->getInstantiatedFromStaticDataMember()) {
3346 // FIXME: Check for explicit specialization?
3347 Diag(D.getIdentifierLoc(),
3348 diag::err_explicit_instantiation_data_member_not_instantiated)
3349 << Prev;
3350 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
3351 // FIXME: Can we provide a note showing where this was declared?
3352 return true;
3353 }
3354
3355 // Instantiate static data member.
3356 // FIXME: Note that this is an explicit instantiation.
3357 if (TSK == TSK_ExplicitInstantiationDefinition)
3358 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false);
3359
3360 // FIXME: Create an ExplicitInstantiation node?
3361 return DeclPtrTy();
3362 }
3363
Douglas Gregor0e876e02009-09-25 23:53:26 +00003364 // If the declarator is a template-id, translate the parser's template
3365 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00003366 bool HasExplicitTemplateArgs = false;
3367 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3368 if (D.getKind() == Declarator::DK_TemplateId) {
3369 TemplateIdAnnotation *TemplateId = D.getTemplateId();
3370 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3371 TemplateId->getTemplateArgs(),
3372 TemplateId->getTemplateArgIsType(),
3373 TemplateId->NumArgs);
3374 translateTemplateArguments(TemplateArgsPtr,
3375 TemplateId->getTemplateArgLocations(),
3376 TemplateArgs);
3377 HasExplicitTemplateArgs = true;
3378 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00003379
Douglas Gregor450f00842009-09-25 18:43:00 +00003380 // C++ [temp.explicit]p1:
3381 // A [...] function [...] can be explicitly instantiated from its template.
3382 // A member function [...] of a class template can be explicitly
3383 // instantiated from the member definition associated with its class
3384 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00003385 llvm::SmallVector<FunctionDecl *, 8> Matches;
3386 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3387 P != PEnd; ++P) {
3388 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00003389 if (!HasExplicitTemplateArgs) {
3390 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
3391 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
3392 Matches.clear();
3393 Matches.push_back(Method);
3394 break;
3395 }
Douglas Gregor450f00842009-09-25 18:43:00 +00003396 }
3397 }
3398
3399 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
3400 if (!FunTmpl)
3401 continue;
3402
3403 TemplateDeductionInfo Info(Context);
3404 FunctionDecl *Specialization = 0;
3405 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00003406 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3407 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00003408 R, Specialization, Info)) {
3409 // FIXME: Keep track of almost-matches?
3410 (void)TDK;
3411 continue;
3412 }
3413
3414 Matches.push_back(Specialization);
3415 }
3416
3417 // Find the most specialized function template specialization.
3418 FunctionDecl *Specialization
3419 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
3420 D.getIdentifierLoc(),
3421 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
3422 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
3423 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
3424
3425 if (!Specialization)
3426 return true;
3427
3428 switch (Specialization->getTemplateSpecializationKind()) {
3429 case TSK_Undeclared:
3430 Diag(D.getIdentifierLoc(),
3431 diag::err_explicit_instantiation_member_function_not_instantiated)
3432 << Specialization
3433 << (Specialization->getTemplateSpecializationKind() ==
3434 TSK_ExplicitSpecialization);
3435 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
3436 return true;
3437
3438 case TSK_ExplicitSpecialization:
3439 // C++ [temp.explicit]p4:
3440 // For a given set of template parameters, if an explicit instantiation
3441 // of a template appears after a declaration of an explicit
3442 // specialization for that template, the explicit instantiation has no
3443 // effect.
3444 break;
3445
3446 case TSK_ExplicitInstantiationDefinition:
3447 // FIXME: Check that we aren't trying to perform an explicit instantiation
3448 // declaration now.
3449 // Fall through
3450
3451 case TSK_ImplicitInstantiation:
3452 case TSK_ExplicitInstantiationDeclaration:
3453 // Instantiate the function, if this is an explicit instantiation
3454 // definition.
3455 if (TSK == TSK_ExplicitInstantiationDefinition)
3456 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
3457 false);
3458
3459 // FIXME: setTemplateSpecializationKind doesn't (yet) work for
3460 // non-templated member functions.
3461 if (!Specialization->getPrimaryTemplate())
3462 break;
3463
3464 Specialization->setTemplateSpecializationKind(TSK);
3465 break;
3466 }
3467
3468 // FIXME: Create some kind of ExplicitInstantiationDecl here.
3469 return DeclPtrTy();
3470}
3471
Douglas Gregor333489b2009-03-27 23:10:48 +00003472Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00003473Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3474 const CXXScopeSpec &SS, IdentifierInfo *Name,
3475 SourceLocation TagLoc, SourceLocation NameLoc) {
3476 // This has to hold, because SS is expected to be defined.
3477 assert(Name && "Expected a name in a dependent tag");
3478
3479 NestedNameSpecifier *NNS
3480 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3481 if (!NNS)
3482 return true;
3483
3484 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
3485 if (T.isNull())
3486 return true;
3487
3488 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
3489 QualType ElabType = Context.getElaboratedType(T, TagKind);
3490
3491 return ElabType.getAsOpaquePtr();
3492}
3493
3494Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00003495Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3496 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00003497 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00003498 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3499 if (!NNS)
3500 return true;
3501
3502 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003503 if (T.isNull())
3504 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00003505 return T.getAsOpaquePtr();
3506}
3507
Douglas Gregordce2b622009-04-01 00:28:59 +00003508Sema::TypeResult
3509Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3510 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003511 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003512 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00003513 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00003514 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00003515 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00003516 assert(TemplateId && "Expected a template specialization type");
3517
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003518 if (computeDeclContext(SS, false)) {
3519 // If we can compute a declaration context, then the "typename"
3520 // keyword was superfluous. Just build a QualifiedNameType to keep
3521 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00003522
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003523 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
3524 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
3525 }
Mike Stump11289f42009-09-09 15:08:12 +00003526
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003527 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00003528}
3529
Douglas Gregor333489b2009-03-27 23:10:48 +00003530/// \brief Build the type that describes a C++ typename specifier,
3531/// e.g., "typename T::type".
3532QualType
3533Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
3534 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003535 CXXRecordDecl *CurrentInstantiation = 0;
3536 if (NNS->isDependent()) {
3537 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00003538
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003539 // If the nested-name-specifier does not refer to the current
3540 // instantiation, then build a typename type.
3541 if (!CurrentInstantiation)
3542 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00003543
Douglas Gregorc707da62009-09-02 13:12:51 +00003544 // The nested-name-specifier refers to the current instantiation, so the
3545 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00003546 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00003547 // extraneous "typename" keywords, and we retroactively apply this DR to
3548 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003549 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003550
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003551 DeclContext *Ctx = 0;
3552
3553 if (CurrentInstantiation)
3554 Ctx = CurrentInstantiation;
3555 else {
3556 CXXScopeSpec SS;
3557 SS.setScopeRep(NNS);
3558 SS.setRange(Range);
3559 if (RequireCompleteDeclContext(SS))
3560 return QualType();
3561
3562 Ctx = computeDeclContext(SS);
3563 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003564 assert(Ctx && "No declaration context?");
3565
3566 DeclarationName Name(&II);
Mike Stump11289f42009-09-09 15:08:12 +00003567 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
Douglas Gregor333489b2009-03-27 23:10:48 +00003568 false);
3569 unsigned DiagID = 0;
3570 Decl *Referenced = 0;
3571 switch (Result.getKind()) {
3572 case LookupResult::NotFound:
3573 if (Ctx->isTranslationUnit())
3574 DiagID = diag::err_typename_nested_not_found_global;
3575 else
3576 DiagID = diag::err_typename_nested_not_found;
3577 break;
3578
3579 case LookupResult::Found:
3580 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3581 // We found a type. Build a QualifiedNameType, since the
3582 // typename-specifier was just sugar. FIXME: Tell
3583 // QualifiedNameType that it has a "typename" prefix.
3584 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3585 }
3586
3587 DiagID = diag::err_typename_nested_not_type;
3588 Referenced = Result.getAsDecl();
3589 break;
3590
3591 case LookupResult::FoundOverloaded:
3592 DiagID = diag::err_typename_nested_not_type;
3593 Referenced = *Result.begin();
3594 break;
3595
3596 case LookupResult::AmbiguousBaseSubobjectTypes:
3597 case LookupResult::AmbiguousBaseSubobjects:
3598 case LookupResult::AmbiguousReference:
3599 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3600 return QualType();
3601 }
3602
3603 // If we get here, it's because name lookup did not find a
3604 // type. Emit an appropriate diagnostic and return an error.
3605 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3606 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3607 else
3608 Diag(Range.getEnd(), DiagID) << Range << Name;
3609 if (Referenced)
3610 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3611 << Name;
3612 return QualType();
3613}
Douglas Gregor15acfb92009-08-06 16:20:37 +00003614
3615namespace {
3616 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00003617 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3618 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00003619 SourceLocation Loc;
3620 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00003621
Douglas Gregor15acfb92009-08-06 16:20:37 +00003622 public:
Mike Stump11289f42009-09-09 15:08:12 +00003623 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00003624 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003625 DeclarationName Entity)
3626 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00003627 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00003628
3629 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00003630 /// transformed.
3631 ///
3632 /// For the purposes of type reconstruction, a type has already been
3633 /// transformed if it is NULL or if it is not dependent.
3634 bool AlreadyTransformed(QualType T) {
3635 return T.isNull() || !T->isDependentType();
3636 }
Mike Stump11289f42009-09-09 15:08:12 +00003637
3638 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00003639 /// rebuilt.
3640 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00003641
Douglas Gregor15acfb92009-08-06 16:20:37 +00003642 /// \brief Returns the name of the entity whose type is being rebuilt.
3643 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00003644
Douglas Gregor15acfb92009-08-06 16:20:37 +00003645 /// \brief Transforms an expression by returning the expression itself
3646 /// (an identity function).
3647 ///
3648 /// FIXME: This is completely unsafe; we will need to actually clone the
3649 /// expressions.
3650 Sema::OwningExprResult TransformExpr(Expr *E) {
3651 return getSema().Owned(E);
3652 }
Mike Stump11289f42009-09-09 15:08:12 +00003653
Douglas Gregor15acfb92009-08-06 16:20:37 +00003654 /// \brief Transforms a typename type by determining whether the type now
3655 /// refers to a member of the current instantiation, and then
3656 /// type-checking and building a QualifiedNameType (when possible).
3657 QualType TransformTypenameType(const TypenameType *T);
3658 };
3659}
3660
Mike Stump11289f42009-09-09 15:08:12 +00003661QualType
Douglas Gregor15acfb92009-08-06 16:20:37 +00003662CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3663 NestedNameSpecifier *NNS
3664 = TransformNestedNameSpecifier(T->getQualifier(),
3665 /*FIXME:*/SourceRange(getBaseLocation()));
3666 if (!NNS)
3667 return QualType();
3668
3669 // If the nested-name-specifier did not change, and we cannot compute the
3670 // context corresponding to the nested-name-specifier, then this
3671 // typename type will not change; exit early.
3672 CXXScopeSpec SS;
3673 SS.setRange(SourceRange(getBaseLocation()));
3674 SS.setScopeRep(NNS);
3675 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3676 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003677
3678 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00003679 // QualifiedNameType.
3680 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00003681 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00003682 = TransformType(QualType(TemplateId, 0));
3683 if (NewTemplateId.isNull())
3684 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003685
Douglas Gregor15acfb92009-08-06 16:20:37 +00003686 if (NNS == T->getQualifier() &&
3687 NewTemplateId == QualType(TemplateId, 0))
3688 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003689
Douglas Gregor15acfb92009-08-06 16:20:37 +00003690 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3691 }
Mike Stump11289f42009-09-09 15:08:12 +00003692
Douglas Gregor15acfb92009-08-06 16:20:37 +00003693 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3694}
3695
3696/// \brief Rebuilds a type within the context of the current instantiation.
3697///
Mike Stump11289f42009-09-09 15:08:12 +00003698/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00003699/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00003700/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00003701/// partial specialization thereof). This routine will rebuild that type now
3702/// that we have entered the declarator's scope, which may produce different
3703/// canonical types, e.g.,
3704///
3705/// \code
3706/// template<typename T>
3707/// struct X {
3708/// typedef T* pointer;
3709/// pointer data();
3710/// };
3711///
3712/// template<typename T>
3713/// typename X<T>::pointer X<T>::data() { ... }
3714/// \endcode
3715///
3716/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3717/// since we do not know that we can look into X<T> when we parsed the type.
3718/// This function will rebuild the type, performing the lookup of "pointer"
3719/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3720/// as the canonical type of T*, allowing the return types of the out-of-line
3721/// definition and the declaration to match.
3722QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3723 DeclarationName Name) {
3724 if (T.isNull() || !T->isDependentType())
3725 return T;
Mike Stump11289f42009-09-09 15:08:12 +00003726
Douglas Gregor15acfb92009-08-06 16:20:37 +00003727 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3728 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00003729}
Douglas Gregorbe999392009-09-15 16:23:51 +00003730
3731/// \brief Produces a formatted string that describes the binding of
3732/// template parameters to template arguments.
3733std::string
3734Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3735 const TemplateArgumentList &Args) {
3736 std::string Result;
3737
3738 if (!Params || Params->size() == 0)
3739 return Result;
3740
3741 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3742 if (I == 0)
3743 Result += "[with ";
3744 else
3745 Result += ", ";
3746
3747 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
3748 Result += Id->getName();
3749 } else {
3750 Result += '$';
3751 Result += llvm::utostr(I);
3752 }
3753
3754 Result += " = ";
3755
3756 switch (Args[I].getKind()) {
3757 case TemplateArgument::Null:
3758 Result += "<no value>";
3759 break;
3760
3761 case TemplateArgument::Type: {
3762 std::string TypeStr;
3763 Args[I].getAsType().getAsStringInternal(TypeStr,
3764 Context.PrintingPolicy);
3765 Result += TypeStr;
3766 break;
3767 }
3768
3769 case TemplateArgument::Declaration: {
3770 bool Unnamed = true;
3771 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
3772 if (ND->getDeclName()) {
3773 Unnamed = false;
3774 Result += ND->getNameAsString();
3775 }
3776 }
3777
3778 if (Unnamed) {
3779 Result += "<anonymous>";
3780 }
3781 break;
3782 }
3783
3784 case TemplateArgument::Integral: {
3785 Result += Args[I].getAsIntegral()->toString(10);
3786 break;
3787 }
3788
3789 case TemplateArgument::Expression: {
3790 assert(false && "No expressions in deduced template arguments!");
3791 Result += "<expression>";
3792 break;
3793 }
3794
3795 case TemplateArgument::Pack:
3796 // FIXME: Format template argument packs
3797 Result += "<template argument pack>";
3798 break;
3799 }
3800 }
3801
3802 Result += ']';
3803 return Result;
3804}