blob: 27e8edd96229dddfbeed047cd4b676ddbe1a6e7b [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.
Mike Stump11289f42009-09-09 15:08:12 +00001040static void
1041translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001042 SourceLocation *TemplateArgLocs,
1043 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
1044 TemplateArgs.reserve(TemplateArgsIn.size());
1045
1046 void **Args = TemplateArgsIn.getArgs();
1047 bool *ArgIsType = TemplateArgsIn.getArgIsType();
1048 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
1049 TemplateArgs.push_back(
1050 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001051 //FIXME: Preserve type source info.
1052 Sema::GetTypeFromParser(Args[Arg]))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001053 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
1054 }
1055}
1056
Douglas Gregordc572a32009-03-30 22:58:21 +00001057QualType Sema::CheckTemplateIdType(TemplateName Name,
1058 SourceLocation TemplateLoc,
1059 SourceLocation LAngleLoc,
1060 const TemplateArgument *TemplateArgs,
1061 unsigned NumTemplateArgs,
1062 SourceLocation RAngleLoc) {
1063 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001064 if (!Template) {
1065 // The template name does not resolve to a template, so we just
1066 // build a dependent template-id type.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001067 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001068 NumTemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001069 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001070
Douglas Gregorc40290e2009-03-09 23:48:35 +00001071 // Check that the template argument list is well-formed for this
1072 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001073 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1074 NumTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001075 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001076 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001077 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001078 return QualType();
1079
Mike Stump11289f42009-09-09 15:08:12 +00001080 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001081 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001082 "Converted template argument list is too short!");
1083
1084 QualType CanonType;
1085
Douglas Gregordc572a32009-03-30 22:58:21 +00001086 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorc40290e2009-03-09 23:48:35 +00001087 TemplateArgs,
1088 NumTemplateArgs)) {
1089 // This class template specialization is a dependent
1090 // type. Therefore, its canonical type is another class template
1091 // specialization type that contains all of the converted
1092 // arguments in canonical form. This ensures that, e.g., A<T> and
1093 // A<T, T> have identical types when A is declared as:
1094 //
1095 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001096 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001097 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001098 Converted.getFlatArguments(),
1099 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001100
Douglas Gregora8e02e72009-07-28 23:00:59 +00001101 // FIXME: CanonType is not actually the canonical type, and unfortunately
1102 // it is a TemplateTypeSpecializationType that we will never use again.
1103 // In the future, we need to teach getTemplateSpecializationType to only
1104 // build the canonical type and return that to us.
1105 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001106 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001107 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001108 // Find the class template specialization declaration that
1109 // corresponds to these arguments.
1110 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001111 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001112 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001113 Converted.flatSize(),
1114 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001115 void *InsertPos = 0;
1116 ClassTemplateSpecializationDecl *Decl
1117 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1118 if (!Decl) {
1119 // This is the first time we have referenced this class template
1120 // specialization. Create the canonical declaration and add it to
1121 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001122 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001123 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001124 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001125 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001126 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001127 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1128 Decl->setLexicalDeclContext(CurContext);
1129 }
1130
1131 CanonType = Context.getTypeDeclType(Decl);
1132 }
Mike Stump11289f42009-09-09 15:08:12 +00001133
Douglas Gregorc40290e2009-03-09 23:48:35 +00001134 // Build the fully-sugared type for this class template
1135 // specialization, which refers back to the class template
1136 // specialization we created or found.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001137 //FIXME: Preserve type source info.
Douglas Gregordc572a32009-03-30 22:58:21 +00001138 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1139 NumTemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001140}
1141
Douglas Gregor67a65642009-02-17 23:15:12 +00001142Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001143Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001144 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001145 ASTTemplateArgsPtr TemplateArgsIn,
1146 SourceLocation *TemplateArgLocs,
John McCalld8fe9af2009-09-08 17:47:29 +00001147 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001148 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001149
Douglas Gregorc40290e2009-03-09 23:48:35 +00001150 // Translate the parser's template argument list in our AST format.
1151 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1152 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001153
Douglas Gregordc572a32009-03-30 22:58:21 +00001154 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +00001155 TemplateArgs.data(),
1156 TemplateArgs.size(),
Douglas Gregordc572a32009-03-30 22:58:21 +00001157 RAngleLoc);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001158 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001159
1160 if (Result.isNull())
1161 return true;
1162
John McCalld8fe9af2009-09-08 17:47:29 +00001163 return Result.getAsOpaquePtr();
1164}
John McCall06f6fe8d2009-09-04 01:14:41 +00001165
John McCalld8fe9af2009-09-08 17:47:29 +00001166Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1167 TagUseKind TUK,
1168 DeclSpec::TST TagSpec,
1169 SourceLocation TagLoc) {
1170 if (TypeResult.isInvalid())
1171 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001172
John McCalld8fe9af2009-09-08 17:47:29 +00001173 QualType Type = QualType::getFromOpaquePtr(TypeResult.get());
John McCall06f6fe8d2009-09-04 01:14:41 +00001174
John McCalld8fe9af2009-09-08 17:47:29 +00001175 // Verify the tag specifier.
1176 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001177
John McCalld8fe9af2009-09-08 17:47:29 +00001178 if (const RecordType *RT = Type->getAs<RecordType>()) {
1179 RecordDecl *D = RT->getDecl();
1180
1181 IdentifierInfo *Id = D->getIdentifier();
1182 assert(Id && "templated class must have an identifier");
1183
1184 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1185 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001186 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001187 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1188 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001189 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001190 }
1191 }
1192
John McCalld8fe9af2009-09-08 17:47:29 +00001193 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1194
1195 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001196}
1197
Douglas Gregora727cb92009-06-30 22:34:41 +00001198Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1199 SourceLocation TemplateNameLoc,
1200 SourceLocation LAngleLoc,
1201 const TemplateArgument *TemplateArgs,
1202 unsigned NumTemplateArgs,
1203 SourceLocation RAngleLoc) {
1204 // FIXME: Can we do any checking at this point? I guess we could check the
1205 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001206 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001207 // though.
Mike Stump11289f42009-09-09 15:08:12 +00001208 return Owned(TemplateIdRefExpr::Create(Context,
Douglas Gregora727cb92009-06-30 22:34:41 +00001209 /*FIXME: New type?*/Context.OverloadTy,
1210 /*FIXME: Necessary?*/0,
1211 /*FIXME: Necessary?*/SourceRange(),
1212 Template, TemplateNameLoc, LAngleLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001213 TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001214 NumTemplateArgs, RAngleLoc));
1215}
1216
1217Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1218 SourceLocation TemplateNameLoc,
1219 SourceLocation LAngleLoc,
1220 ASTTemplateArgsPtr TemplateArgsIn,
1221 SourceLocation *TemplateArgLocs,
1222 SourceLocation RAngleLoc) {
1223 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001224
Douglas Gregora727cb92009-06-30 22:34:41 +00001225 // Translate the parser's template argument list in our AST format.
1226 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1227 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001228 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001229
Douglas Gregora727cb92009-06-30 22:34:41 +00001230 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1231 TemplateArgs.data(), TemplateArgs.size(),
1232 RAngleLoc);
1233}
1234
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001235Sema::OwningExprResult
1236Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base,
1237 SourceLocation OpLoc,
1238 tok::TokenKind OpKind,
1239 const CXXScopeSpec &SS,
1240 TemplateTy TemplateD,
1241 SourceLocation TemplateNameLoc,
1242 SourceLocation LAngleLoc,
1243 ASTTemplateArgsPtr TemplateArgsIn,
1244 SourceLocation *TemplateArgLocs,
1245 SourceLocation RAngleLoc) {
1246 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001247
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001248 // FIXME: We're going to end up looking up the template based on its name,
1249 // twice!
1250 DeclarationName Name;
1251 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
1252 Name = ActualTemplate->getDeclName();
1253 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
1254 Name = Ovl->getDeclName();
1255 else
Douglas Gregor308047d2009-09-09 00:23:06 +00001256 Name = Template.getAsDependentTemplateName()->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001257
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001258 // Translate the parser's template argument list in our AST format.
1259 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1260 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1261 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001262
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001263 // Do we have the save the actual template name? We might need it...
1264 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc,
1265 Name, true, LAngleLoc,
1266 TemplateArgs.data(), TemplateArgs.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001267 RAngleLoc, DeclPtrTy(), &SS);
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001268}
1269
Douglas Gregorb67535d2009-03-31 00:43:58 +00001270/// \brief Form a dependent template name.
1271///
1272/// This action forms a dependent template name given the template
1273/// name and its (presumably dependent) scope specifier. For
1274/// example, given "MetaFun::template apply", the scope specifier \p
1275/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1276/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001277Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001278Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1279 const IdentifierInfo &Name,
1280 SourceLocation NameLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001281 const CXXScopeSpec &SS,
1282 TypeTy *ObjectType) {
Mike Stump11289f42009-09-09 15:08:12 +00001283 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001284 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1285 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001286 // C++0x [temp.names]p5:
1287 // If a name prefixed by the keyword template is not the name of
1288 // a template, the program is ill-formed. [Note: the keyword
1289 // template may not be applied to non-template members of class
1290 // templates. -end note ] [ Note: as is the case with the
1291 // typename prefix, the template prefix is allowed in cases
1292 // where it is not strictly necessary; i.e., when the
1293 // nested-name-specifier or the expression on the left of the ->
1294 // or . is not dependent on a template-parameter, or the use
1295 // does not appear in the scope of a template. -end note]
1296 //
1297 // Note: C++03 was more strict here, because it banned the use of
1298 // the "template" keyword prior to a template-name that was not a
1299 // dependent name. C++ DR468 relaxed this requirement (the
1300 // "template" keyword is now permitted). We follow the C++0x
1301 // rules, even in C++03 mode, retroactively applying the DR.
1302 TemplateTy Template;
Mike Stump11289f42009-09-09 15:08:12 +00001303 TemplateNameKind TNK = isTemplateName(0, Name, NameLoc, &SS, ObjectType,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001304 false, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001305 if (TNK == TNK_Non_template) {
1306 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1307 << &Name;
1308 return TemplateTy();
1309 }
1310
1311 return Template;
1312 }
1313
Mike Stump11289f42009-09-09 15:08:12 +00001314 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001315 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorb67535d2009-03-31 00:43:58 +00001316 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1317}
1318
Mike Stump11289f42009-09-09 15:08:12 +00001319bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001320 const TemplateArgument &Arg,
1321 TemplateArgumentListBuilder &Converted) {
1322 // Check template type parameter.
1323 if (Arg.getKind() != TemplateArgument::Type) {
1324 // C++ [temp.arg.type]p1:
1325 // A template-argument for a template-parameter which is a
1326 // type shall be a type-id.
1327
1328 // We have a template type parameter but the template argument
1329 // is not a type.
1330 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1331 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001332
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001333 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001334 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001335
1336 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1337 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001338
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001339 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001340 Converted.Append(
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001341 TemplateArgument(Arg.getLocation(),
1342 Context.getCanonicalType(Arg.getAsType())));
1343 return false;
1344}
1345
Douglas Gregord32e0282009-02-09 23:23:08 +00001346/// \brief Check that the given template argument list is well-formed
1347/// for specializing the given template.
1348bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1349 SourceLocation TemplateLoc,
1350 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001351 const TemplateArgument *TemplateArgs,
1352 unsigned NumTemplateArgs,
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001353 SourceLocation RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001354 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001355 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001356 TemplateParameterList *Params = Template->getTemplateParameters();
1357 unsigned NumParams = Params->size();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001358 unsigned NumArgs = NumTemplateArgs;
Douglas Gregord32e0282009-02-09 23:23:08 +00001359 bool Invalid = false;
1360
Mike Stump11289f42009-09-09 15:08:12 +00001361 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001362 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001363
Anders Carlsson15201f12009-06-13 02:08:00 +00001364 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001365 (NumArgs < Params->getMinRequiredArguments() &&
1366 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001367 // FIXME: point at either the first arg beyond what we can handle,
1368 // or the '>', depending on whether we have too many or too few
1369 // arguments.
1370 SourceRange Range;
1371 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001372 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001373 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1374 << (NumArgs > NumParams)
1375 << (isa<ClassTemplateDecl>(Template)? 0 :
1376 isa<FunctionTemplateDecl>(Template)? 1 :
1377 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1378 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001379 Diag(Template->getLocation(), diag::note_template_decl_here)
1380 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001381 Invalid = true;
1382 }
Mike Stump11289f42009-09-09 15:08:12 +00001383
1384 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001385 // [...] The type and form of each template-argument specified in
1386 // a template-id shall match the type and form specified for the
1387 // corresponding parameter declared by the template in its
1388 // template-parameter-list.
1389 unsigned ArgIdx = 0;
1390 for (TemplateParameterList::iterator Param = Params->begin(),
1391 ParamEnd = Params->end();
1392 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001393 if (ArgIdx > NumArgs && PartialTemplateArgs)
1394 break;
Mike Stump11289f42009-09-09 15:08:12 +00001395
Douglas Gregord32e0282009-02-09 23:23:08 +00001396 // Decode the template argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001397 TemplateArgument Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00001398 if (ArgIdx >= NumArgs) {
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001399 // Retrieve the default template argument from the template
1400 // parameter.
1401 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001402 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001403 // We have an empty argument pack.
1404 Converted.BeginPack();
1405 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001406 break;
1407 }
Mike Stump11289f42009-09-09 15:08:12 +00001408
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001409 if (!TTP->hasDefaultArgument())
1410 break;
1411
Douglas Gregorc40290e2009-03-09 23:48:35 +00001412 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001413
1414 // If the argument type is dependent, instantiate it now based
1415 // on the previously-computed template arguments.
Douglas Gregor79cf6032009-03-10 20:44:00 +00001416 if (ArgType->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001417 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001418 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001419 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001420 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregord002c7b2009-05-11 23:53:27 +00001421
Anders Carlssonc8e71132009-06-05 04:47:51 +00001422 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001423 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001424 ArgType = SubstType(ArgType,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001425 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001426 TTP->getDefaultArgumentLoc(),
1427 TTP->getDeclName());
Douglas Gregor79cf6032009-03-10 20:44:00 +00001428 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001429
1430 if (ArgType.isNull())
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001431 return true;
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001432
Douglas Gregorc40290e2009-03-09 23:48:35 +00001433 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001434 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001435 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1436 if (!NTTP->hasDefaultArgument())
1437 break;
1438
Mike Stump11289f42009-09-09 15:08:12 +00001439 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001440 Template, Converted.getFlatArguments(),
Anders Carlsson40ed3442009-06-11 16:06:49 +00001441 Converted.flatSize(),
1442 SourceRange(TemplateLoc, RAngleLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001443
Anders Carlsson40ed3442009-06-11 16:06:49 +00001444 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001445 /*TakeArgs=*/false);
Anders Carlsson40ed3442009-06-11 16:06:49 +00001446
Mike Stump11289f42009-09-09 15:08:12 +00001447 Sema::OwningExprResult E
1448 = SubstExpr(NTTP->getDefaultArgument(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00001449 MultiLevelTemplateArgumentList(TemplateArgs));
Anders Carlsson40ed3442009-06-11 16:06:49 +00001450 if (E.isInvalid())
1451 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001452
Anders Carlsson40ed3442009-06-11 16:06:49 +00001453 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001454 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001455 TemplateTemplateParmDecl *TempParm
1456 = cast<TemplateTemplateParmDecl>(*Param);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001457
1458 if (!TempParm->hasDefaultArgument())
1459 break;
1460
John McCall76d824f2009-08-25 22:02:44 +00001461 // FIXME: Subst default argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001462 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001463 }
1464 } else {
1465 // Retrieve the template argument produced by the user.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001466 Arg = TemplateArgs[ArgIdx];
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001467 }
1468
Douglas Gregord32e0282009-02-09 23:23:08 +00001469
1470 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001471 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001472 Converted.BeginPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001473 // Check all the remaining arguments (if any).
1474 for (; ArgIdx < NumArgs; ++ArgIdx) {
1475 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1476 Invalid = true;
1477 }
Mike Stump11289f42009-09-09 15:08:12 +00001478
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001479 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001480 } else {
1481 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1482 Invalid = true;
1483 }
Mike Stump11289f42009-09-09 15:08:12 +00001484 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord32e0282009-02-09 23:23:08 +00001485 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1486 // Check non-type template parameters.
Douglas Gregor463421d2009-03-03 04:44:36 +00001487
John McCall76d824f2009-08-25 22:02:44 +00001488 // Do substitution on the type of the non-type template parameter
1489 // with the template arguments we've seen thus far.
Douglas Gregor463421d2009-03-03 04:44:36 +00001490 QualType NTTPType = NTTP->getType();
1491 if (NTTPType->isDependentType()) {
John McCall76d824f2009-08-25 22:02:44 +00001492 // Do substitution on the type of the non-type template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001493 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001494 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001495 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001496 SourceRange(TemplateLoc, RAngleLoc));
1497
Anders Carlssonc8e71132009-06-05 04:47:51 +00001498 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001499 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001500 NTTPType = SubstType(NTTPType,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00001501 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001502 NTTP->getLocation(),
1503 NTTP->getDeclName());
Douglas Gregor463421d2009-03-03 04:44:36 +00001504 // If that worked, check the non-type template parameter type
1505 // for validity.
1506 if (!NTTPType.isNull())
Mike Stump11289f42009-09-09 15:08:12 +00001507 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
Douglas Gregor463421d2009-03-03 04:44:36 +00001508 NTTP->getLocation());
Douglas Gregor463421d2009-03-03 04:44:36 +00001509 if (NTTPType.isNull()) {
1510 Invalid = true;
1511 break;
1512 }
1513 }
1514
Douglas Gregorc40290e2009-03-09 23:48:35 +00001515 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001516 case TemplateArgument::Null:
1517 assert(false && "Should never see a NULL template argument here");
1518 break;
Mike Stump11289f42009-09-09 15:08:12 +00001519
Douglas Gregorc40290e2009-03-09 23:48:35 +00001520 case TemplateArgument::Expression: {
1521 Expr *E = Arg.getAsExpr();
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001522 TemplateArgument Result;
1523 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregord32e0282009-02-09 23:23:08 +00001524 Invalid = true;
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001525 else
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001526 Converted.Append(Result);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001527 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001528 }
1529
Douglas Gregorc40290e2009-03-09 23:48:35 +00001530 case TemplateArgument::Declaration:
1531 case TemplateArgument::Integral:
1532 // We've already checked this template argument, so just copy
1533 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001534 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001535 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001536
Douglas Gregorc40290e2009-03-09 23:48:35 +00001537 case TemplateArgument::Type:
1538 // We have a non-type template parameter but the template
1539 // argument is a type.
Mike Stump11289f42009-09-09 15:08:12 +00001540
Douglas Gregorc40290e2009-03-09 23:48:35 +00001541 // C++ [temp.arg]p2:
1542 // In a template-argument, an ambiguity between a type-id and
1543 // an expression is resolved to a type-id, regardless of the
1544 // form of the corresponding template-parameter.
1545 //
1546 // We warn specifically about this case, since it can be rather
1547 // confusing for users.
1548 if (Arg.getAsType()->isFunctionType())
1549 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1550 << Arg.getAsType();
1551 else
1552 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1553 Diag((*Param)->getLocation(), diag::note_template_param_here);
1554 Invalid = true;
Anders Carlssonbc343912009-06-15 17:04:53 +00001555 break;
Mike Stump11289f42009-09-09 15:08:12 +00001556
Anders Carlssonbc343912009-06-15 17:04:53 +00001557 case TemplateArgument::Pack:
1558 assert(0 && "FIXME: Implement!");
1559 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001560 }
Mike Stump11289f42009-09-09 15:08:12 +00001561 } else {
Douglas Gregord32e0282009-02-09 23:23:08 +00001562 // Check template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001563 TemplateTemplateParmDecl *TempParm
Douglas Gregord32e0282009-02-09 23:23:08 +00001564 = cast<TemplateTemplateParmDecl>(*Param);
Mike Stump11289f42009-09-09 15:08:12 +00001565
Douglas Gregorc40290e2009-03-09 23:48:35 +00001566 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001567 case TemplateArgument::Null:
1568 assert(false && "Should never see a NULL template argument here");
1569 break;
Mike Stump11289f42009-09-09 15:08:12 +00001570
Douglas Gregorc40290e2009-03-09 23:48:35 +00001571 case TemplateArgument::Expression: {
1572 Expr *ArgExpr = Arg.getAsExpr();
1573 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1574 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1575 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1576 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001577
Douglas Gregorc40290e2009-03-09 23:48:35 +00001578 // Add the converted template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001579 Decl *D
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00001580 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001581 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorc40290e2009-03-09 23:48:35 +00001582 continue;
1583 }
1584 }
1585 // fall through
Mike Stump11289f42009-09-09 15:08:12 +00001586
Douglas Gregorc40290e2009-03-09 23:48:35 +00001587 case TemplateArgument::Type: {
1588 // We have a template template parameter but the template
1589 // argument does not refer to a template.
1590 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1591 Invalid = true;
1592 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001593 }
1594
Douglas Gregorc40290e2009-03-09 23:48:35 +00001595 case TemplateArgument::Declaration:
1596 // We've already checked this template argument, so just copy
1597 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001598 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001599 break;
Mike Stump11289f42009-09-09 15:08:12 +00001600
Douglas Gregorc40290e2009-03-09 23:48:35 +00001601 case TemplateArgument::Integral:
1602 assert(false && "Integral argument with template template parameter");
1603 break;
Mike Stump11289f42009-09-09 15:08:12 +00001604
Anders Carlssonbc343912009-06-15 17:04:53 +00001605 case TemplateArgument::Pack:
1606 assert(0 && "FIXME: Implement!");
1607 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001608 }
Douglas Gregord32e0282009-02-09 23:23:08 +00001609 }
1610 }
1611
1612 return Invalid;
1613}
1614
1615/// \brief Check a template argument against its corresponding
1616/// template type parameter.
1617///
1618/// This routine implements the semantics of C++ [temp.arg.type]. It
1619/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001620bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
Douglas Gregord32e0282009-02-09 23:23:08 +00001621 QualType Arg, SourceLocation ArgLoc) {
1622 // C++ [temp.arg.type]p2:
1623 // A local type, a type with no linkage, an unnamed type or a type
1624 // compounded from any of these types shall not be used as a
1625 // template-argument for a template type-parameter.
1626 //
1627 // FIXME: Perform the recursive and no-linkage type checks.
1628 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001629 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001630 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001631 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001632 Tag = RecordT;
1633 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1634 return Diag(ArgLoc, diag::err_template_arg_local_type)
1635 << QualType(Tag, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001636 else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001637 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001638 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1639 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1640 return true;
1641 }
1642
1643 return false;
1644}
1645
Douglas Gregorccb07762009-02-11 19:52:55 +00001646/// \brief Checks whether the given template argument is the address
1647/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001648bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1649 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001650 bool Invalid = false;
1651
1652 // See through any implicit casts we added to fix the type.
1653 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1654 Arg = Cast->getSubExpr();
1655
Sebastian Redl576fd422009-05-10 18:38:11 +00001656 // C++0x allows nullptr, and there's no further checking to be done for that.
1657 if (Arg->getType()->isNullPtrType())
1658 return false;
1659
Douglas Gregorccb07762009-02-11 19:52:55 +00001660 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001661 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001662 // A template-argument for a non-type, non-template
1663 // template-parameter shall be one of: [...]
1664 //
1665 // -- the address of an object or function with external
1666 // linkage, including function templates and function
1667 // template-ids but excluding non-static class members,
1668 // expressed as & id-expression where the & is optional if
1669 // the name refers to a function or array, or if the
1670 // corresponding template-parameter is a reference; or
1671 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001672
Douglas Gregorccb07762009-02-11 19:52:55 +00001673 // Ignore (and complain about) any excess parentheses.
1674 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1675 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001676 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001677 diag::err_template_arg_extra_parens)
1678 << Arg->getSourceRange();
1679 Invalid = true;
1680 }
1681
1682 Arg = Parens->getSubExpr();
1683 }
1684
1685 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1686 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1687 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1688 } else
1689 DRE = dyn_cast<DeclRefExpr>(Arg);
1690
1691 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00001692 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001693 diag::err_template_arg_not_object_or_func_form)
1694 << Arg->getSourceRange();
1695
1696 // Cannot refer to non-static data members
1697 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1698 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1699 << Field << Arg->getSourceRange();
1700
1701 // Cannot refer to non-static member functions
1702 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1703 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00001704 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001705 diag::err_template_arg_method)
1706 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001707
Douglas Gregorccb07762009-02-11 19:52:55 +00001708 // Functions must have external linkage.
1709 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1710 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00001711 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001712 diag::err_template_arg_function_not_extern)
1713 << Func << Arg->getSourceRange();
1714 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1715 << true;
1716 return true;
1717 }
1718
1719 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001720 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00001721 return Invalid;
1722 }
1723
1724 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1725 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00001726 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001727 diag::err_template_arg_object_not_extern)
1728 << Var << Arg->getSourceRange();
1729 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1730 << true;
1731 return true;
1732 }
1733
1734 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001735 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00001736 return Invalid;
1737 }
Mike Stump11289f42009-09-09 15:08:12 +00001738
Douglas Gregorccb07762009-02-11 19:52:55 +00001739 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001740 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001741 diag::err_template_arg_not_object_or_func)
1742 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001743 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001744 diag::note_template_arg_refers_here);
1745 return true;
1746}
1747
1748/// \brief Checks whether the given template argument is a pointer to
1749/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump11289f42009-09-09 15:08:12 +00001750bool
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001751Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001752 bool Invalid = false;
1753
1754 // See through any implicit casts we added to fix the type.
1755 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1756 Arg = Cast->getSubExpr();
1757
Sebastian Redl576fd422009-05-10 18:38:11 +00001758 // C++0x allows nullptr, and there's no further checking to be done for that.
1759 if (Arg->getType()->isNullPtrType())
1760 return false;
1761
Douglas Gregorccb07762009-02-11 19:52:55 +00001762 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001763 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001764 // A template-argument for a non-type, non-template
1765 // template-parameter shall be one of: [...]
1766 //
1767 // -- a pointer to member expressed as described in 5.3.1.
1768 QualifiedDeclRefExpr *DRE = 0;
1769
1770 // Ignore (and complain about) any excess parentheses.
1771 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1772 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001773 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001774 diag::err_template_arg_extra_parens)
1775 << Arg->getSourceRange();
1776 Invalid = true;
1777 }
1778
1779 Arg = Parens->getSubExpr();
1780 }
1781
1782 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1783 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1784 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1785
1786 if (!DRE)
1787 return Diag(Arg->getSourceRange().getBegin(),
1788 diag::err_template_arg_not_pointer_to_member_form)
1789 << Arg->getSourceRange();
1790
1791 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1792 assert((isa<FieldDecl>(DRE->getDecl()) ||
1793 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1794 "Only non-static member pointers can make it here");
1795
1796 // Okay: this is the address of a non-static member, and therefore
1797 // a member pointer constant.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001798 Member = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00001799 return Invalid;
1800 }
1801
1802 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001803 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001804 diag::err_template_arg_not_pointer_to_member_form)
1805 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001806 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001807 diag::note_template_arg_refers_here);
1808 return true;
1809}
1810
Douglas Gregord32e0282009-02-09 23:23:08 +00001811/// \brief Check a template argument against its corresponding
1812/// non-type template parameter.
1813///
Douglas Gregor463421d2009-03-03 04:44:36 +00001814/// This routine implements the semantics of C++ [temp.arg.nontype].
1815/// It returns true if an error occurred, and false otherwise. \p
1816/// InstantiatedParamType is the type of the non-type template
1817/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001818///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001819/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00001820bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00001821 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001822 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001823 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1824
Douglas Gregor86560402009-02-10 23:36:10 +00001825 // If either the parameter has a dependent type or the argument is
1826 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001827 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00001828 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1829 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001830 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00001831 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001832 }
Douglas Gregor86560402009-02-10 23:36:10 +00001833
1834 // C++ [temp.arg.nontype]p5:
1835 // The following conversions are performed on each expression used
1836 // as a non-type template-argument. If a non-type
1837 // template-argument cannot be converted to the type of the
1838 // corresponding template-parameter then the program is
1839 // ill-formed.
1840 //
1841 // -- for a non-type template-parameter of integral or
1842 // enumeration type, integral promotions (4.5) and integral
1843 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00001844 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001845 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00001846 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00001847 // C++ [temp.arg.nontype]p1:
1848 // A template-argument for a non-type, non-template
1849 // template-parameter shall be one of:
1850 //
1851 // -- an integral constant-expression of integral or enumeration
1852 // type; or
1853 // -- the name of a non-type template-parameter; or
1854 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001855 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00001856 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001857 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001858 diag::err_template_arg_not_integral_or_enumeral)
1859 << ArgType << Arg->getSourceRange();
1860 Diag(Param->getLocation(), diag::note_template_param_here);
1861 return true;
1862 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001863 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00001864 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1865 << ArgType << Arg->getSourceRange();
1866 return true;
1867 }
1868
1869 // FIXME: We need some way to more easily get the unqualified form
1870 // of the types without going all the way to the
1871 // canonical type.
1872 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1873 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1874 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1875 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1876
1877 // Try to convert the argument to the parameter's type.
1878 if (ParamType == ArgType) {
1879 // Okay: no conversion necessary
1880 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1881 !ParamType->isEnumeralType()) {
1882 // This is an integral promotion or conversion.
1883 ImpCastExprToType(Arg, ParamType);
1884 } else {
1885 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00001886 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001887 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00001888 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00001889 Diag(Param->getLocation(), diag::note_template_param_here);
1890 return true;
1891 }
1892
Douglas Gregor52aba872009-03-14 00:20:21 +00001893 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00001894 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001895 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00001896
1897 if (!Arg->isValueDependent()) {
1898 // Check that an unsigned parameter does not receive a negative
1899 // value.
1900 if (IntegerType->isUnsignedIntegerType()
1901 && (Value.isSigned() && Value.isNegative())) {
1902 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1903 << Value.toString(10) << Param->getType()
1904 << Arg->getSourceRange();
1905 Diag(Param->getLocation(), diag::note_template_param_here);
1906 return true;
1907 }
1908
1909 // Check that we don't overflow the template parameter type.
1910 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1911 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00001912 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00001913 diag::err_template_arg_too_large)
1914 << Value.toString(10) << Param->getType()
1915 << Arg->getSourceRange();
1916 Diag(Param->getLocation(), diag::note_template_param_here);
1917 return true;
1918 }
1919
1920 if (Value.getBitWidth() != AllowedBits)
1921 Value.extOrTrunc(AllowedBits);
1922 Value.setIsSigned(IntegerType->isSignedIntegerType());
1923 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001924
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001925 // Add the value of this argument to the list of converted
1926 // arguments. We use the bitwidth and signedness of the template
1927 // parameter.
1928 if (Arg->isValueDependent()) {
1929 // The argument is value-dependent. Create a new
1930 // TemplateArgument with the converted expression.
1931 Converted = TemplateArgument(Arg);
1932 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001933 }
1934
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001935 Converted = TemplateArgument(StartLoc, Value,
Mike Stump11289f42009-09-09 15:08:12 +00001936 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001937 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00001938 return false;
1939 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001940
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001941 // Handle pointer-to-function, reference-to-function, and
1942 // pointer-to-member-function all in (roughly) the same way.
1943 if (// -- For a non-type template-parameter of type pointer to
1944 // function, only the function-to-pointer conversion (4.3) is
1945 // applied. If the template-argument represents a set of
1946 // overloaded functions (or a pointer to such), the matching
1947 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00001948 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001949 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001950 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001951 // -- For a non-type template-parameter of type reference to
1952 // function, no conversions apply. If the template-argument
1953 // represents a set of overloaded functions, the matching
1954 // function is selected from the set (13.4).
1955 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001956 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001957 // -- For a non-type template-parameter of type pointer to
1958 // member function, no conversions apply. If the
1959 // template-argument represents a set of overloaded member
1960 // functions, the matching member function is selected from
1961 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00001962 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001963 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001964 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001965 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00001966 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00001967 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001968 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00001969 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1970 ParamType->isMemberPointerType())) {
1971 ArgType = ParamType;
1972 ImpCastExprToType(Arg, ParamType);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001973 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001974 ArgType = Context.getPointerType(ArgType);
1975 ImpCastExprToType(Arg, ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001976 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001977 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00001978 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1979 return true;
1980
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001981 FixOverloadedFunctionReference(Arg, Fn);
1982 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001983 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001984 ArgType = Context.getPointerType(Arg->getType());
1985 ImpCastExprToType(Arg, ArgType);
1986 }
1987 }
1988
Mike Stump11289f42009-09-09 15:08:12 +00001989 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00001990 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001991 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00001992 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001993 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00001994 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001995 Diag(Param->getLocation(), diag::note_template_param_here);
1996 return true;
1997 }
Mike Stump11289f42009-09-09 15:08:12 +00001998
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001999 if (ParamType->isMemberPointerType()) {
2000 NamedDecl *Member = 0;
2001 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2002 return true;
2003
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002004 if (Member)
2005 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002006 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002007 return false;
2008 }
Mike Stump11289f42009-09-09 15:08:12 +00002009
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002010 NamedDecl *Entity = 0;
2011 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2012 return true;
2013
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002014 if (Entity)
2015 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002016 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002017 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002018 }
2019
Chris Lattner696197c2009-02-20 21:37:53 +00002020 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002021 // -- for a non-type template-parameter of type pointer to
2022 // object, qualification conversions (4.4) and the
2023 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002024 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002025 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002026 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002027
Sebastian Redl576fd422009-05-10 18:38:11 +00002028 if (ArgType->isNullPtrType()) {
2029 ArgType = ParamType;
2030 ImpCastExprToType(Arg, ParamType);
2031 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002032 ArgType = Context.getArrayDecayedType(ArgType);
2033 ImpCastExprToType(Arg, ArgType);
Douglas Gregora9faa442009-02-11 00:44:29 +00002034 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002035
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002036 if (IsQualificationConversion(ArgType, ParamType)) {
2037 ArgType = ParamType;
2038 ImpCastExprToType(Arg, ParamType);
2039 }
Mike Stump11289f42009-09-09 15:08:12 +00002040
Douglas Gregor1515f762009-02-11 18:22:40 +00002041 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002042 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002043 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002044 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002045 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002046 Diag(Param->getLocation(), diag::note_template_param_here);
2047 return true;
2048 }
Mike Stump11289f42009-09-09 15:08:12 +00002049
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002050 NamedDecl *Entity = 0;
2051 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2052 return true;
2053
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002054 if (Entity)
2055 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002056 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002057 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002058 }
Mike Stump11289f42009-09-09 15:08:12 +00002059
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002060 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002061 // -- For a non-type template-parameter of type reference to
2062 // object, no conversions apply. The type referred to by the
2063 // reference may be more cv-qualified than the (otherwise
2064 // identical) type of the template-argument. The
2065 // template-parameter is bound directly to the
2066 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002067 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002068 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002069
Douglas Gregor1515f762009-02-11 18:22:40 +00002070 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002071 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002072 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002073 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002074 << Arg->getSourceRange();
2075 Diag(Param->getLocation(), diag::note_template_param_here);
2076 return true;
2077 }
2078
Mike Stump11289f42009-09-09 15:08:12 +00002079 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002080 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2081 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002082
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002083 if ((ParamQuals | ArgQuals) != ParamQuals) {
2084 Diag(Arg->getSourceRange().getBegin(),
2085 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002086 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002087 << Arg->getSourceRange();
2088 Diag(Param->getLocation(), diag::note_template_param_here);
2089 return true;
2090 }
Mike Stump11289f42009-09-09 15:08:12 +00002091
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002092 NamedDecl *Entity = 0;
2093 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2094 return true;
2095
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002096 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002097 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002098 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002099 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002100
2101 // -- For a non-type template-parameter of type pointer to data
2102 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002103 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002104 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2105
Douglas Gregor1515f762009-02-11 18:22:40 +00002106 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002107 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002108 } else if (ArgType->isNullPtrType()) {
2109 ImpCastExprToType(Arg, ParamType);
Douglas Gregor0e558532009-02-11 16:16:59 +00002110 } else if (IsQualificationConversion(ArgType, ParamType)) {
2111 ImpCastExprToType(Arg, ParamType);
2112 } else {
2113 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002114 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002115 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002116 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002117 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002118 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002119 }
2120
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002121 NamedDecl *Member = 0;
2122 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2123 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002124
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002125 if (Member)
2126 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002127 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002128 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00002129}
2130
2131/// \brief Check a template argument against its corresponding
2132/// template template parameter.
2133///
2134/// This routine implements the semantics of C++ [temp.arg.template].
2135/// It returns true if an error occurred, and false otherwise.
2136bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2137 DeclRefExpr *Arg) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002138 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2139 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2140
2141 // C++ [temp.arg.template]p1:
2142 // A template-argument for a template template-parameter shall be
2143 // the name of a class template, expressed as id-expression. Only
2144 // primary class templates are considered when matching the
2145 // template template argument with the corresponding parameter;
2146 // partial specializations are not considered even if their
2147 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002148 //
2149 // Note that we also allow template template parameters here, which
2150 // will happen when we are dealing with, e.g., class template
2151 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002152 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002153 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002154 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002155 "Only function templates are possible here");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002156 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2157 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002158 << Template;
2159 }
2160
2161 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2162 Param->getTemplateParameters(),
2163 true, true,
2164 Arg->getSourceRange().getBegin());
Douglas Gregord32e0282009-02-09 23:23:08 +00002165}
2166
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002167/// \brief Determine whether the given template parameter lists are
2168/// equivalent.
2169///
Mike Stump11289f42009-09-09 15:08:12 +00002170/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002171/// source code as part of a new template declaration.
2172///
2173/// \param Old The old template parameter list, typically found via
2174/// name lookup of the template declared with this template parameter
2175/// list.
2176///
2177/// \param Complain If true, this routine will produce a diagnostic if
2178/// the template parameter lists are not equivalent.
2179///
Douglas Gregor85e0f662009-02-10 00:24:35 +00002180/// \param IsTemplateTemplateParm If true, this routine is being
2181/// called to compare the template parameter lists of a template
2182/// template parameter.
2183///
2184/// \param TemplateArgLoc If this source location is valid, then we
2185/// are actually checking the template parameter list of a template
2186/// argument (New) against the template parameter list of its
2187/// corresponding template template parameter (Old). We produce
2188/// slightly different diagnostics in this scenario.
2189///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002190/// \returns True if the template parameter lists are equal, false
2191/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002192bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002193Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2194 TemplateParameterList *Old,
2195 bool Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002196 bool IsTemplateTemplateParm,
2197 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002198 if (Old->size() != New->size()) {
2199 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002200 unsigned NextDiag = diag::err_template_param_list_different_arity;
2201 if (TemplateArgLoc.isValid()) {
2202 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2203 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002204 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002205 Diag(New->getTemplateLoc(), NextDiag)
2206 << (New->size() > Old->size())
2207 << IsTemplateTemplateParm
2208 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002209 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2210 << IsTemplateTemplateParm
2211 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2212 }
2213
2214 return false;
2215 }
2216
2217 for (TemplateParameterList::iterator OldParm = Old->begin(),
2218 OldParmEnd = Old->end(), NewParm = New->begin();
2219 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2220 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002221 if (Complain) {
2222 unsigned NextDiag = diag::err_template_param_different_kind;
2223 if (TemplateArgLoc.isValid()) {
2224 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2225 NextDiag = diag::note_template_param_different_kind;
2226 }
2227 Diag((*NewParm)->getLocation(), NextDiag)
2228 << IsTemplateTemplateParm;
2229 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2230 << IsTemplateTemplateParm;
Douglas Gregor85e0f662009-02-10 00:24:35 +00002231 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002232 return false;
2233 }
2234
2235 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2236 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002237 // know we're at the same index).
2238#if 0
Mike Stump87c57ac2009-05-16 07:39:55 +00002239 // FIXME: Enable this code in debug mode *after* we properly go through
2240 // and "instantiate" the template parameter lists of template template
2241 // parameters. It's only after this instantiation that (1) any dependent
2242 // types within the template parameter list of the template template
2243 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregor85e0f662009-02-10 00:24:35 +00002244 // will match up.
Mike Stump11289f42009-09-09 15:08:12 +00002245 QualType OldParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002246 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
Mike Stump11289f42009-09-09 15:08:12 +00002247 QualType NewParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002248 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
Mike Stump11289f42009-09-09 15:08:12 +00002249 assert(Context.getCanonicalType(OldParmType) ==
2250 Context.getCanonicalType(NewParmType) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002251 "type parameter mismatch?");
2252#endif
Mike Stump11289f42009-09-09 15:08:12 +00002253 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002254 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2255 // The types of non-type template parameters must agree.
2256 NonTypeTemplateParmDecl *NewNTTP
2257 = cast<NonTypeTemplateParmDecl>(*NewParm);
2258 if (Context.getCanonicalType(OldNTTP->getType()) !=
2259 Context.getCanonicalType(NewNTTP->getType())) {
2260 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002261 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2262 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002263 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002264 diag::err_template_arg_template_params_mismatch);
2265 NextDiag = diag::note_template_nontype_parm_different_type;
2266 }
2267 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002268 << NewNTTP->getType()
2269 << IsTemplateTemplateParm;
Mike Stump11289f42009-09-09 15:08:12 +00002270 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002271 diag::note_template_nontype_parm_prev_declaration)
2272 << OldNTTP->getType();
2273 }
2274 return false;
2275 }
2276 } else {
2277 // The template parameter lists of template template
2278 // parameters must agree.
2279 // FIXME: Could we perform a faster "type" comparison here?
Mike Stump11289f42009-09-09 15:08:12 +00002280 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002281 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002282 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002283 = cast<TemplateTemplateParmDecl>(*OldParm);
2284 TemplateTemplateParmDecl *NewTTP
2285 = cast<TemplateTemplateParmDecl>(*NewParm);
2286 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2287 OldTTP->getTemplateParameters(),
2288 Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002289 /*IsTemplateTemplateParm=*/true,
2290 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002291 return false;
2292 }
2293 }
2294
2295 return true;
2296}
2297
2298/// \brief Check whether a template can be declared within this scope.
2299///
2300/// If the template declaration is valid in this scope, returns
2301/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002302bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002303Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002304 // Find the nearest enclosing declaration scope.
2305 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2306 (S->getFlags() & Scope::TemplateParamScope) != 0)
2307 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002308
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002309 // C++ [temp]p2:
2310 // A template-declaration can appear only as a namespace scope or
2311 // class scope declaration.
2312 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002313 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2314 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002315 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002316 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002317
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002318 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002319 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002320
2321 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2322 return false;
2323
Mike Stump11289f42009-09-09 15:08:12 +00002324 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002325 diag::err_template_outside_namespace_or_class_scope)
2326 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002327}
Douglas Gregor67a65642009-02-17 23:15:12 +00002328
Douglas Gregorf61eca92009-05-13 18:28:20 +00002329/// \brief Check whether a class template specialization or explicit
2330/// instantiation in the current context is well-formed.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002331///
Douglas Gregorf61eca92009-05-13 18:28:20 +00002332/// This routine determines whether a class template specialization or
Mike Stump11289f42009-09-09 15:08:12 +00002333/// explicit instantiation can be declared in the current context
2334/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2335/// appropriate diagnostics if there was an error. It returns true if
Douglas Gregorf61eca92009-05-13 18:28:20 +00002336// there was an error that we cannot recover from, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002337bool
Douglas Gregorf47b9112009-02-25 22:02:03 +00002338Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2339 ClassTemplateSpecializationDecl *PrevDecl,
2340 SourceLocation TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002341 SourceRange ScopeSpecifierRange,
Douglas Gregor30b01972009-06-12 22:21:45 +00002342 bool PartialSpecialization,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002343 bool ExplicitInstantiation) {
Douglas Gregorf47b9112009-02-25 22:02:03 +00002344 // C++ [temp.expl.spec]p2:
2345 // An explicit specialization shall be declared in the namespace
2346 // of which the template is a member, or, for member templates, in
2347 // the namespace of which the enclosing class or enclosing class
2348 // template is a member. An explicit specialization of a member
2349 // function, member class or static data member of a class
2350 // template shall be declared in the namespace of which the class
2351 // template is a member. Such a declaration may also be a
2352 // definition. If the declaration is not a definition, the
2353 // specialization may be defined later in the name- space in which
2354 // the explicit specialization was declared, or in a namespace
2355 // that encloses the one in which the explicit specialization was
2356 // declared.
2357 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor30b01972009-06-12 22:21:45 +00002358 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002359 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002360 << Kind << ClassTemplate;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002361 return true;
2362 }
2363
2364 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00002365 DeclContext *TemplateContext
Douglas Gregorf47b9112009-02-25 22:02:03 +00002366 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorf61eca92009-05-13 18:28:20 +00002367 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2368 !ExplicitInstantiation) {
Douglas Gregorf47b9112009-02-25 22:02:03 +00002369 // There is no prior declaration of this entity, so this
2370 // specialization must be in the same context as the template
2371 // itself.
2372 if (DC != TemplateContext) {
2373 if (isa<TranslationUnitDecl>(TemplateContext))
2374 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor30b01972009-06-12 22:21:45 +00002375 << PartialSpecialization
Douglas Gregorf47b9112009-02-25 22:02:03 +00002376 << ClassTemplate << ScopeSpecifierRange;
2377 else if (isa<NamespaceDecl>(TemplateContext))
2378 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Mike Stump11289f42009-09-09 15:08:12 +00002379 << PartialSpecialization << ClassTemplate
Douglas Gregor30b01972009-06-12 22:21:45 +00002380 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002381
2382 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2383 }
2384
2385 return false;
2386 }
2387
2388 // We have a previous declaration of this entity. Make sure that
2389 // this redeclaration (or definition) occurs in an enclosing namespace.
2390 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002391 // FIXME: In C++98, we would like to turn these errors into warnings,
2392 // dependent on a -Wc++0x flag.
Douglas Gregorf61eca92009-05-13 18:28:20 +00002393 bool SuppressedDiag = false;
Douglas Gregor30b01972009-06-12 22:21:45 +00002394 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorf61eca92009-05-13 18:28:20 +00002395 if (isa<TranslationUnitDecl>(TemplateContext)) {
2396 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2397 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002398 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorf61eca92009-05-13 18:28:20 +00002399 else
2400 SuppressedDiag = true;
2401 } else if (isa<NamespaceDecl>(TemplateContext)) {
2402 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2403 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002404 << Kind << ClassTemplate
Douglas Gregorf61eca92009-05-13 18:28:20 +00002405 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Mike Stump11289f42009-09-09 15:08:12 +00002406 else
Douglas Gregorf61eca92009-05-13 18:28:20 +00002407 SuppressedDiag = true;
2408 }
Mike Stump11289f42009-09-09 15:08:12 +00002409
Douglas Gregorf61eca92009-05-13 18:28:20 +00002410 if (!SuppressedDiag)
2411 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002412 }
2413
2414 return false;
2415}
2416
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002417/// \brief Check the non-type template arguments of a class template
2418/// partial specialization according to C++ [temp.class.spec]p9.
2419///
Douglas Gregor09a30232009-06-12 22:08:06 +00002420/// \param TemplateParams the template parameters of the primary class
2421/// template.
2422///
2423/// \param TemplateArg the template arguments of the class template
2424/// partial specialization.
2425///
2426/// \param MirrorsPrimaryTemplate will be set true if the class
2427/// template partial specialization arguments are identical to the
2428/// implicit template arguments of the primary template. This is not
2429/// necessarily an error (C++0x), and it is left to the caller to diagnose
2430/// this condition when it is an error.
2431///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002432/// \returns true if there was an error, false otherwise.
2433bool Sema::CheckClassTemplatePartialSpecializationArgs(
2434 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002435 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002436 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002437 // FIXME: the interface to this function will have to change to
2438 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002439 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002440
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002441 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002442
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002443 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002444 // Determine whether the template argument list of the partial
2445 // specialization is identical to the implicit argument list of
2446 // the primary template. The caller may need to diagnostic this as
2447 // an error per C++ [temp.class.spec]p9b3.
2448 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002449 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002450 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2451 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002452 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002453 MirrorsPrimaryTemplate = false;
2454 } else if (TemplateTemplateParmDecl *TTP
2455 = dyn_cast<TemplateTemplateParmDecl>(
2456 TemplateParams->getParam(I))) {
2457 // FIXME: We should settle on either Declaration storage or
2458 // Expression storage for template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002459 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor09a30232009-06-12 22:08:06 +00002460 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson40c1d492009-06-13 18:20:51 +00002461 ArgList[I].getAsDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002462 if (!ArgDecl)
Mike Stump11289f42009-09-09 15:08:12 +00002463 if (DeclRefExpr *DRE
Anders Carlsson40c1d492009-06-13 18:20:51 +00002464 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002465 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2466
2467 if (!ArgDecl ||
2468 ArgDecl->getIndex() != TTP->getIndex() ||
2469 ArgDecl->getDepth() != TTP->getDepth())
2470 MirrorsPrimaryTemplate = false;
2471 }
2472 }
2473
Mike Stump11289f42009-09-09 15:08:12 +00002474 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002475 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002476 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002477 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002478 }
2479
Anders Carlsson40c1d492009-06-13 18:20:51 +00002480 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002481 if (!ArgExpr) {
2482 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002483 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002484 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002485
2486 // C++ [temp.class.spec]p8:
2487 // A non-type argument is non-specialized if it is the name of a
2488 // non-type parameter. All other non-type arguments are
2489 // specialized.
2490 //
2491 // Below, we check the two conditions that only apply to
2492 // specialized non-type arguments, so skip any non-specialized
2493 // arguments.
2494 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002495 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002496 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002497 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002498 (Param->getIndex() != NTTP->getIndex() ||
2499 Param->getDepth() != NTTP->getDepth()))
2500 MirrorsPrimaryTemplate = false;
2501
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002502 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002503 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002504
2505 // C++ [temp.class.spec]p9:
2506 // Within the argument list of a class template partial
2507 // specialization, the following restrictions apply:
2508 // -- A partially specialized non-type argument expression
2509 // shall not involve a template parameter of the partial
2510 // specialization except when the argument expression is a
2511 // simple identifier.
2512 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002513 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002514 diag::err_dependent_non_type_arg_in_partial_spec)
2515 << ArgExpr->getSourceRange();
2516 return true;
2517 }
2518
2519 // -- The type of a template parameter corresponding to a
2520 // specialized non-type argument shall not be dependent on a
2521 // parameter of the specialization.
2522 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002523 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002524 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2525 << Param->getType()
2526 << ArgExpr->getSourceRange();
2527 Diag(Param->getLocation(), diag::note_template_param_here);
2528 return true;
2529 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002530
2531 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002532 }
2533
2534 return false;
2535}
2536
Douglas Gregorc08f4892009-03-25 00:13:59 +00002537Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002538Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2539 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002540 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002541 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002542 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002543 SourceLocation TemplateNameLoc,
2544 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002545 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002546 SourceLocation *TemplateArgLocs,
2547 SourceLocation RAngleLoc,
2548 AttributeList *Attr,
2549 MultiTemplateParamsArg TemplateParameterLists) {
John McCall06f6fe8d2009-09-04 01:14:41 +00002550 assert(TUK == TUK_Declaration || TUK == TUK_Definition);
2551
Douglas Gregor67a65642009-02-17 23:15:12 +00002552 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002553 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002554 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002555 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002556
Douglas Gregor2373c592009-05-31 09:31:02 +00002557 bool isPartialSpecialization = false;
2558
Douglas Gregorf47b9112009-02-25 22:02:03 +00002559 // Check the validity of the template headers that introduce this
2560 // template.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002561 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002562 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2563 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002564 TemplateParameterLists.size());
2565 if (TemplateParams && TemplateParams->size() > 0) {
2566 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002567
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002568 // C++ [temp.class.spec]p10:
2569 // The template parameter list of a specialization shall not
2570 // contain default template argument values.
2571 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2572 Decl *Param = TemplateParams->getParam(I);
2573 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2574 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002575 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002576 diag::err_default_arg_in_partial_spec);
2577 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2578 }
2579 } else if (NonTypeTemplateParmDecl *NTTP
2580 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2581 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002582 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002583 diag::err_default_arg_in_partial_spec)
2584 << DefArg->getSourceRange();
2585 NTTP->setDefaultArgument(0);
2586 DefArg->Destroy(Context);
2587 }
2588 } else {
2589 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2590 if (Expr *DefArg = TTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002591 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002592 diag::err_default_arg_in_partial_spec)
2593 << DefArg->getSourceRange();
2594 TTP->setDefaultArgument(0);
2595 DefArg->Destroy(Context);
Douglas Gregord5222052009-06-12 19:43:02 +00002596 }
2597 }
2598 }
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002599 } else if (!TemplateParams)
2600 Diag(KWLoc, diag::err_template_spec_needs_header)
2601 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregorf47b9112009-02-25 22:02:03 +00002602
Douglas Gregor67a65642009-02-17 23:15:12 +00002603 // Check that the specialization uses the same tag kind as the
2604 // original template.
2605 TagDecl::TagKind Kind;
2606 switch (TagSpec) {
2607 default: assert(0 && "Unknown tag type!");
2608 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2609 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2610 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2611 }
Douglas Gregord9034f02009-05-14 16:41:31 +00002612 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00002613 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00002614 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00002615 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00002616 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00002617 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00002618 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00002619 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00002620 diag::note_previous_use);
2621 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2622 }
2623
Douglas Gregorc40290e2009-03-09 23:48:35 +00002624 // Translate the parser's template argument list in our AST format.
2625 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2626 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2627
Douglas Gregor67a65642009-02-17 23:15:12 +00002628 // Check that the template argument list is well-formed for this
2629 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002630 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2631 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00002632 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002633 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00002634 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002635 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002636
Mike Stump11289f42009-09-09 15:08:12 +00002637 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00002638 ClassTemplate->getTemplateParameters()->size()) &&
2639 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00002640
Douglas Gregor2373c592009-05-31 09:31:02 +00002641 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00002642 // corresponds to these arguments.
2643 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00002644 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002645 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002646 if (CheckClassTemplatePartialSpecializationArgs(
2647 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002648 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002649 return true;
2650
Douglas Gregor09a30232009-06-12 22:08:06 +00002651 if (MirrorsPrimaryTemplate) {
2652 // C++ [temp.class.spec]p9b3:
2653 //
Mike Stump11289f42009-09-09 15:08:12 +00002654 // -- The argument list of the specialization shall not be identical
2655 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00002656 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00002657 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00002658 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00002659 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00002660 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00002661 ClassTemplate->getIdentifier(),
2662 TemplateNameLoc,
2663 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002664 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00002665 AS_none);
2666 }
2667
Douglas Gregor2373c592009-05-31 09:31:02 +00002668 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00002669 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002670 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002671 Converted.flatSize(),
2672 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002673 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002674 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002675 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002676 Converted.flatSize(),
2677 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00002678 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002679 ClassTemplateSpecializationDecl *PrevDecl = 0;
2680
2681 if (isPartialSpecialization)
2682 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00002683 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00002684 InsertPos);
2685 else
2686 PrevDecl
2687 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00002688
2689 ClassTemplateSpecializationDecl *Specialization = 0;
2690
Douglas Gregorf47b9112009-02-25 22:02:03 +00002691 // Check whether we can declare a class template specialization in
2692 // the current scope.
2693 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002694 TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002695 SS.getRange(),
Douglas Gregor30b01972009-06-12 22:21:45 +00002696 isPartialSpecialization,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002697 /*ExplicitInstantiation=*/false))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002698 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002699
Douglas Gregor15301382009-07-30 17:40:51 +00002700 // The canonical type
2701 QualType CanonType;
Douglas Gregor67a65642009-02-17 23:15:12 +00002702 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2703 // Since the only prior class template specialization with these
2704 // arguments was referenced but not declared, reuse that
2705 // declaration node as our own, updating its source location to
2706 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002707 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00002708 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00002709 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00002710 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00002711 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00002712 // Build the canonical type that describes the converted template
2713 // arguments of the class template partial specialization.
2714 CanonType = Context.getTemplateSpecializationType(
2715 TemplateName(ClassTemplate),
2716 Converted.getFlatArguments(),
2717 Converted.flatSize());
2718
Douglas Gregor2373c592009-05-31 09:31:02 +00002719 // Create a new class template partial specialization declaration node.
Mike Stump11289f42009-09-09 15:08:12 +00002720 TemplateParameterList *TemplateParams
Douglas Gregor2373c592009-05-31 09:31:02 +00002721 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2722 ClassTemplatePartialSpecializationDecl *PrevPartial
2723 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002724 ClassTemplatePartialSpecializationDecl *Partial
2725 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00002726 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002727 TemplateNameLoc,
2728 TemplateParams,
2729 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002730 Converted,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002731 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00002732
2733 if (PrevPartial) {
2734 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2735 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2736 } else {
2737 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2738 }
2739 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00002740
2741 // Check that all of the template parameters of the class template
2742 // partial specialization are deducible from the template
2743 // arguments. If not, this class template partial specialization
2744 // will never be used.
2745 llvm::SmallVector<bool, 8> DeducibleParams;
2746 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002747 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2748 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00002749 unsigned NumNonDeducible = 0;
2750 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2751 if (!DeducibleParams[I])
2752 ++NumNonDeducible;
2753
2754 if (NumNonDeducible) {
2755 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2756 << (NumNonDeducible > 1)
2757 << SourceRange(TemplateNameLoc, RAngleLoc);
2758 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2759 if (!DeducibleParams[I]) {
2760 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2761 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00002762 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002763 diag::note_partial_spec_unused_parameter)
2764 << Param->getDeclName();
2765 else
Mike Stump11289f42009-09-09 15:08:12 +00002766 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002767 diag::note_partial_spec_unused_parameter)
2768 << std::string("<anonymous>");
2769 }
2770 }
2771 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002772 } else {
2773 // Create a new class template specialization declaration node for
2774 // this explicit specialization.
2775 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00002776 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00002777 ClassTemplate->getDeclContext(),
2778 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002779 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002780 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00002781 PrevDecl);
2782
2783 if (PrevDecl) {
2784 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2785 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2786 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002787 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00002788 InsertPos);
2789 }
Douglas Gregor15301382009-07-30 17:40:51 +00002790
2791 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002792 }
2793
2794 // Note that this is an explicit specialization.
2795 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2796
2797 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002798 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002799 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002800 // FIXME: Should also handle explicit specialization after implicit
2801 // instantiation with a special diagnostic.
Douglas Gregor67a65642009-02-17 23:15:12 +00002802 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002803 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00002804 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00002805 Diag(Def->getLocation(), diag::note_previous_definition);
2806 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00002807 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002808 }
2809 }
2810
Douglas Gregord56a91e2009-02-26 22:19:44 +00002811 // Build the fully-sugared type for this class template
2812 // specialization as the user wrote in the specialization
2813 // itself. This means that we'll pretty-print the type retrieved
2814 // from the specialization's declaration the way that the user
2815 // actually wrote the specialization, rather than formatting the
2816 // name based on the "canonical" representation used to store the
2817 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002818 QualType WrittenTy
2819 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002820 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00002821 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00002822 CanonType);
Douglas Gregordc572a32009-03-30 22:58:21 +00002823 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002824 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00002825
Douglas Gregor1e249f82009-02-25 22:18:32 +00002826 // C++ [temp.expl.spec]p9:
2827 // A template explicit specialization is in the scope of the
2828 // namespace in which the template was defined.
2829 //
2830 // We actually implement this paragraph where we set the semantic
2831 // context (in the creation of the ClassTemplateSpecializationDecl),
2832 // but we also maintain the lexical context where the actual
2833 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00002834 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00002835
Douglas Gregor67a65642009-02-17 23:15:12 +00002836 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002837 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00002838 Specialization->startDefinition();
2839
2840 // Add the specialization into its lexical context, so that it can
2841 // be seen when iterating through the list of declarations in that
2842 // context. However, specializations are not found by name lookup.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002843 CurContext->addDecl(Specialization);
Chris Lattner83f095c2009-03-28 19:18:32 +00002844 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002845}
Douglas Gregor333489b2009-03-27 23:10:48 +00002846
Mike Stump11289f42009-09-09 15:08:12 +00002847Sema::DeclPtrTy
2848Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002849 MultiTemplateParamsArg TemplateParameterLists,
2850 Declarator &D) {
2851 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2852}
2853
Mike Stump11289f42009-09-09 15:08:12 +00002854Sema::DeclPtrTy
2855Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002856 MultiTemplateParamsArg TemplateParameterLists,
2857 Declarator &D) {
2858 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2859 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2860 "Not a function declarator!");
2861 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00002862
Douglas Gregor17a7c122009-06-24 00:54:41 +00002863 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00002864 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00002865 }
Mike Stump11289f42009-09-09 15:08:12 +00002866
Douglas Gregor17a7c122009-06-24 00:54:41 +00002867 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002868
2869 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002870 move(TemplateParameterLists),
2871 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002872 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00002873 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00002874 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002875 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00002876 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2877 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002878 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00002879}
2880
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002881/// \brief Perform semantic analysis for the given function template
2882/// specialization.
2883///
2884/// This routine performs all of the semantic analysis required for an
2885/// explicit function template specialization. On successful completion,
2886/// the function declaration \p FD will become a function template
2887/// specialization.
2888///
2889/// \param FD the function declaration, which will be updated to become a
2890/// function template specialization.
2891///
2892/// \param HasExplicitTemplateArgs whether any template arguments were
2893/// explicitly provided.
2894///
2895/// \param LAngleLoc the location of the left angle bracket ('<'), if
2896/// template arguments were explicitly provided.
2897///
2898/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
2899/// if any.
2900///
2901/// \param NumExplicitTemplateArgs the number of explicitly-provided template
2902/// arguments. This number may be zero even when HasExplicitTemplateArgs is
2903/// true as in, e.g., \c void sort<>(char*, char*);
2904///
2905/// \param RAngleLoc the location of the right angle bracket ('>'), if
2906/// template arguments were explicitly provided.
2907///
2908/// \param PrevDecl the set of declarations that
2909bool
2910Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
2911 bool HasExplicitTemplateArgs,
2912 SourceLocation LAngleLoc,
2913 const TemplateArgument *ExplicitTemplateArgs,
2914 unsigned NumExplicitTemplateArgs,
2915 SourceLocation RAngleLoc,
2916 NamedDecl *&PrevDecl) {
2917 // The set of function template specializations that could match this
2918 // explicit function template specialization.
2919 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
2920 CandidateSet Candidates;
2921
2922 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
2923 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2924 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
2925 // Only consider templates found within the same semantic lookup scope as
2926 // FD.
2927 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
2928 continue;
2929
2930 // C++ [temp.expl.spec]p11:
2931 // A trailing template-argument can be left unspecified in the
2932 // template-id naming an explicit function template specialization
2933 // provided it can be deduced from the function argument type.
2934 // Perform template argument deduction to determine whether we may be
2935 // specializing this template.
2936 // FIXME: It is somewhat wasteful to build
2937 TemplateDeductionInfo Info(Context);
2938 FunctionDecl *Specialization = 0;
2939 if (TemplateDeductionResult TDK
2940 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
2941 ExplicitTemplateArgs,
2942 NumExplicitTemplateArgs,
2943 FD->getType(),
2944 Specialization,
2945 Info)) {
2946 // FIXME: Template argument deduction failed; record why it failed, so
2947 // that we can provide nifty diagnostics.
2948 (void)TDK;
2949 continue;
2950 }
2951
2952 // Record this candidate.
2953 Candidates.push_back(Specialization);
2954 }
2955 }
2956
2957 if (Candidates.empty()) {
2958 Diag(FD->getLocation(), diag::err_function_template_spec_no_match)
2959 << FD->getDeclName();
2960 // FIXME: Print the almost-ran candidates.
2961 return true;
2962 }
2963
2964 if (Candidates.size() > 1) {
2965 // C++ [temp.func.order]p1:
2966 // Partial ordering of overloaded function template declarations is used
2967 // [...] when [...] an explicit specialization (14.7.3) refers to a
2968 // function template specialization.
2969 CandidateSet::iterator Best = Candidates.begin();
2970 for (CandidateSet::iterator C = Best + 1, CEnd = Candidates.end();
2971 C != CEnd; ++C) {
2972 if (getMoreSpecializedTemplate((*Best)->getPrimaryTemplate(),
2973 (*C)->getPrimaryTemplate(),
2974 TPOC_Other)
2975 == (*C)->getPrimaryTemplate())
2976 Best = C;
2977 }
2978
2979 bool Ambiguous = false;
2980 for (CandidateSet::iterator C = Candidates.begin(), CEnd = Candidates.end();
2981 C != CEnd; ++C) {
2982 if (C != Best &&
2983 getMoreSpecializedTemplate((*Best)->getPrimaryTemplate(),
2984 (*C)->getPrimaryTemplate(),
2985 TPOC_Other)
2986 != (*Best)->getPrimaryTemplate()) {
2987 Ambiguous = true;
2988 break;
2989 }
2990 }
2991
2992 if (Ambiguous) {
2993 // Partial ordering was ambiguous.
2994 Diag(FD->getLocation(), diag::err_function_template_spec_ambiguous)
2995 << FD->getDeclName()
2996 << HasExplicitTemplateArgs;
2997
2998 for (CandidateSet::iterator C = Candidates.begin(),
2999 CEnd = Candidates.end();
3000 C != CEnd; ++C)
3001 Diag((*C)->getLocation(), diag::note_function_template_spec_matched)
3002 << getTemplateArgumentBindingsText(
3003 (*C)->getPrimaryTemplate()->getTemplateParameters(),
3004 *(*C)->getTemplateSpecializationArgs());
3005
3006 return true;
3007 }
3008
3009 // Move the best candidate to the front of the candidates list.
3010 std::swap(*Best, Candidates.front());
3011 }
3012
3013 // The first candidate is a prior declaration of the function template
3014 // specialization we're declared here, which we may have created above.
3015 FunctionDecl *Specialization = Candidates.front();
3016
3017 // FIXME: Check if the prior specialization has a point of instantiation.
3018 // If so, we have run afoul of C++ [temp.expl.spec]p6.
3019
3020 // Mark the prior declaration as an explicit specialization, so that later
3021 // clients know that this is an explicit specialization.
3022 // FIXME: Check for prior explicit instantiations?
3023 Specialization->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
3024
3025 // Turn the given function declaration into a function template
3026 // specialization, with the template arguments from the previous
3027 // specialization.
3028 FD->setFunctionTemplateSpecialization(Context,
3029 Specialization->getPrimaryTemplate(),
3030 new (Context) TemplateArgumentList(
3031 *Specialization->getTemplateSpecializationArgs()),
3032 /*InsertPos=*/0,
3033 TSK_ExplicitSpecialization);
3034
3035 // The "previous declaration" for this function template specialization is
3036 // the prior function template specialization.
3037 PrevDecl = Specialization;
3038 return false;
3039}
3040
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003041// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003042// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003043Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003044Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003045 SourceLocation ExternLoc,
3046 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003047 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003048 SourceLocation KWLoc,
3049 const CXXScopeSpec &SS,
3050 TemplateTy TemplateD,
3051 SourceLocation TemplateNameLoc,
3052 SourceLocation LAngleLoc,
3053 ASTTemplateArgsPtr TemplateArgsIn,
3054 SourceLocation *TemplateArgLocs,
3055 SourceLocation RAngleLoc,
3056 AttributeList *Attr) {
3057 // Find the class template we're specializing
3058 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003059 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003060 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3061
3062 // Check that the specialization uses the same tag kind as the
3063 // original template.
3064 TagDecl::TagKind Kind;
3065 switch (TagSpec) {
3066 default: assert(0 && "Unknown tag type!");
3067 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3068 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3069 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3070 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003071 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003072 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003073 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003074 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003075 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003076 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003077 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003078 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003079 diag::note_previous_use);
3080 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3081 }
3082
Douglas Gregorf61eca92009-05-13 18:28:20 +00003083 // C++0x [temp.explicit]p2:
3084 // [...] An explicit instantiation shall appear in an enclosing
3085 // namespace of its template. [...]
3086 //
3087 // This is C++ DR 275.
3088 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
Mike Stump11289f42009-09-09 15:08:12 +00003089 TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003090 SS.getRange(),
Douglas Gregor30b01972009-06-12 22:21:45 +00003091 /*PartialSpecialization=*/false,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003092 /*ExplicitInstantiation=*/true))
3093 return true;
3094
Douglas Gregora1f49972009-05-13 00:25:59 +00003095 // Translate the parser's template argument list in our AST format.
3096 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3097 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3098
3099 // Check that the template argument list is well-formed for this
3100 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003101 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3102 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003103 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003104 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003105 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003106 return true;
3107
Mike Stump11289f42009-09-09 15:08:12 +00003108 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003109 ClassTemplate->getTemplateParameters()->size()) &&
3110 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003111
Douglas Gregora1f49972009-05-13 00:25:59 +00003112 // Find the class template specialization declaration that
3113 // corresponds to these arguments.
3114 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003115 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003116 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003117 Converted.flatSize(),
3118 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003119 void *InsertPos = 0;
3120 ClassTemplateSpecializationDecl *PrevDecl
3121 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3122
3123 ClassTemplateSpecializationDecl *Specialization = 0;
3124
Douglas Gregorf61eca92009-05-13 18:28:20 +00003125 bool SpecializationRequiresInstantiation = true;
Douglas Gregora1f49972009-05-13 00:25:59 +00003126 if (PrevDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003127 if (PrevDecl->getSpecializationKind()
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003128 == TSK_ExplicitInstantiationDefinition) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003129 // This particular specialization has already been declared or
3130 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorf61eca92009-05-13 18:28:20 +00003131 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
3132 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003133 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003134 diag::note_previous_explicit_instantiation);
Douglas Gregora1f49972009-05-13 00:25:59 +00003135 return DeclPtrTy::make(PrevDecl);
3136 }
3137
Douglas Gregorf61eca92009-05-13 18:28:20 +00003138 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003139 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorf61eca92009-05-13 18:28:20 +00003140 // For a given set of template parameters, if an explicit
3141 // instantiation of a template appears after a declaration of
3142 // an explicit specialization for that template, the explicit
3143 // instantiation has no effect.
3144 if (!getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00003145 Diag(TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003146 diag::ext_explicit_instantiation_after_specialization)
3147 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003148 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003149 diag::note_previous_template_specialization);
3150 }
3151
3152 // Create a new class template specialization declaration node
3153 // for this explicit specialization. This node is only used to
3154 // record the existence of this explicit instantiation for
3155 // accurate reproduction of the source code; we don't actually
3156 // use it for anything, since it is semantically irrelevant.
3157 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003158 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003159 ClassTemplate->getDeclContext(),
3160 TemplateNameLoc,
3161 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003162 Converted, 0);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003163 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003164 CurContext->addDecl(Specialization);
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003165 return DeclPtrTy::make(PrevDecl);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003166 }
3167
3168 // If we have already (implicitly) instantiated this
3169 // specialization, there is less work to do.
3170 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
3171 SpecializationRequiresInstantiation = false;
3172
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003173 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3174 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3175 // Since the only prior class template specialization with these
3176 // arguments was referenced but not declared, reuse that
3177 // declaration node as our own, updating its source location to
3178 // reflect our new declaration.
3179 Specialization = PrevDecl;
3180 Specialization->setLocation(TemplateNameLoc);
3181 PrevDecl = 0;
3182 }
3183 }
3184
3185 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003186 // Create a new class template specialization declaration node for
3187 // this explicit specialization.
3188 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003189 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003190 ClassTemplate->getDeclContext(),
3191 TemplateNameLoc,
3192 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003193 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003194
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003195 if (PrevDecl) {
3196 // Remove the previous declaration from the folding set, since we want
3197 // to introduce a new declaration.
3198 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3199 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3200 }
3201
3202 // Insert the new specialization.
3203 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003204 }
3205
3206 // Build the fully-sugared type for this explicit instantiation as
3207 // the user wrote in the explicit instantiation itself. This means
3208 // that we'll pretty-print the type retrieved from the
3209 // specialization's declaration the way that the user actually wrote
3210 // the explicit instantiation, rather than formatting the name based
3211 // on the "canonical" representation used to store the template
3212 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003213 QualType WrittenTy
3214 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003215 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003216 TemplateArgs.size(),
3217 Context.getTypeDeclType(Specialization));
3218 Specialization->setTypeAsWritten(WrittenTy);
3219 TemplateArgsIn.release();
3220
3221 // Add the explicit instantiation into its lexical context. However,
3222 // since explicit instantiations are never found by name lookup, we
3223 // just put it into the declaration context directly.
3224 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003225 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003226
John McCall1806c272009-09-11 07:25:08 +00003227 Specialization->setPointOfInstantiation(TemplateNameLoc);
3228
Douglas Gregora1f49972009-05-13 00:25:59 +00003229 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003230 // A definition of a class template or class member template
3231 // shall be in scope at the point of the explicit instantiation of
3232 // the class template or class member template.
3233 //
3234 // This check comes when we actually try to perform the
3235 // instantiation.
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003236 TemplateSpecializationKind TSK
Mike Stump11289f42009-09-09 15:08:12 +00003237 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003238 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor67da0d92009-05-15 17:59:04 +00003239 if (SpecializationRequiresInstantiation)
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003240 InstantiateClassTemplateSpecialization(Specialization, TSK);
Douglas Gregor85673582009-05-18 17:01:57 +00003241 else // Instantiate the members of this class template specialization.
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003242 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization,
3243 TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003244
3245 return DeclPtrTy::make(Specialization);
3246}
3247
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003248// Explicit instantiation of a member class of a class template.
3249Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003250Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003251 SourceLocation ExternLoc,
3252 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003253 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003254 SourceLocation KWLoc,
3255 const CXXScopeSpec &SS,
3256 IdentifierInfo *Name,
3257 SourceLocation NameLoc,
3258 AttributeList *Attr) {
3259
Douglas Gregord6ab8742009-05-28 23:31:59 +00003260 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003261 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00003262 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00003263 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00003264 MultiTemplateParamsArg(*this, 0, 0),
3265 Owned, IsDependent);
3266 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3267
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003268 if (!TagD)
3269 return true;
3270
3271 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3272 if (Tag->isEnum()) {
3273 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3274 << Context.getTypeDeclType(Tag);
3275 return true;
3276 }
3277
Douglas Gregorb8006faf2009-05-27 17:30:49 +00003278 if (Tag->isInvalidDecl())
3279 return true;
3280
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003281 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3282 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3283 if (!Pattern) {
3284 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3285 << Context.getTypeDeclType(Record);
3286 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3287 return true;
3288 }
3289
3290 // C++0x [temp.explicit]p2:
3291 // [...] An explicit instantiation shall appear in an enclosing
3292 // namespace of its template. [...]
3293 //
3294 // This is C++ DR 275.
3295 if (getLangOptions().CPlusPlus0x) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003296 // FIXME: In C++98, we would like to turn these errors into warnings,
3297 // dependent on a -Wc++0x flag.
Mike Stump11289f42009-09-09 15:08:12 +00003298 DeclContext *PatternContext
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003299 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
3300 if (!CurContext->Encloses(PatternContext)) {
3301 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
3302 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
3303 Diag(Pattern->getLocation(), diag::note_previous_declaration);
3304 }
3305 }
3306
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003307 TemplateSpecializationKind TSK
Mike Stump11289f42009-09-09 15:08:12 +00003308 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003309 : TSK_ExplicitInstantiationDeclaration;
Mike Stump11289f42009-09-09 15:08:12 +00003310
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003311 if (!Record->getDefinition(Context)) {
3312 // If the class has a definition, instantiate it (and all of its
3313 // members, recursively).
3314 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
Mike Stump11289f42009-09-09 15:08:12 +00003315 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregorb4850462009-05-14 23:26:13 +00003316 getTemplateInstantiationArgs(Record),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003317 TSK))
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003318 return true;
John McCall76d824f2009-08-25 22:02:44 +00003319 } else // Instantiate all of the members of the class.
Mike Stump11289f42009-09-09 15:08:12 +00003320 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003321 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003322
Mike Stump87c57ac2009-05-16 07:39:55 +00003323 // FIXME: We don't have any representation for explicit instantiations of
3324 // member classes. Such a representation is not needed for compilation, but it
3325 // should be available for clients that want to see all of the declarations in
3326 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003327 return TagD;
3328}
3329
Douglas Gregor450f00842009-09-25 18:43:00 +00003330Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
3331 SourceLocation ExternLoc,
3332 SourceLocation TemplateLoc,
3333 Declarator &D) {
3334 // Explicit instantiations always require a name.
3335 DeclarationName Name = GetNameForDeclarator(D);
3336 if (!Name) {
3337 if (!D.isInvalidType())
3338 Diag(D.getDeclSpec().getSourceRange().getBegin(),
3339 diag::err_explicit_instantiation_requires_name)
3340 << D.getDeclSpec().getSourceRange()
3341 << D.getSourceRange();
3342
3343 return true;
3344 }
3345
3346 // The scope passed in may not be a decl scope. Zip up the scope tree until
3347 // we find one that is.
3348 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3349 (S->getFlags() & Scope::TemplateParamScope) != 0)
3350 S = S->getParent();
3351
3352 // Determine the type of the declaration.
3353 QualType R = GetTypeForDeclarator(D, S, 0);
3354 if (R.isNull())
3355 return true;
3356
3357 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3358 // Cannot explicitly instantiate a typedef.
3359 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
3360 << Name;
3361 return true;
3362 }
3363
3364 // Determine what kind of explicit instantiation we have.
3365 TemplateSpecializationKind TSK
3366 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3367 : TSK_ExplicitInstantiationDeclaration;
3368
3369 LookupResult Previous = LookupParsedName(S, &D.getCXXScopeSpec(),
3370 Name, LookupOrdinaryName);
3371
3372 if (!R->isFunctionType()) {
3373 // C++ [temp.explicit]p1:
3374 // A [...] static data member of a class template can be explicitly
3375 // instantiated from the member definition associated with its class
3376 // template.
3377 if (Previous.isAmbiguous()) {
3378 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
3379 D.getSourceRange());
3380 }
3381
3382 VarDecl *Prev = dyn_cast_or_null<VarDecl>(Previous.getAsDecl());
3383 if (!Prev || !Prev->isStaticDataMember()) {
3384 // We expect to see a data data member here.
3385 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
3386 << Name;
3387 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3388 P != PEnd; ++P)
3389 Diag(P->getLocation(), diag::note_explicit_instantiation_here);
3390 return true;
3391 }
3392
3393 if (!Prev->getInstantiatedFromStaticDataMember()) {
3394 // FIXME: Check for explicit specialization?
3395 Diag(D.getIdentifierLoc(),
3396 diag::err_explicit_instantiation_data_member_not_instantiated)
3397 << Prev;
3398 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
3399 // FIXME: Can we provide a note showing where this was declared?
3400 return true;
3401 }
3402
3403 // Instantiate static data member.
3404 // FIXME: Note that this is an explicit instantiation.
3405 if (TSK == TSK_ExplicitInstantiationDefinition)
3406 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false);
3407
3408 // FIXME: Create an ExplicitInstantiation node?
3409 return DeclPtrTy();
3410 }
3411
Douglas Gregord90fd522009-09-25 21:45:23 +00003412 // Translate the parser's template argument list in our AST format.
3413 bool HasExplicitTemplateArgs = false;
3414 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3415 if (D.getKind() == Declarator::DK_TemplateId) {
3416 TemplateIdAnnotation *TemplateId = D.getTemplateId();
3417 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3418 TemplateId->getTemplateArgs(),
3419 TemplateId->getTemplateArgIsType(),
3420 TemplateId->NumArgs);
3421 translateTemplateArguments(TemplateArgsPtr,
3422 TemplateId->getTemplateArgLocations(),
3423 TemplateArgs);
3424 HasExplicitTemplateArgs = true;
3425 }
3426
3427
Douglas Gregor450f00842009-09-25 18:43:00 +00003428 // C++ [temp.explicit]p1:
3429 // A [...] function [...] can be explicitly instantiated from its template.
3430 // A member function [...] of a class template can be explicitly
3431 // instantiated from the member definition associated with its class
3432 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00003433 llvm::SmallVector<FunctionDecl *, 8> Matches;
3434 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3435 P != PEnd; ++P) {
3436 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00003437 if (!HasExplicitTemplateArgs) {
3438 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
3439 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
3440 Matches.clear();
3441 Matches.push_back(Method);
3442 break;
3443 }
Douglas Gregor450f00842009-09-25 18:43:00 +00003444 }
3445 }
3446
3447 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
3448 if (!FunTmpl)
3449 continue;
3450
3451 TemplateDeductionInfo Info(Context);
3452 FunctionDecl *Specialization = 0;
3453 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00003454 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3455 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00003456 R, Specialization, Info)) {
3457 // FIXME: Keep track of almost-matches?
3458 (void)TDK;
3459 continue;
3460 }
3461
3462 Matches.push_back(Specialization);
3463 }
3464
3465 // Find the most specialized function template specialization.
3466 FunctionDecl *Specialization
3467 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
3468 D.getIdentifierLoc(),
3469 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
3470 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
3471 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
3472
3473 if (!Specialization)
3474 return true;
3475
3476 switch (Specialization->getTemplateSpecializationKind()) {
3477 case TSK_Undeclared:
3478 Diag(D.getIdentifierLoc(),
3479 diag::err_explicit_instantiation_member_function_not_instantiated)
3480 << Specialization
3481 << (Specialization->getTemplateSpecializationKind() ==
3482 TSK_ExplicitSpecialization);
3483 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
3484 return true;
3485
3486 case TSK_ExplicitSpecialization:
3487 // C++ [temp.explicit]p4:
3488 // For a given set of template parameters, if an explicit instantiation
3489 // of a template appears after a declaration of an explicit
3490 // specialization for that template, the explicit instantiation has no
3491 // effect.
3492 break;
3493
3494 case TSK_ExplicitInstantiationDefinition:
3495 // FIXME: Check that we aren't trying to perform an explicit instantiation
3496 // declaration now.
3497 // Fall through
3498
3499 case TSK_ImplicitInstantiation:
3500 case TSK_ExplicitInstantiationDeclaration:
3501 // Instantiate the function, if this is an explicit instantiation
3502 // definition.
3503 if (TSK == TSK_ExplicitInstantiationDefinition)
3504 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
3505 false);
3506
3507 // FIXME: setTemplateSpecializationKind doesn't (yet) work for
3508 // non-templated member functions.
3509 if (!Specialization->getPrimaryTemplate())
3510 break;
3511
3512 Specialization->setTemplateSpecializationKind(TSK);
3513 break;
3514 }
3515
3516 // FIXME: Create some kind of ExplicitInstantiationDecl here.
3517 return DeclPtrTy();
3518}
3519
Douglas Gregor333489b2009-03-27 23:10:48 +00003520Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00003521Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3522 const CXXScopeSpec &SS, IdentifierInfo *Name,
3523 SourceLocation TagLoc, SourceLocation NameLoc) {
3524 // This has to hold, because SS is expected to be defined.
3525 assert(Name && "Expected a name in a dependent tag");
3526
3527 NestedNameSpecifier *NNS
3528 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3529 if (!NNS)
3530 return true;
3531
3532 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
3533 if (T.isNull())
3534 return true;
3535
3536 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
3537 QualType ElabType = Context.getElaboratedType(T, TagKind);
3538
3539 return ElabType.getAsOpaquePtr();
3540}
3541
3542Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00003543Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3544 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00003545 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00003546 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3547 if (!NNS)
3548 return true;
3549
3550 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003551 if (T.isNull())
3552 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00003553 return T.getAsOpaquePtr();
3554}
3555
Douglas Gregordce2b622009-04-01 00:28:59 +00003556Sema::TypeResult
3557Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3558 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003559 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003560 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00003561 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00003562 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00003563 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00003564 assert(TemplateId && "Expected a template specialization type");
3565
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003566 if (computeDeclContext(SS, false)) {
3567 // If we can compute a declaration context, then the "typename"
3568 // keyword was superfluous. Just build a QualifiedNameType to keep
3569 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00003570
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003571 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
3572 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
3573 }
Mike Stump11289f42009-09-09 15:08:12 +00003574
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003575 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00003576}
3577
Douglas Gregor333489b2009-03-27 23:10:48 +00003578/// \brief Build the type that describes a C++ typename specifier,
3579/// e.g., "typename T::type".
3580QualType
3581Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
3582 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003583 CXXRecordDecl *CurrentInstantiation = 0;
3584 if (NNS->isDependent()) {
3585 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00003586
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003587 // If the nested-name-specifier does not refer to the current
3588 // instantiation, then build a typename type.
3589 if (!CurrentInstantiation)
3590 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00003591
Douglas Gregorc707da62009-09-02 13:12:51 +00003592 // The nested-name-specifier refers to the current instantiation, so the
3593 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00003594 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00003595 // extraneous "typename" keywords, and we retroactively apply this DR to
3596 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003597 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003598
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003599 DeclContext *Ctx = 0;
3600
3601 if (CurrentInstantiation)
3602 Ctx = CurrentInstantiation;
3603 else {
3604 CXXScopeSpec SS;
3605 SS.setScopeRep(NNS);
3606 SS.setRange(Range);
3607 if (RequireCompleteDeclContext(SS))
3608 return QualType();
3609
3610 Ctx = computeDeclContext(SS);
3611 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003612 assert(Ctx && "No declaration context?");
3613
3614 DeclarationName Name(&II);
Mike Stump11289f42009-09-09 15:08:12 +00003615 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
Douglas Gregor333489b2009-03-27 23:10:48 +00003616 false);
3617 unsigned DiagID = 0;
3618 Decl *Referenced = 0;
3619 switch (Result.getKind()) {
3620 case LookupResult::NotFound:
3621 if (Ctx->isTranslationUnit())
3622 DiagID = diag::err_typename_nested_not_found_global;
3623 else
3624 DiagID = diag::err_typename_nested_not_found;
3625 break;
3626
3627 case LookupResult::Found:
3628 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3629 // We found a type. Build a QualifiedNameType, since the
3630 // typename-specifier was just sugar. FIXME: Tell
3631 // QualifiedNameType that it has a "typename" prefix.
3632 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3633 }
3634
3635 DiagID = diag::err_typename_nested_not_type;
3636 Referenced = Result.getAsDecl();
3637 break;
3638
3639 case LookupResult::FoundOverloaded:
3640 DiagID = diag::err_typename_nested_not_type;
3641 Referenced = *Result.begin();
3642 break;
3643
3644 case LookupResult::AmbiguousBaseSubobjectTypes:
3645 case LookupResult::AmbiguousBaseSubobjects:
3646 case LookupResult::AmbiguousReference:
3647 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3648 return QualType();
3649 }
3650
3651 // If we get here, it's because name lookup did not find a
3652 // type. Emit an appropriate diagnostic and return an error.
3653 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3654 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3655 else
3656 Diag(Range.getEnd(), DiagID) << Range << Name;
3657 if (Referenced)
3658 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3659 << Name;
3660 return QualType();
3661}
Douglas Gregor15acfb92009-08-06 16:20:37 +00003662
3663namespace {
3664 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00003665 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3666 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00003667 SourceLocation Loc;
3668 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00003669
Douglas Gregor15acfb92009-08-06 16:20:37 +00003670 public:
Mike Stump11289f42009-09-09 15:08:12 +00003671 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00003672 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003673 DeclarationName Entity)
3674 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00003675 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00003676
3677 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00003678 /// transformed.
3679 ///
3680 /// For the purposes of type reconstruction, a type has already been
3681 /// transformed if it is NULL or if it is not dependent.
3682 bool AlreadyTransformed(QualType T) {
3683 return T.isNull() || !T->isDependentType();
3684 }
Mike Stump11289f42009-09-09 15:08:12 +00003685
3686 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00003687 /// rebuilt.
3688 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00003689
Douglas Gregor15acfb92009-08-06 16:20:37 +00003690 /// \brief Returns the name of the entity whose type is being rebuilt.
3691 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00003692
Douglas Gregor15acfb92009-08-06 16:20:37 +00003693 /// \brief Transforms an expression by returning the expression itself
3694 /// (an identity function).
3695 ///
3696 /// FIXME: This is completely unsafe; we will need to actually clone the
3697 /// expressions.
3698 Sema::OwningExprResult TransformExpr(Expr *E) {
3699 return getSema().Owned(E);
3700 }
Mike Stump11289f42009-09-09 15:08:12 +00003701
Douglas Gregor15acfb92009-08-06 16:20:37 +00003702 /// \brief Transforms a typename type by determining whether the type now
3703 /// refers to a member of the current instantiation, and then
3704 /// type-checking and building a QualifiedNameType (when possible).
3705 QualType TransformTypenameType(const TypenameType *T);
3706 };
3707}
3708
Mike Stump11289f42009-09-09 15:08:12 +00003709QualType
Douglas Gregor15acfb92009-08-06 16:20:37 +00003710CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3711 NestedNameSpecifier *NNS
3712 = TransformNestedNameSpecifier(T->getQualifier(),
3713 /*FIXME:*/SourceRange(getBaseLocation()));
3714 if (!NNS)
3715 return QualType();
3716
3717 // If the nested-name-specifier did not change, and we cannot compute the
3718 // context corresponding to the nested-name-specifier, then this
3719 // typename type will not change; exit early.
3720 CXXScopeSpec SS;
3721 SS.setRange(SourceRange(getBaseLocation()));
3722 SS.setScopeRep(NNS);
3723 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3724 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003725
3726 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00003727 // QualifiedNameType.
3728 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00003729 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00003730 = TransformType(QualType(TemplateId, 0));
3731 if (NewTemplateId.isNull())
3732 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003733
Douglas Gregor15acfb92009-08-06 16:20:37 +00003734 if (NNS == T->getQualifier() &&
3735 NewTemplateId == QualType(TemplateId, 0))
3736 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003737
Douglas Gregor15acfb92009-08-06 16:20:37 +00003738 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3739 }
Mike Stump11289f42009-09-09 15:08:12 +00003740
Douglas Gregor15acfb92009-08-06 16:20:37 +00003741 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3742}
3743
3744/// \brief Rebuilds a type within the context of the current instantiation.
3745///
Mike Stump11289f42009-09-09 15:08:12 +00003746/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00003747/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00003748/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00003749/// partial specialization thereof). This routine will rebuild that type now
3750/// that we have entered the declarator's scope, which may produce different
3751/// canonical types, e.g.,
3752///
3753/// \code
3754/// template<typename T>
3755/// struct X {
3756/// typedef T* pointer;
3757/// pointer data();
3758/// };
3759///
3760/// template<typename T>
3761/// typename X<T>::pointer X<T>::data() { ... }
3762/// \endcode
3763///
3764/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3765/// since we do not know that we can look into X<T> when we parsed the type.
3766/// This function will rebuild the type, performing the lookup of "pointer"
3767/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3768/// as the canonical type of T*, allowing the return types of the out-of-line
3769/// definition and the declaration to match.
3770QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3771 DeclarationName Name) {
3772 if (T.isNull() || !T->isDependentType())
3773 return T;
Mike Stump11289f42009-09-09 15:08:12 +00003774
Douglas Gregor15acfb92009-08-06 16:20:37 +00003775 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3776 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00003777}
Douglas Gregorbe999392009-09-15 16:23:51 +00003778
3779/// \brief Produces a formatted string that describes the binding of
3780/// template parameters to template arguments.
3781std::string
3782Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3783 const TemplateArgumentList &Args) {
3784 std::string Result;
3785
3786 if (!Params || Params->size() == 0)
3787 return Result;
3788
3789 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3790 if (I == 0)
3791 Result += "[with ";
3792 else
3793 Result += ", ";
3794
3795 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
3796 Result += Id->getName();
3797 } else {
3798 Result += '$';
3799 Result += llvm::utostr(I);
3800 }
3801
3802 Result += " = ";
3803
3804 switch (Args[I].getKind()) {
3805 case TemplateArgument::Null:
3806 Result += "<no value>";
3807 break;
3808
3809 case TemplateArgument::Type: {
3810 std::string TypeStr;
3811 Args[I].getAsType().getAsStringInternal(TypeStr,
3812 Context.PrintingPolicy);
3813 Result += TypeStr;
3814 break;
3815 }
3816
3817 case TemplateArgument::Declaration: {
3818 bool Unnamed = true;
3819 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
3820 if (ND->getDeclName()) {
3821 Unnamed = false;
3822 Result += ND->getNameAsString();
3823 }
3824 }
3825
3826 if (Unnamed) {
3827 Result += "<anonymous>";
3828 }
3829 break;
3830 }
3831
3832 case TemplateArgument::Integral: {
3833 Result += Args[I].getAsIntegral()->toString(10);
3834 break;
3835 }
3836
3837 case TemplateArgument::Expression: {
3838 assert(false && "No expressions in deduced template arguments!");
3839 Result += "<expression>";
3840 break;
3841 }
3842
3843 case TemplateArgument::Pack:
3844 // FIXME: Format template argument packs
3845 Result += "<template argument pack>";
3846 break;
3847 }
3848 }
3849
3850 Result += ']';
3851 return Result;
3852}