blob: 509237a855a786759dd93c51e307f9110abed80e [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 Gregor15acfb92009-08-06 16:20:37 +000020#include "llvm/Support/Compiler.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000021#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022using namespace clang;
23
Douglas Gregorb7bfe792009-09-02 22:59:36 +000024/// \brief Determine whether the declaration found is acceptable as the name
25/// of a template and, if so, return that template declaration. Otherwise,
26/// returns NULL.
27static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
28 if (!D)
29 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000030
Douglas Gregorb7bfe792009-09-02 22:59:36 +000031 if (isa<TemplateDecl>(D))
32 return D;
Mike Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
35 // C++ [temp.local]p1:
36 // Like normal (non-template) classes, class templates have an
37 // injected-class-name (Clause 9). The injected-class-name
38 // can be used with or without a template-argument-list. When
39 // it is used without a template-argument-list, it is
40 // equivalent to the injected-class-name followed by the
41 // template-parameters of the class template enclosed in
42 // <>. When it is used with a template-argument-list, it
43 // refers to the specified class template specialization,
44 // which could be the current specialization or another
45 // specialization.
46 if (Record->isInjectedClassName()) {
47 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
48 if (Record->getDescribedClassTemplate())
49 return Record->getDescribedClassTemplate();
50
51 if (ClassTemplateSpecializationDecl *Spec
52 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
53 return Spec->getSpecializedTemplate();
54 }
Mike Stump11289f42009-09-09 15:08:12 +000055
Douglas Gregorb7bfe792009-09-02 22:59:36 +000056 return 0;
57 }
Mike Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregorb7bfe792009-09-02 22:59:36 +000059 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
60 if (!Ovl)
61 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000062
Douglas Gregorb7bfe792009-09-02 22:59:36 +000063 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
64 FEnd = Ovl->function_end();
65 F != FEnd; ++F) {
66 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
67 // We've found a function template. Determine whether there are
68 // any other function templates we need to bundle together in an
69 // OverloadedFunctionDecl
70 for (++F; F != FEnd; ++F) {
71 if (isa<FunctionTemplateDecl>(*F))
72 break;
73 }
Mike Stump11289f42009-09-09 15:08:12 +000074
Douglas Gregorb7bfe792009-09-02 22:59:36 +000075 if (F != FEnd) {
76 // Build an overloaded function decl containing only the
77 // function templates in Ovl.
Mike Stump11289f42009-09-09 15:08:12 +000078 OverloadedFunctionDecl *OvlTemplate
Douglas Gregorb7bfe792009-09-02 22:59:36 +000079 = OverloadedFunctionDecl::Create(Context,
80 Ovl->getDeclContext(),
81 Ovl->getDeclName());
82 OvlTemplate->addOverload(FuncTmpl);
83 OvlTemplate->addOverload(*F);
84 for (++F; F != FEnd; ++F) {
85 if (isa<FunctionTemplateDecl>(*F))
86 OvlTemplate->addOverload(*F);
87 }
Mike Stump11289f42009-09-09 15:08:12 +000088
Douglas Gregorb7bfe792009-09-02 22:59:36 +000089 return OvlTemplate;
90 }
91
92 return FuncTmpl;
93 }
94 }
Mike Stump11289f42009-09-09 15:08:12 +000095
Douglas Gregorb7bfe792009-09-02 22:59:36 +000096 return 0;
97}
98
99TemplateNameKind Sema::isTemplateName(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +0000100 const IdentifierInfo &II,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000101 SourceLocation IdLoc,
Douglas Gregore861bac2009-08-25 22:51:20 +0000102 const CXXScopeSpec *SS,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000103 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000104 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000105 TemplateTy &TemplateResult) {
106 // Determine where to perform name lookup
107 DeclContext *LookupCtx = 0;
108 bool isDependent = false;
109 if (ObjectTypePtr) {
110 // This nested-name-specifier occurs in a member access expression, e.g.,
111 // x->B::f, and we are looking into the type of the object.
Mike Stump11289f42009-09-09 15:08:12 +0000112 assert((!SS || !SS->isSet()) &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000113 "ObjectType and scope specifier cannot coexist");
114 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
115 LookupCtx = computeDeclContext(ObjectType);
116 isDependent = ObjectType->isDependentType();
117 } else if (SS && SS->isSet()) {
118 // This nested-name-specifier occurs after another nested-name-specifier,
119 // so long into the context associated with the prior nested-name-specifier.
120
121 LookupCtx = computeDeclContext(*SS, EnteringContext);
122 isDependent = isDependentScopeSpecifier(*SS);
123 }
Mike Stump11289f42009-09-09 15:08:12 +0000124
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000125 LookupResult Found;
126 bool ObjectTypeSearchedInScope = false;
127 if (LookupCtx) {
128 // Perform "qualified" name lookup into the declaration context we
129 // computed, which is either the type of the base of a member access
Mike Stump11289f42009-09-09 15:08:12 +0000130 // expression or the declaration context associated with a prior
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000131 // nested-name-specifier.
132
133 // The declaration context must be complete.
134 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
135 return TNK_Non_template;
Mike Stump11289f42009-09-09 15:08:12 +0000136
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000137 Found = LookupQualifiedName(LookupCtx, &II, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +0000138
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000139 if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
140 // C++ [basic.lookup.classref]p1:
141 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump11289f42009-09-09 15:08:12 +0000142 // immediately followed by an identifier followed by a <, the
143 // identifier must be looked up to determine whether the < is the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000144 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump11289f42009-09-09 15:08:12 +0000145 // The identifier is first looked up in the class of the object
146 // expression. If the identifier is not found, it is then looked up in
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000147 // the context of the entire postfix-expression and shall name a class
148 // or function template.
149 //
150 // FIXME: When we're instantiating a template, do we actually have to
151 // look in the scope of the template? Seems fishy...
152 Found = LookupName(S, &II, LookupOrdinaryName);
153 ObjectTypeSearchedInScope = true;
154 }
155 } else if (isDependent) {
Mike Stump11289f42009-09-09 15:08:12 +0000156 // We cannot look into a dependent object type or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000157 return TNK_Non_template;
158 } else {
159 // Perform unqualified name lookup in the current scope.
160 Found = LookupName(S, &II, LookupOrdinaryName);
161 }
Mike Stump11289f42009-09-09 15:08:12 +0000162
Douglas Gregore861bac2009-08-25 22:51:20 +0000163 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump11289f42009-09-09 15:08:12 +0000164 assert(!Found.isAmbiguous() &&
Douglas Gregore861bac2009-08-25 22:51:20 +0000165 "Cannot handle template name-lookup ambiguities");
Douglas Gregordc572a32009-03-30 22:58:21 +0000166
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000167 NamedDecl *Template = isAcceptableTemplateName(Context, Found);
168 if (!Template)
169 return TNK_Non_template;
170
171 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
172 // C++ [basic.lookup.classref]p1:
Mike Stump11289f42009-09-09 15:08:12 +0000173 // [...] If the lookup in the class of the object expression finds a
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000174 // template, the name is also looked up in the context of the entire
175 // postfix-expression and [...]
176 //
177 LookupResult FoundOuter = LookupName(S, &II, LookupOrdinaryName);
178 // FIXME: Handle ambiguities in this lookup better
179 NamedDecl *OuterTemplate = isAcceptableTemplateName(Context, FoundOuter);
Mike Stump11289f42009-09-09 15:08:12 +0000180
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000181 if (!OuterTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +0000182 // - if the name is not found, the name found in the class of the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000183 // object expression is used, otherwise
184 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump11289f42009-09-09 15:08:12 +0000185 // - if the name is found in the context of the entire
186 // postfix-expression and does not name a class template, the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000187 // found in the class of the object expression is used, otherwise
188 } else {
189 // - if the name found is a class template, it must refer to the same
Mike Stump11289f42009-09-09 15:08:12 +0000190 // entity as the one found in the class of the object expression,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000191 // otherwise the program is ill-formed.
192 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
193 Diag(IdLoc, diag::err_nested_name_member_ref_lookup_ambiguous)
194 << &II;
195 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
196 << QualType::getFromOpaquePtr(ObjectTypePtr);
197 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump11289f42009-09-09 15:08:12 +0000198
199 // Recover by taking the template that we found in the object
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000200 // expression's type.
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000201 }
Mike Stump11289f42009-09-09 15:08:12 +0000202 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000203 }
Mike Stump11289f42009-09-09 15:08:12 +0000204
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000205 if (SS && SS->isSet() && !SS->isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000206 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000207 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000208 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000209 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000210 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000211 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
212 Ovl));
213 else
Mike Stump11289f42009-09-09 15:08:12 +0000214 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000215 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000216 cast<TemplateDecl>(Template)));
217 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000218 = dyn_cast<OverloadedFunctionDecl>(Template)) {
219 TemplateResult = TemplateTy::make(TemplateName(Ovl));
220 } else {
221 TemplateResult = TemplateTy::make(
222 TemplateName(cast<TemplateDecl>(Template)));
223 }
Mike Stump11289f42009-09-09 15:08:12 +0000224
225 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000226 isa<TemplateTemplateParmDecl>(Template))
227 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000228
229 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000230 isa<OverloadedFunctionDecl>(Template)) &&
231 "Unhandled template kind in Sema::isTemplateName");
232 return TNK_Function_template;
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000233}
234
Douglas Gregor5101c242008-12-05 18:15:24 +0000235/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
236/// that the template parameter 'PrevDecl' is being shadowed by a new
237/// declaration at location Loc. Returns true to indicate that this is
238/// an error, and false otherwise.
239bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000240 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000241
242 // Microsoft Visual C++ permits template parameters to be shadowed.
243 if (getLangOptions().Microsoft)
244 return false;
245
246 // C++ [temp.local]p4:
247 // A template-parameter shall not be redeclared within its
248 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000249 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000250 << cast<NamedDecl>(PrevDecl)->getDeclName();
251 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
252 return true;
253}
254
Douglas Gregor463421d2009-03-03 04:44:36 +0000255/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000256/// the parameter D to reference the templated declaration and return a pointer
257/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000258TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
259 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
260 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000261 return Temp;
262 }
263 return 0;
264}
265
Douglas Gregor5101c242008-12-05 18:15:24 +0000266/// ActOnTypeParameter - Called when a C++ template type parameter
267/// (e.g., "typename T") has been parsed. Typename specifies whether
268/// the keyword "typename" was used to declare the type parameter
269/// (otherwise, "class" was used), and KeyLoc is the location of the
270/// "class" or "typename" keyword. ParamName is the name of the
271/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000272/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000273/// If the type parameter has a default argument, it will be added
274/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000275Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000276 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000277 SourceLocation KeyLoc,
278 IdentifierInfo *ParamName,
279 SourceLocation ParamNameLoc,
280 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000281 assert(S->isTemplateParamScope() &&
282 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000283 bool Invalid = false;
284
285 if (ParamName) {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000286 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000287 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000288 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000289 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000290 }
291
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000292 SourceLocation Loc = ParamNameLoc;
293 if (!ParamName)
294 Loc = KeyLoc;
295
Douglas Gregor5101c242008-12-05 18:15:24 +0000296 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000297 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
298 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000299 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000300 if (Invalid)
301 Param->setInvalidDecl();
302
303 if (ParamName) {
304 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000305 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000306 IdResolver.AddDecl(Param);
307 }
308
Chris Lattner83f095c2009-03-28 19:18:32 +0000309 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000310}
311
Douglas Gregordba32632009-02-10 19:49:53 +0000312/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000313/// Default) to the given template type parameter (TypeParam).
314void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000315 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000316 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000317 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000318 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000319 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000320 // FIXME: Preserve type source info.
321 QualType Default = GetTypeFromParser(DefaultT);
Douglas Gregordba32632009-02-10 19:49:53 +0000322
Anders Carlssond3824352009-06-12 22:30:13 +0000323 // C++0x [temp.param]p9:
324 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000325 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000326 if (Parm->isParameterPack()) {
327 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000328 return;
329 }
Mike Stump11289f42009-09-09 15:08:12 +0000330
Douglas Gregordba32632009-02-10 19:49:53 +0000331 // C++ [temp.param]p14:
332 // A template-parameter shall not be used in its own default argument.
333 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000334
Douglas Gregordba32632009-02-10 19:49:53 +0000335 // Check the template argument itself.
336 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
337 Parm->setInvalidDecl();
338 return;
339 }
340
341 Parm->setDefaultArgument(Default, DefaultLoc, false);
342}
343
Douglas Gregor463421d2009-03-03 04:44:36 +0000344/// \brief Check that the type of a non-type template parameter is
345/// well-formed.
346///
347/// \returns the (possibly-promoted) parameter type if valid;
348/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000349QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000350Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
351 // C++ [temp.param]p4:
352 //
353 // A non-type template-parameter shall have one of the following
354 // (optionally cv-qualified) types:
355 //
356 // -- integral or enumeration type,
357 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000358 // -- pointer to object or pointer to function,
359 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000360 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
361 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000362 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000363 T->isReferenceType() ||
364 // -- pointer to member.
365 T->isMemberPointerType() ||
366 // If T is a dependent type, we can't do the check now, so we
367 // assume that it is well-formed.
368 T->isDependentType())
369 return T;
370 // C++ [temp.param]p8:
371 //
372 // A non-type template-parameter of type "array of T" or
373 // "function returning T" is adjusted to be of type "pointer to
374 // T" or "pointer to function returning T", respectively.
375 else if (T->isArrayType())
376 // FIXME: Keep the type prior to promotion?
377 return Context.getArrayDecayedType(T);
378 else if (T->isFunctionType())
379 // FIXME: Keep the type prior to promotion?
380 return Context.getPointerType(T);
381
382 Diag(Loc, diag::err_template_nontype_parm_bad_type)
383 << T;
384
385 return QualType();
386}
387
Douglas Gregor5101c242008-12-05 18:15:24 +0000388/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
389/// template parameter (e.g., "int Size" in "template<int Size>
390/// class Array") has been parsed. S is the current scope and D is
391/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000392Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000393 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000394 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000395 DeclaratorInfo *DInfo = 0;
396 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000397
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000398 assert(S->isTemplateParamScope() &&
399 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000400 bool Invalid = false;
401
402 IdentifierInfo *ParamName = D.getIdentifier();
403 if (ParamName) {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000404 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000405 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000406 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000407 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000408 }
409
Douglas Gregor463421d2009-03-03 04:44:36 +0000410 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000411 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000412 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000413 Invalid = true;
414 }
Douglas Gregor81338792009-02-10 17:43:50 +0000415
Douglas Gregor5101c242008-12-05 18:15:24 +0000416 NonTypeTemplateParmDecl *Param
417 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000418 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000419 if (Invalid)
420 Param->setInvalidDecl();
421
422 if (D.getIdentifier()) {
423 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000424 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000425 IdResolver.AddDecl(Param);
426 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000427 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000428}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000429
Douglas Gregordba32632009-02-10 19:49:53 +0000430/// \brief Adds a default argument to the given non-type template
431/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000432void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000433 SourceLocation EqualLoc,
434 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000435 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000436 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000437 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000438
Douglas Gregordba32632009-02-10 19:49:53 +0000439 // C++ [temp.param]p14:
440 // A template-parameter shall not be used in its own default argument.
441 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000442
Douglas Gregordba32632009-02-10 19:49:53 +0000443 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000444 TemplateArgument Converted;
445 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
446 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000447 TemplateParm->setInvalidDecl();
448 return;
449 }
450
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000451 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000452}
453
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000454
455/// ActOnTemplateTemplateParameter - Called when a C++ template template
456/// parameter (e.g. T in template <template <typename> class T> class array)
457/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000458Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
459 SourceLocation TmpLoc,
460 TemplateParamsTy *Params,
461 IdentifierInfo *Name,
462 SourceLocation NameLoc,
463 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000464 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000465 assert(S->isTemplateParamScope() &&
466 "Template template parameter not in template parameter scope!");
467
468 // Construct the parameter object.
469 TemplateTemplateParmDecl *Param =
470 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
471 Position, Name,
472 (TemplateParameterList*)Params);
473
474 // Make sure the parameter is valid.
475 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
476 // do anything yet. However, if the template parameter list or (eventual)
477 // default value is ever invalidated, that will propagate here.
478 bool Invalid = false;
479 if (Invalid) {
480 Param->setInvalidDecl();
481 }
482
483 // If the tt-param has a name, then link the identifier into the scope
484 // and lookup mechanisms.
485 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000486 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000487 IdResolver.AddDecl(Param);
488 }
489
Chris Lattner83f095c2009-03-28 19:18:32 +0000490 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000491}
492
Douglas Gregordba32632009-02-10 19:49:53 +0000493/// \brief Adds a default argument to the given template template
494/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000495void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000496 SourceLocation EqualLoc,
497 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000498 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000499 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000500
501 // Since a template-template parameter's default argument is an
502 // id-expression, it must be a DeclRefExpr.
Mike Stump11289f42009-09-09 15:08:12 +0000503 DeclRefExpr *Default
Douglas Gregordba32632009-02-10 19:49:53 +0000504 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
505
506 // C++ [temp.param]p14:
507 // A template-parameter shall not be used in its own default argument.
508 // FIXME: Implement this check! Needs a recursive walk over the types.
509
510 // Check the well-formedness of the template argument.
511 if (!isa<TemplateDecl>(Default->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +0000512 Diag(Default->getSourceRange().getBegin(),
Douglas Gregordba32632009-02-10 19:49:53 +0000513 diag::err_template_arg_must_be_template)
514 << Default->getSourceRange();
515 TemplateParm->setInvalidDecl();
516 return;
Mike Stump11289f42009-09-09 15:08:12 +0000517 }
Douglas Gregordba32632009-02-10 19:49:53 +0000518 if (CheckTemplateArgument(TemplateParm, Default)) {
519 TemplateParm->setInvalidDecl();
520 return;
521 }
522
523 DefaultE.release();
524 TemplateParm->setDefaultArgument(Default);
525}
526
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000527/// ActOnTemplateParameterList - Builds a TemplateParameterList that
528/// contains the template parameters in Params/NumParams.
529Sema::TemplateParamsTy *
530Sema::ActOnTemplateParameterList(unsigned Depth,
531 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000532 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000533 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000534 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000535 SourceLocation RAngleLoc) {
536 if (ExportLoc.isValid())
537 Diag(ExportLoc, diag::note_template_export_unsupported);
538
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000539 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000540 (NamedDecl**)Params, NumParams,
541 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000542}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000543
Douglas Gregorc08f4892009-03-25 00:13:59 +0000544Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000545Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000546 SourceLocation KWLoc, const CXXScopeSpec &SS,
547 IdentifierInfo *Name, SourceLocation NameLoc,
548 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000549 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000550 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000551 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000552 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000553 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000554 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000555
556 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000557 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000558 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000559
John McCall27b5c252009-09-14 21:59:20 +0000560 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
561 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000562
563 // There is no such thing as an unnamed class template.
564 if (!Name) {
565 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000566 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000567 }
568
569 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000570 DeclContext *SemanticContext;
571 LookupResult Previous;
572 if (SS.isNotEmpty() && !SS.isInvalid()) {
573 SemanticContext = computeDeclContext(SS, true);
574 if (!SemanticContext) {
575 // FIXME: Produce a reasonable diagnostic here
576 return true;
577 }
Mike Stump11289f42009-09-09 15:08:12 +0000578
579 Previous = LookupQualifiedName(SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000580 true);
581 } else {
582 SemanticContext = CurContext;
583 Previous = LookupName(S, Name, LookupOrdinaryName, true);
584 }
Mike Stump11289f42009-09-09 15:08:12 +0000585
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000586 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
587 NamedDecl *PrevDecl = 0;
588 if (Previous.begin() != Previous.end())
589 PrevDecl = *Previous.begin();
590
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000591 if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000592 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000593
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000594 // If there is a previous declaration with the same name, check
595 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000596 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000597 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
598 if (PrevClassTemplate) {
599 // Ensure that the template parameter lists are compatible.
600 if (!TemplateParameterListsAreEqual(TemplateParams,
601 PrevClassTemplate->getTemplateParameters(),
602 /*Complain=*/true))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000603 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000604
605 // C++ [temp.class]p4:
606 // In a redeclaration, partial specialization, explicit
607 // specialization or explicit instantiation of a class template,
608 // the class-key shall agree in kind with the original class
609 // template declaration (7.1.5.3).
610 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000611 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000612 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000613 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000614 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000615 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000616 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000617 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000618 }
619
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000620 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000621 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000622 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
623 Diag(NameLoc, diag::err_redefinition) << Name;
624 Diag(Def->getLocation(), diag::note_previous_definition);
625 // FIXME: Would it make sense to try to "forget" the previous
626 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000627 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000628 }
629 }
630 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
631 // Maybe we will complain about the shadowed template parameter.
632 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
633 // Just pretend that we didn't see the previous declaration.
634 PrevDecl = 0;
635 } else if (PrevDecl) {
636 // C++ [temp]p5:
637 // A class template shall not have the same name as any other
638 // template, class, function, object, enumeration, enumerator,
639 // namespace, or type in the same scope (3.3), except as specified
640 // in (14.5.4).
641 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
642 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000643 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000644 }
645
Douglas Gregordba32632009-02-10 19:49:53 +0000646 // Check the template parameter list of this declaration, possibly
647 // merging in the template parameter list from the previous class
648 // template declaration.
649 if (CheckTemplateParameterList(TemplateParams,
650 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
651 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000652
Douglas Gregore362cea2009-05-10 22:57:19 +0000653 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000654 // declaration!
655
John McCall27b5c252009-09-14 21:59:20 +0000656 // If this is a friend declaration of an undeclared template,
657 // create the template in the innermost namespace scope.
658 if (TUK == TUK_Friend && !PrevClassTemplate) {
659 while (!SemanticContext->isFileContext())
660 SemanticContext = SemanticContext->getParent();
661 }
662
Mike Stump11289f42009-09-09 15:08:12 +0000663 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000664 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000665 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000666 PrevClassTemplate->getTemplatedDecl() : 0,
667 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000668
669 ClassTemplateDecl *NewTemplate
670 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
671 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000672 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000673 NewClass->setDescribedClassTemplate(NewTemplate);
674
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000675 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000676 QualType T =
677 Context.getTypeDeclType(NewClass,
678 PrevClassTemplate?
679 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000680 assert(T->isDependentType() && "Class template type is not dependent?");
681 (void)T;
682
Anders Carlsson137108d2009-03-26 01:24:28 +0000683 // Set the access specifier.
John McCall27b5c252009-09-14 21:59:20 +0000684 if (TUK == TUK_Friend)
685 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
686 PrevClassTemplate != NULL);
687 else
688 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000689
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000690 // Set the lexical context of these templates
691 NewClass->setLexicalDeclContext(CurContext);
692 NewTemplate->setLexicalDeclContext(CurContext);
693
John McCall9bb74a52009-07-31 02:45:11 +0000694 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000695 NewClass->startDefinition();
696
697 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000698 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000699
John McCall27b5c252009-09-14 21:59:20 +0000700 if (TUK != TUK_Friend)
701 PushOnScopeChains(NewTemplate, S);
702 else {
703 // We might be replacing an existing declaration in the lookup tables;
704 // if so, borrow its access specifier.
705 if (PrevClassTemplate)
706 NewTemplate->setAccess(PrevClassTemplate->getAccess());
707
708 // Friend templates are visible in fairly strange ways.
709 if (!CurContext->isDependentContext()) {
710 DeclContext *DC = SemanticContext->getLookupContext();
711 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
712 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
713 PushOnScopeChains(NewTemplate, EnclosingScope,
714 /* AddToContext = */ false);
715 }
716 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000717
Douglas Gregordba32632009-02-10 19:49:53 +0000718 if (Invalid) {
719 NewTemplate->setInvalidDecl();
720 NewClass->setInvalidDecl();
721 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000722 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000723}
724
Douglas Gregordba32632009-02-10 19:49:53 +0000725/// \brief Checks the validity of a template parameter list, possibly
726/// considering the template parameter list from a previous
727/// declaration.
728///
729/// If an "old" template parameter list is provided, it must be
730/// equivalent (per TemplateParameterListsAreEqual) to the "new"
731/// template parameter list.
732///
733/// \param NewParams Template parameter list for a new template
734/// declaration. This template parameter list will be updated with any
735/// default arguments that are carried through from the previous
736/// template parameter list.
737///
738/// \param OldParams If provided, template parameter list from a
739/// previous declaration of the same template. Default template
740/// arguments will be merged from the old template parameter list to
741/// the new template parameter list.
742///
743/// \returns true if an error occurred, false otherwise.
744bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
745 TemplateParameterList *OldParams) {
746 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000747
Douglas Gregordba32632009-02-10 19:49:53 +0000748 // C++ [temp.param]p10:
749 // The set of default template-arguments available for use with a
750 // template declaration or definition is obtained by merging the
751 // default arguments from the definition (if in scope) and all
752 // declarations in scope in the same way default function
753 // arguments are (8.3.6).
754 bool SawDefaultArgument = false;
755 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000756
Anders Carlsson327865d2009-06-12 23:20:15 +0000757 bool SawParameterPack = false;
758 SourceLocation ParameterPackLoc;
759
Mike Stumpc89c8e32009-02-11 23:03:27 +0000760 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000761 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000762 if (OldParams)
763 OldParam = OldParams->begin();
764
765 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
766 NewParamEnd = NewParams->end();
767 NewParam != NewParamEnd; ++NewParam) {
768 // Variables used to diagnose redundant default arguments
769 bool RedundantDefaultArg = false;
770 SourceLocation OldDefaultLoc;
771 SourceLocation NewDefaultLoc;
772
773 // Variables used to diagnose missing default arguments
774 bool MissingDefaultArg = false;
775
Anders Carlsson327865d2009-06-12 23:20:15 +0000776 // C++0x [temp.param]p11:
777 // If a template parameter of a class template is a template parameter pack,
778 // it must be the last template parameter.
779 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +0000780 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +0000781 diag::err_template_param_pack_must_be_last_template_parameter);
782 Invalid = true;
783 }
784
Douglas Gregordba32632009-02-10 19:49:53 +0000785 // Merge default arguments for template type parameters.
786 if (TemplateTypeParmDecl *NewTypeParm
787 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump11289f42009-09-09 15:08:12 +0000788 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000789 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000790
Anders Carlsson327865d2009-06-12 23:20:15 +0000791 if (NewTypeParm->isParameterPack()) {
792 assert(!NewTypeParm->hasDefaultArgument() &&
793 "Parameter packs can't have a default argument!");
794 SawParameterPack = true;
795 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000796 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000797 NewTypeParm->hasDefaultArgument()) {
798 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
799 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
800 SawDefaultArgument = true;
801 RedundantDefaultArg = true;
802 PreviousDefaultArgLoc = NewDefaultLoc;
803 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
804 // Merge the default argument from the old declaration to the
805 // new declaration.
806 SawDefaultArgument = true;
807 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
808 OldTypeParm->getDefaultArgumentLoc(),
809 true);
810 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
811 } else if (NewTypeParm->hasDefaultArgument()) {
812 SawDefaultArgument = true;
813 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
814 } else if (SawDefaultArgument)
815 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000816 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000817 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000818 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000819 NonTypeTemplateParmDecl *OldNonTypeParm
820 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000821 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000822 NewNonTypeParm->hasDefaultArgument()) {
823 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
824 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
825 SawDefaultArgument = true;
826 RedundantDefaultArg = true;
827 PreviousDefaultArgLoc = NewDefaultLoc;
828 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
829 // Merge the default argument from the old declaration to the
830 // new declaration.
831 SawDefaultArgument = true;
832 // FIXME: We need to create a new kind of "default argument"
833 // expression that points to a previous template template
834 // parameter.
835 NewNonTypeParm->setDefaultArgument(
836 OldNonTypeParm->getDefaultArgument());
837 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
838 } else if (NewNonTypeParm->hasDefaultArgument()) {
839 SawDefaultArgument = true;
840 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
841 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000842 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000843 } else {
Douglas Gregordba32632009-02-10 19:49:53 +0000844 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000845 TemplateTemplateParmDecl *NewTemplateParm
846 = cast<TemplateTemplateParmDecl>(*NewParam);
847 TemplateTemplateParmDecl *OldTemplateParm
848 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000849 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000850 NewTemplateParm->hasDefaultArgument()) {
851 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
852 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
853 SawDefaultArgument = true;
854 RedundantDefaultArg = true;
855 PreviousDefaultArgLoc = NewDefaultLoc;
856 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
857 // Merge the default argument from the old declaration to the
858 // new declaration.
859 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +0000860 // FIXME: We need to create a new kind of "default argument" expression
861 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +0000862 NewTemplateParm->setDefaultArgument(
863 OldTemplateParm->getDefaultArgument());
864 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
865 } else if (NewTemplateParm->hasDefaultArgument()) {
866 SawDefaultArgument = true;
867 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
868 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000869 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +0000870 }
871
872 if (RedundantDefaultArg) {
873 // C++ [temp.param]p12:
874 // A template-parameter shall not be given default arguments
875 // by two different declarations in the same scope.
876 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
877 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
878 Invalid = true;
879 } else if (MissingDefaultArg) {
880 // C++ [temp.param]p11:
881 // If a template-parameter has a default template-argument,
882 // all subsequent template-parameters shall have a default
883 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +0000884 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +0000885 diag::err_template_param_default_arg_missing);
886 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
887 Invalid = true;
888 }
889
890 // If we have an old template parameter list that we're merging
891 // in, move on to the next parameter.
892 if (OldParams)
893 ++OldParam;
894 }
895
896 return Invalid;
897}
Douglas Gregord32e0282009-02-09 23:23:08 +0000898
Mike Stump11289f42009-09-09 15:08:12 +0000899/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +0000900/// specifier, returning the template parameter list that applies to the
901/// name.
902///
903/// \param DeclStartLoc the start of the declaration that has a scope
904/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +0000905///
Douglas Gregord8d297c2009-07-21 23:53:31 +0000906/// \param SS the scope specifier that will be matched to the given template
907/// parameter lists. This scope specifier precedes a qualified name that is
908/// being declared.
909///
910/// \param ParamLists the template parameter lists, from the outermost to the
911/// innermost template parameter lists.
912///
913/// \param NumParamLists the number of template parameter lists in ParamLists.
914///
Mike Stump11289f42009-09-09 15:08:12 +0000915/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +0000916/// name that is preceded by the scope specifier @p SS. This template
917/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +0000918/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +0000919/// template specialization), or may be NULL (if we were's declaring isn't
920/// itself a template).
921TemplateParameterList *
922Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
923 const CXXScopeSpec &SS,
924 TemplateParameterList **ParamLists,
925 unsigned NumParamLists) {
Douglas Gregord8d297c2009-07-21 23:53:31 +0000926 // Find the template-ids that occur within the nested-name-specifier. These
927 // template-ids will match up with the template parameter lists.
928 llvm::SmallVector<const TemplateSpecializationType *, 4>
929 TemplateIdsInSpecifier;
930 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
931 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +0000932 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +0000933 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
934 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
935 if (!Template)
936 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +0000937
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000938 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +0000939 ClassTemplateSpecializationDecl *SpecDecl
940 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
941 // If the nested name specifier refers to an explicit specialization,
942 // we don't need a template<> header.
Douglas Gregor82e22862009-09-16 00:01:48 +0000943 // FIXME: revisit this approach once we cope with specializations
Douglas Gregor15301382009-07-30 17:40:51 +0000944 // properly.
Douglas Gregord8d297c2009-07-21 23:53:31 +0000945 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
946 continue;
947 }
Mike Stump11289f42009-09-09 15:08:12 +0000948
Douglas Gregord8d297c2009-07-21 23:53:31 +0000949 TemplateIdsInSpecifier.push_back(SpecType);
950 }
951 }
Mike Stump11289f42009-09-09 15:08:12 +0000952
Douglas Gregord8d297c2009-07-21 23:53:31 +0000953 // Reverse the list of template-ids in the scope specifier, so that we can
954 // more easily match up the template-ids and the template parameter lists.
955 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +0000956
Douglas Gregord8d297c2009-07-21 23:53:31 +0000957 SourceLocation FirstTemplateLoc = DeclStartLoc;
958 if (NumParamLists)
959 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000960
Douglas Gregord8d297c2009-07-21 23:53:31 +0000961 // Match the template-ids found in the specifier to the template parameter
962 // lists.
963 unsigned Idx = 0;
964 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
965 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +0000966 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
967 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +0000968 if (Idx >= NumParamLists) {
969 // We have a template-id without a corresponding template parameter
970 // list.
971 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +0000972 // FIXME: the location information here isn't great.
973 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +0000974 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +0000975 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +0000976 << SS.getRange();
977 } else {
978 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
979 << SS.getRange()
980 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
981 "template<> ");
982 }
983 return 0;
984 }
Mike Stump11289f42009-09-09 15:08:12 +0000985
Douglas Gregord8d297c2009-07-21 23:53:31 +0000986 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +0000987 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +0000988 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +0000989 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
990
Mike Stump11289f42009-09-09 15:08:12 +0000991 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +0000992 = dyn_cast<ClassTemplateDecl>(Template)) {
993 TemplateParameterList *ExpectedTemplateParams = 0;
994 // Is this template-id naming the primary template?
995 if (Context.hasSameType(TemplateId,
996 ClassTemplate->getInjectedClassNameType(Context)))
997 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
998 // ... or a partial specialization?
999 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1000 = ClassTemplate->findPartialSpecialization(TemplateId))
1001 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1002
1003 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001004 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001005 ExpectedTemplateParams,
1006 true);
Mike Stump11289f42009-09-09 15:08:12 +00001007 }
Douglas Gregor15301382009-07-30 17:40:51 +00001008 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001009 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001010 diag::err_template_param_list_matches_nontemplate)
1011 << TemplateId
1012 << ParamLists[Idx]->getSourceRange();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001013 }
Mike Stump11289f42009-09-09 15:08:12 +00001014
Douglas Gregord8d297c2009-07-21 23:53:31 +00001015 // If there were at least as many template-ids as there were template
1016 // parameter lists, then there are no template parameter lists remaining for
1017 // the declaration itself.
1018 if (Idx >= NumParamLists)
1019 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001020
Douglas Gregord8d297c2009-07-21 23:53:31 +00001021 // If there were too many template parameter lists, complain about that now.
1022 if (Idx != NumParamLists - 1) {
1023 while (Idx < NumParamLists - 1) {
Mike Stump11289f42009-09-09 15:08:12 +00001024 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001025 diag::err_template_spec_extra_headers)
1026 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1027 ParamLists[Idx]->getRAngleLoc());
1028 ++Idx;
1029 }
1030 }
Mike Stump11289f42009-09-09 15:08:12 +00001031
Douglas Gregord8d297c2009-07-21 23:53:31 +00001032 // Return the last template parameter list, which corresponds to the
1033 // entity being declared.
1034 return ParamLists[NumParamLists - 1];
1035}
1036
Douglas Gregorc40290e2009-03-09 23:48:35 +00001037/// \brief Translates template arguments as provided by the parser
1038/// into template arguments used by semantic analysis.
Mike Stump11289f42009-09-09 15:08:12 +00001039static void
1040translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001041 SourceLocation *TemplateArgLocs,
1042 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
1043 TemplateArgs.reserve(TemplateArgsIn.size());
1044
1045 void **Args = TemplateArgsIn.getArgs();
1046 bool *ArgIsType = TemplateArgsIn.getArgIsType();
1047 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
1048 TemplateArgs.push_back(
1049 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001050 //FIXME: Preserve type source info.
1051 Sema::GetTypeFromParser(Args[Arg]))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001052 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
1053 }
1054}
1055
Douglas Gregordc572a32009-03-30 22:58:21 +00001056QualType Sema::CheckTemplateIdType(TemplateName Name,
1057 SourceLocation TemplateLoc,
1058 SourceLocation LAngleLoc,
1059 const TemplateArgument *TemplateArgs,
1060 unsigned NumTemplateArgs,
1061 SourceLocation RAngleLoc) {
1062 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001063 if (!Template) {
1064 // The template name does not resolve to a template, so we just
1065 // build a dependent template-id type.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001066 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001067 NumTemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001068 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001069
Douglas Gregorc40290e2009-03-09 23:48:35 +00001070 // Check that the template argument list is well-formed for this
1071 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001072 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1073 NumTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001074 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001075 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001076 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001077 return QualType();
1078
Mike Stump11289f42009-09-09 15:08:12 +00001079 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001080 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001081 "Converted template argument list is too short!");
1082
1083 QualType CanonType;
1084
Douglas Gregordc572a32009-03-30 22:58:21 +00001085 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorc40290e2009-03-09 23:48:35 +00001086 TemplateArgs,
1087 NumTemplateArgs)) {
1088 // This class template specialization is a dependent
1089 // type. Therefore, its canonical type is another class template
1090 // specialization type that contains all of the converted
1091 // arguments in canonical form. This ensures that, e.g., A<T> and
1092 // A<T, T> have identical types when A is declared as:
1093 //
1094 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001095 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001096 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001097 Converted.getFlatArguments(),
1098 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001099
Douglas Gregora8e02e72009-07-28 23:00:59 +00001100 // FIXME: CanonType is not actually the canonical type, and unfortunately
1101 // it is a TemplateTypeSpecializationType that we will never use again.
1102 // In the future, we need to teach getTemplateSpecializationType to only
1103 // build the canonical type and return that to us.
1104 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001105 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001106 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001107 // Find the class template specialization declaration that
1108 // corresponds to these arguments.
1109 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001110 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001111 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001112 Converted.flatSize(),
1113 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001114 void *InsertPos = 0;
1115 ClassTemplateSpecializationDecl *Decl
1116 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1117 if (!Decl) {
1118 // This is the first time we have referenced this class template
1119 // specialization. Create the canonical declaration and add it to
1120 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001121 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001122 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001123 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001124 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001125 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001126 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1127 Decl->setLexicalDeclContext(CurContext);
1128 }
1129
1130 CanonType = Context.getTypeDeclType(Decl);
1131 }
Mike Stump11289f42009-09-09 15:08:12 +00001132
Douglas Gregorc40290e2009-03-09 23:48:35 +00001133 // Build the fully-sugared type for this class template
1134 // specialization, which refers back to the class template
1135 // specialization we created or found.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001136 //FIXME: Preserve type source info.
Douglas Gregordc572a32009-03-30 22:58:21 +00001137 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1138 NumTemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001139}
1140
Douglas Gregor67a65642009-02-17 23:15:12 +00001141Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001142Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001143 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001144 ASTTemplateArgsPtr TemplateArgsIn,
1145 SourceLocation *TemplateArgLocs,
John McCalld8fe9af2009-09-08 17:47:29 +00001146 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001147 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001148
Douglas Gregorc40290e2009-03-09 23:48:35 +00001149 // Translate the parser's template argument list in our AST format.
1150 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1151 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001152
Douglas Gregordc572a32009-03-30 22:58:21 +00001153 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +00001154 TemplateArgs.data(),
1155 TemplateArgs.size(),
Douglas Gregordc572a32009-03-30 22:58:21 +00001156 RAngleLoc);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001157 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001158
1159 if (Result.isNull())
1160 return true;
1161
John McCalld8fe9af2009-09-08 17:47:29 +00001162 return Result.getAsOpaquePtr();
1163}
John McCall06f6fe8d2009-09-04 01:14:41 +00001164
John McCalld8fe9af2009-09-08 17:47:29 +00001165Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1166 TagUseKind TUK,
1167 DeclSpec::TST TagSpec,
1168 SourceLocation TagLoc) {
1169 if (TypeResult.isInvalid())
1170 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001171
John McCalld8fe9af2009-09-08 17:47:29 +00001172 QualType Type = QualType::getFromOpaquePtr(TypeResult.get());
John McCall06f6fe8d2009-09-04 01:14:41 +00001173
John McCalld8fe9af2009-09-08 17:47:29 +00001174 // Verify the tag specifier.
1175 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001176
John McCalld8fe9af2009-09-08 17:47:29 +00001177 if (const RecordType *RT = Type->getAs<RecordType>()) {
1178 RecordDecl *D = RT->getDecl();
1179
1180 IdentifierInfo *Id = D->getIdentifier();
1181 assert(Id && "templated class must have an identifier");
1182
1183 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1184 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001185 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001186 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1187 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001188 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001189 }
1190 }
1191
John McCalld8fe9af2009-09-08 17:47:29 +00001192 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1193
1194 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001195}
1196
Douglas Gregora727cb92009-06-30 22:34:41 +00001197Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1198 SourceLocation TemplateNameLoc,
1199 SourceLocation LAngleLoc,
1200 const TemplateArgument *TemplateArgs,
1201 unsigned NumTemplateArgs,
1202 SourceLocation RAngleLoc) {
1203 // FIXME: Can we do any checking at this point? I guess we could check the
1204 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001205 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001206 // though.
Mike Stump11289f42009-09-09 15:08:12 +00001207 return Owned(TemplateIdRefExpr::Create(Context,
Douglas Gregora727cb92009-06-30 22:34:41 +00001208 /*FIXME: New type?*/Context.OverloadTy,
1209 /*FIXME: Necessary?*/0,
1210 /*FIXME: Necessary?*/SourceRange(),
1211 Template, TemplateNameLoc, LAngleLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001212 TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001213 NumTemplateArgs, RAngleLoc));
1214}
1215
1216Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1217 SourceLocation TemplateNameLoc,
1218 SourceLocation LAngleLoc,
1219 ASTTemplateArgsPtr TemplateArgsIn,
1220 SourceLocation *TemplateArgLocs,
1221 SourceLocation RAngleLoc) {
1222 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001223
Douglas Gregora727cb92009-06-30 22:34:41 +00001224 // Translate the parser's template argument list in our AST format.
1225 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1226 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001227 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001228
Douglas Gregora727cb92009-06-30 22:34:41 +00001229 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1230 TemplateArgs.data(), TemplateArgs.size(),
1231 RAngleLoc);
1232}
1233
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001234Sema::OwningExprResult
1235Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base,
1236 SourceLocation OpLoc,
1237 tok::TokenKind OpKind,
1238 const CXXScopeSpec &SS,
1239 TemplateTy TemplateD,
1240 SourceLocation TemplateNameLoc,
1241 SourceLocation LAngleLoc,
1242 ASTTemplateArgsPtr TemplateArgsIn,
1243 SourceLocation *TemplateArgLocs,
1244 SourceLocation RAngleLoc) {
1245 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001246
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001247 // FIXME: We're going to end up looking up the template based on its name,
1248 // twice!
1249 DeclarationName Name;
1250 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
1251 Name = ActualTemplate->getDeclName();
1252 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
1253 Name = Ovl->getDeclName();
1254 else
Douglas Gregor308047d2009-09-09 00:23:06 +00001255 Name = Template.getAsDependentTemplateName()->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001256
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001257 // Translate the parser's template argument list in our AST format.
1258 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1259 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1260 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001261
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001262 // Do we have the save the actual template name? We might need it...
1263 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc,
1264 Name, true, LAngleLoc,
1265 TemplateArgs.data(), TemplateArgs.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001266 RAngleLoc, DeclPtrTy(), &SS);
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001267}
1268
Douglas Gregorb67535d2009-03-31 00:43:58 +00001269/// \brief Form a dependent template name.
1270///
1271/// This action forms a dependent template name given the template
1272/// name and its (presumably dependent) scope specifier. For
1273/// example, given "MetaFun::template apply", the scope specifier \p
1274/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1275/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001276Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001277Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1278 const IdentifierInfo &Name,
1279 SourceLocation NameLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001280 const CXXScopeSpec &SS,
1281 TypeTy *ObjectType) {
Mike Stump11289f42009-09-09 15:08:12 +00001282 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001283 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1284 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001285 // C++0x [temp.names]p5:
1286 // If a name prefixed by the keyword template is not the name of
1287 // a template, the program is ill-formed. [Note: the keyword
1288 // template may not be applied to non-template members of class
1289 // templates. -end note ] [ Note: as is the case with the
1290 // typename prefix, the template prefix is allowed in cases
1291 // where it is not strictly necessary; i.e., when the
1292 // nested-name-specifier or the expression on the left of the ->
1293 // or . is not dependent on a template-parameter, or the use
1294 // does not appear in the scope of a template. -end note]
1295 //
1296 // Note: C++03 was more strict here, because it banned the use of
1297 // the "template" keyword prior to a template-name that was not a
1298 // dependent name. C++ DR468 relaxed this requirement (the
1299 // "template" keyword is now permitted). We follow the C++0x
1300 // rules, even in C++03 mode, retroactively applying the DR.
1301 TemplateTy Template;
Mike Stump11289f42009-09-09 15:08:12 +00001302 TemplateNameKind TNK = isTemplateName(0, Name, NameLoc, &SS, ObjectType,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001303 false, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001304 if (TNK == TNK_Non_template) {
1305 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1306 << &Name;
1307 return TemplateTy();
1308 }
1309
1310 return Template;
1311 }
1312
Mike Stump11289f42009-09-09 15:08:12 +00001313 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001314 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorb67535d2009-03-31 00:43:58 +00001315 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1316}
1317
Mike Stump11289f42009-09-09 15:08:12 +00001318bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001319 const TemplateArgument &Arg,
1320 TemplateArgumentListBuilder &Converted) {
1321 // Check template type parameter.
1322 if (Arg.getKind() != TemplateArgument::Type) {
1323 // C++ [temp.arg.type]p1:
1324 // A template-argument for a template-parameter which is a
1325 // type shall be a type-id.
1326
1327 // We have a template type parameter but the template argument
1328 // is not a type.
1329 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1330 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001331
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001332 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001333 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001334
1335 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1336 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001337
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001338 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001339 Converted.Append(
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001340 TemplateArgument(Arg.getLocation(),
1341 Context.getCanonicalType(Arg.getAsType())));
1342 return false;
1343}
1344
Douglas Gregord32e0282009-02-09 23:23:08 +00001345/// \brief Check that the given template argument list is well-formed
1346/// for specializing the given template.
1347bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1348 SourceLocation TemplateLoc,
1349 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001350 const TemplateArgument *TemplateArgs,
1351 unsigned NumTemplateArgs,
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001352 SourceLocation RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001353 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001354 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001355 TemplateParameterList *Params = Template->getTemplateParameters();
1356 unsigned NumParams = Params->size();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001357 unsigned NumArgs = NumTemplateArgs;
Douglas Gregord32e0282009-02-09 23:23:08 +00001358 bool Invalid = false;
1359
Mike Stump11289f42009-09-09 15:08:12 +00001360 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001361 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001362
Anders Carlsson15201f12009-06-13 02:08:00 +00001363 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001364 (NumArgs < Params->getMinRequiredArguments() &&
1365 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001366 // FIXME: point at either the first arg beyond what we can handle,
1367 // or the '>', depending on whether we have too many or too few
1368 // arguments.
1369 SourceRange Range;
1370 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001371 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001372 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1373 << (NumArgs > NumParams)
1374 << (isa<ClassTemplateDecl>(Template)? 0 :
1375 isa<FunctionTemplateDecl>(Template)? 1 :
1376 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1377 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001378 Diag(Template->getLocation(), diag::note_template_decl_here)
1379 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001380 Invalid = true;
1381 }
Mike Stump11289f42009-09-09 15:08:12 +00001382
1383 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001384 // [...] The type and form of each template-argument specified in
1385 // a template-id shall match the type and form specified for the
1386 // corresponding parameter declared by the template in its
1387 // template-parameter-list.
1388 unsigned ArgIdx = 0;
1389 for (TemplateParameterList::iterator Param = Params->begin(),
1390 ParamEnd = Params->end();
1391 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001392 if (ArgIdx > NumArgs && PartialTemplateArgs)
1393 break;
Mike Stump11289f42009-09-09 15:08:12 +00001394
Douglas Gregord32e0282009-02-09 23:23:08 +00001395 // Decode the template argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001396 TemplateArgument Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00001397 if (ArgIdx >= NumArgs) {
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001398 // Retrieve the default template argument from the template
1399 // parameter.
1400 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001401 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001402 // We have an empty argument pack.
1403 Converted.BeginPack();
1404 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001405 break;
1406 }
Mike Stump11289f42009-09-09 15:08:12 +00001407
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001408 if (!TTP->hasDefaultArgument())
1409 break;
1410
Douglas Gregorc40290e2009-03-09 23:48:35 +00001411 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001412
1413 // If the argument type is dependent, instantiate it now based
1414 // on the previously-computed template arguments.
Douglas Gregor79cf6032009-03-10 20:44:00 +00001415 if (ArgType->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001416 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001417 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001418 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001419 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregord002c7b2009-05-11 23:53:27 +00001420
Anders Carlssonc8e71132009-06-05 04:47:51 +00001421 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001422 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001423 ArgType = SubstType(ArgType,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001424 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001425 TTP->getDefaultArgumentLoc(),
1426 TTP->getDeclName());
Douglas Gregor79cf6032009-03-10 20:44:00 +00001427 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001428
1429 if (ArgType.isNull())
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001430 return true;
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001431
Douglas Gregorc40290e2009-03-09 23:48:35 +00001432 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001433 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001434 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1435 if (!NTTP->hasDefaultArgument())
1436 break;
1437
Mike Stump11289f42009-09-09 15:08:12 +00001438 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001439 Template, Converted.getFlatArguments(),
Anders Carlsson40ed3442009-06-11 16:06:49 +00001440 Converted.flatSize(),
1441 SourceRange(TemplateLoc, RAngleLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001442
Anders Carlsson40ed3442009-06-11 16:06:49 +00001443 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001444 /*TakeArgs=*/false);
Anders Carlsson40ed3442009-06-11 16:06:49 +00001445
Mike Stump11289f42009-09-09 15:08:12 +00001446 Sema::OwningExprResult E
1447 = SubstExpr(NTTP->getDefaultArgument(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00001448 MultiLevelTemplateArgumentList(TemplateArgs));
Anders Carlsson40ed3442009-06-11 16:06:49 +00001449 if (E.isInvalid())
1450 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001451
Anders Carlsson40ed3442009-06-11 16:06:49 +00001452 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001453 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001454 TemplateTemplateParmDecl *TempParm
1455 = cast<TemplateTemplateParmDecl>(*Param);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001456
1457 if (!TempParm->hasDefaultArgument())
1458 break;
1459
John McCall76d824f2009-08-25 22:02:44 +00001460 // FIXME: Subst default argument
Douglas Gregorc40290e2009-03-09 23:48:35 +00001461 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001462 }
1463 } else {
1464 // Retrieve the template argument produced by the user.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001465 Arg = TemplateArgs[ArgIdx];
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001466 }
1467
Douglas Gregord32e0282009-02-09 23:23:08 +00001468
1469 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001470 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001471 Converted.BeginPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001472 // Check all the remaining arguments (if any).
1473 for (; ArgIdx < NumArgs; ++ArgIdx) {
1474 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1475 Invalid = true;
1476 }
Mike Stump11289f42009-09-09 15:08:12 +00001477
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001478 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001479 } else {
1480 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1481 Invalid = true;
1482 }
Mike Stump11289f42009-09-09 15:08:12 +00001483 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord32e0282009-02-09 23:23:08 +00001484 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1485 // Check non-type template parameters.
Douglas Gregor463421d2009-03-03 04:44:36 +00001486
John McCall76d824f2009-08-25 22:02:44 +00001487 // Do substitution on the type of the non-type template parameter
1488 // with the template arguments we've seen thus far.
Douglas Gregor463421d2009-03-03 04:44:36 +00001489 QualType NTTPType = NTTP->getType();
1490 if (NTTPType->isDependentType()) {
John McCall76d824f2009-08-25 22:02:44 +00001491 // Do substitution on the type of the non-type template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001492 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001493 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001494 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001495 SourceRange(TemplateLoc, RAngleLoc));
1496
Anders Carlssonc8e71132009-06-05 04:47:51 +00001497 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001498 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001499 NTTPType = SubstType(NTTPType,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00001500 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001501 NTTP->getLocation(),
1502 NTTP->getDeclName());
Douglas Gregor463421d2009-03-03 04:44:36 +00001503 // If that worked, check the non-type template parameter type
1504 // for validity.
1505 if (!NTTPType.isNull())
Mike Stump11289f42009-09-09 15:08:12 +00001506 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
Douglas Gregor463421d2009-03-03 04:44:36 +00001507 NTTP->getLocation());
Douglas Gregor463421d2009-03-03 04:44:36 +00001508 if (NTTPType.isNull()) {
1509 Invalid = true;
1510 break;
1511 }
1512 }
1513
Douglas Gregorc40290e2009-03-09 23:48:35 +00001514 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001515 case TemplateArgument::Null:
1516 assert(false && "Should never see a NULL template argument here");
1517 break;
Mike Stump11289f42009-09-09 15:08:12 +00001518
Douglas Gregorc40290e2009-03-09 23:48:35 +00001519 case TemplateArgument::Expression: {
1520 Expr *E = Arg.getAsExpr();
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001521 TemplateArgument Result;
1522 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregord32e0282009-02-09 23:23:08 +00001523 Invalid = true;
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001524 else
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001525 Converted.Append(Result);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001526 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001527 }
1528
Douglas Gregorc40290e2009-03-09 23:48:35 +00001529 case TemplateArgument::Declaration:
1530 case TemplateArgument::Integral:
1531 // We've already checked this template argument, so just copy
1532 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001533 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001534 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001535
Douglas Gregorc40290e2009-03-09 23:48:35 +00001536 case TemplateArgument::Type:
1537 // We have a non-type template parameter but the template
1538 // argument is a type.
Mike Stump11289f42009-09-09 15:08:12 +00001539
Douglas Gregorc40290e2009-03-09 23:48:35 +00001540 // C++ [temp.arg]p2:
1541 // In a template-argument, an ambiguity between a type-id and
1542 // an expression is resolved to a type-id, regardless of the
1543 // form of the corresponding template-parameter.
1544 //
1545 // We warn specifically about this case, since it can be rather
1546 // confusing for users.
1547 if (Arg.getAsType()->isFunctionType())
1548 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1549 << Arg.getAsType();
1550 else
1551 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1552 Diag((*Param)->getLocation(), diag::note_template_param_here);
1553 Invalid = true;
Anders Carlssonbc343912009-06-15 17:04:53 +00001554 break;
Mike Stump11289f42009-09-09 15:08:12 +00001555
Anders Carlssonbc343912009-06-15 17:04:53 +00001556 case TemplateArgument::Pack:
1557 assert(0 && "FIXME: Implement!");
1558 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001559 }
Mike Stump11289f42009-09-09 15:08:12 +00001560 } else {
Douglas Gregord32e0282009-02-09 23:23:08 +00001561 // Check template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001562 TemplateTemplateParmDecl *TempParm
Douglas Gregord32e0282009-02-09 23:23:08 +00001563 = cast<TemplateTemplateParmDecl>(*Param);
Mike Stump11289f42009-09-09 15:08:12 +00001564
Douglas Gregorc40290e2009-03-09 23:48:35 +00001565 switch (Arg.getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001566 case TemplateArgument::Null:
1567 assert(false && "Should never see a NULL template argument here");
1568 break;
Mike Stump11289f42009-09-09 15:08:12 +00001569
Douglas Gregorc40290e2009-03-09 23:48:35 +00001570 case TemplateArgument::Expression: {
1571 Expr *ArgExpr = Arg.getAsExpr();
1572 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1573 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1574 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1575 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001576
Douglas Gregorc40290e2009-03-09 23:48:35 +00001577 // Add the converted template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001578 Decl *D
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00001579 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001580 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorc40290e2009-03-09 23:48:35 +00001581 continue;
1582 }
1583 }
1584 // fall through
Mike Stump11289f42009-09-09 15:08:12 +00001585
Douglas Gregorc40290e2009-03-09 23:48:35 +00001586 case TemplateArgument::Type: {
1587 // We have a template template parameter but the template
1588 // argument does not refer to a template.
1589 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1590 Invalid = true;
1591 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001592 }
1593
Douglas Gregorc40290e2009-03-09 23:48:35 +00001594 case TemplateArgument::Declaration:
1595 // We've already checked this template argument, so just copy
1596 // it to the list of converted arguments.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001597 Converted.Append(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001598 break;
Mike Stump11289f42009-09-09 15:08:12 +00001599
Douglas Gregorc40290e2009-03-09 23:48:35 +00001600 case TemplateArgument::Integral:
1601 assert(false && "Integral argument with template template parameter");
1602 break;
Mike Stump11289f42009-09-09 15:08:12 +00001603
Anders Carlssonbc343912009-06-15 17:04:53 +00001604 case TemplateArgument::Pack:
1605 assert(0 && "FIXME: Implement!");
1606 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001607 }
Douglas Gregord32e0282009-02-09 23:23:08 +00001608 }
1609 }
1610
1611 return Invalid;
1612}
1613
1614/// \brief Check a template argument against its corresponding
1615/// template type parameter.
1616///
1617/// This routine implements the semantics of C++ [temp.arg.type]. It
1618/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001619bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
Douglas Gregord32e0282009-02-09 23:23:08 +00001620 QualType Arg, SourceLocation ArgLoc) {
1621 // C++ [temp.arg.type]p2:
1622 // A local type, a type with no linkage, an unnamed type or a type
1623 // compounded from any of these types shall not be used as a
1624 // template-argument for a template type-parameter.
1625 //
1626 // FIXME: Perform the recursive and no-linkage type checks.
1627 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001628 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001629 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001630 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001631 Tag = RecordT;
1632 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1633 return Diag(ArgLoc, diag::err_template_arg_local_type)
1634 << QualType(Tag, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001635 else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001636 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001637 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1638 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1639 return true;
1640 }
1641
1642 return false;
1643}
1644
Douglas Gregorccb07762009-02-11 19:52:55 +00001645/// \brief Checks whether the given template argument is the address
1646/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001647bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1648 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001649 bool Invalid = false;
1650
1651 // See through any implicit casts we added to fix the type.
1652 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1653 Arg = Cast->getSubExpr();
1654
Sebastian Redl576fd422009-05-10 18:38:11 +00001655 // C++0x allows nullptr, and there's no further checking to be done for that.
1656 if (Arg->getType()->isNullPtrType())
1657 return false;
1658
Douglas Gregorccb07762009-02-11 19:52:55 +00001659 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001660 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001661 // A template-argument for a non-type, non-template
1662 // template-parameter shall be one of: [...]
1663 //
1664 // -- the address of an object or function with external
1665 // linkage, including function templates and function
1666 // template-ids but excluding non-static class members,
1667 // expressed as & id-expression where the & is optional if
1668 // the name refers to a function or array, or if the
1669 // corresponding template-parameter is a reference; or
1670 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001671
Douglas Gregorccb07762009-02-11 19:52:55 +00001672 // Ignore (and complain about) any excess parentheses.
1673 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1674 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001675 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001676 diag::err_template_arg_extra_parens)
1677 << Arg->getSourceRange();
1678 Invalid = true;
1679 }
1680
1681 Arg = Parens->getSubExpr();
1682 }
1683
1684 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1685 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1686 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1687 } else
1688 DRE = dyn_cast<DeclRefExpr>(Arg);
1689
1690 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00001691 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001692 diag::err_template_arg_not_object_or_func_form)
1693 << Arg->getSourceRange();
1694
1695 // Cannot refer to non-static data members
1696 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1697 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1698 << Field << Arg->getSourceRange();
1699
1700 // Cannot refer to non-static member functions
1701 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1702 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00001703 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001704 diag::err_template_arg_method)
1705 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001706
Douglas Gregorccb07762009-02-11 19:52:55 +00001707 // Functions must have external linkage.
1708 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1709 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00001710 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001711 diag::err_template_arg_function_not_extern)
1712 << Func << Arg->getSourceRange();
1713 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1714 << true;
1715 return true;
1716 }
1717
1718 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001719 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00001720 return Invalid;
1721 }
1722
1723 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1724 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00001725 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001726 diag::err_template_arg_object_not_extern)
1727 << Var << Arg->getSourceRange();
1728 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1729 << true;
1730 return true;
1731 }
1732
1733 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001734 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00001735 return Invalid;
1736 }
Mike Stump11289f42009-09-09 15:08:12 +00001737
Douglas Gregorccb07762009-02-11 19:52:55 +00001738 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001739 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001740 diag::err_template_arg_not_object_or_func)
1741 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001742 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001743 diag::note_template_arg_refers_here);
1744 return true;
1745}
1746
1747/// \brief Checks whether the given template argument is a pointer to
1748/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump11289f42009-09-09 15:08:12 +00001749bool
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001750Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001751 bool Invalid = false;
1752
1753 // See through any implicit casts we added to fix the type.
1754 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1755 Arg = Cast->getSubExpr();
1756
Sebastian Redl576fd422009-05-10 18:38:11 +00001757 // C++0x allows nullptr, and there's no further checking to be done for that.
1758 if (Arg->getType()->isNullPtrType())
1759 return false;
1760
Douglas Gregorccb07762009-02-11 19:52:55 +00001761 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001762 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001763 // A template-argument for a non-type, non-template
1764 // template-parameter shall be one of: [...]
1765 //
1766 // -- a pointer to member expressed as described in 5.3.1.
1767 QualifiedDeclRefExpr *DRE = 0;
1768
1769 // Ignore (and complain about) any excess parentheses.
1770 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1771 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001772 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001773 diag::err_template_arg_extra_parens)
1774 << Arg->getSourceRange();
1775 Invalid = true;
1776 }
1777
1778 Arg = Parens->getSubExpr();
1779 }
1780
1781 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1782 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1783 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1784
1785 if (!DRE)
1786 return Diag(Arg->getSourceRange().getBegin(),
1787 diag::err_template_arg_not_pointer_to_member_form)
1788 << Arg->getSourceRange();
1789
1790 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1791 assert((isa<FieldDecl>(DRE->getDecl()) ||
1792 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1793 "Only non-static member pointers can make it here");
1794
1795 // Okay: this is the address of a non-static member, and therefore
1796 // a member pointer constant.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001797 Member = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00001798 return Invalid;
1799 }
1800
1801 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001802 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001803 diag::err_template_arg_not_pointer_to_member_form)
1804 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001805 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001806 diag::note_template_arg_refers_here);
1807 return true;
1808}
1809
Douglas Gregord32e0282009-02-09 23:23:08 +00001810/// \brief Check a template argument against its corresponding
1811/// non-type template parameter.
1812///
Douglas Gregor463421d2009-03-03 04:44:36 +00001813/// This routine implements the semantics of C++ [temp.arg.nontype].
1814/// It returns true if an error occurred, and false otherwise. \p
1815/// InstantiatedParamType is the type of the non-type template
1816/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001817///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001818/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00001819bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00001820 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001821 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001822 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1823
Douglas Gregor86560402009-02-10 23:36:10 +00001824 // If either the parameter has a dependent type or the argument is
1825 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001826 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00001827 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1828 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001829 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00001830 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001831 }
Douglas Gregor86560402009-02-10 23:36:10 +00001832
1833 // C++ [temp.arg.nontype]p5:
1834 // The following conversions are performed on each expression used
1835 // as a non-type template-argument. If a non-type
1836 // template-argument cannot be converted to the type of the
1837 // corresponding template-parameter then the program is
1838 // ill-formed.
1839 //
1840 // -- for a non-type template-parameter of integral or
1841 // enumeration type, integral promotions (4.5) and integral
1842 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00001843 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001844 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00001845 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00001846 // C++ [temp.arg.nontype]p1:
1847 // A template-argument for a non-type, non-template
1848 // template-parameter shall be one of:
1849 //
1850 // -- an integral constant-expression of integral or enumeration
1851 // type; or
1852 // -- the name of a non-type template-parameter; or
1853 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001854 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00001855 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001856 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001857 diag::err_template_arg_not_integral_or_enumeral)
1858 << ArgType << Arg->getSourceRange();
1859 Diag(Param->getLocation(), diag::note_template_param_here);
1860 return true;
1861 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001862 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00001863 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1864 << ArgType << Arg->getSourceRange();
1865 return true;
1866 }
1867
1868 // FIXME: We need some way to more easily get the unqualified form
1869 // of the types without going all the way to the
1870 // canonical type.
1871 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1872 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1873 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1874 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1875
1876 // Try to convert the argument to the parameter's type.
1877 if (ParamType == ArgType) {
1878 // Okay: no conversion necessary
1879 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1880 !ParamType->isEnumeralType()) {
1881 // This is an integral promotion or conversion.
1882 ImpCastExprToType(Arg, ParamType);
1883 } else {
1884 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00001885 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001886 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00001887 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00001888 Diag(Param->getLocation(), diag::note_template_param_here);
1889 return true;
1890 }
1891
Douglas Gregor52aba872009-03-14 00:20:21 +00001892 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00001893 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001894 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00001895
1896 if (!Arg->isValueDependent()) {
1897 // Check that an unsigned parameter does not receive a negative
1898 // value.
1899 if (IntegerType->isUnsignedIntegerType()
1900 && (Value.isSigned() && Value.isNegative())) {
1901 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1902 << Value.toString(10) << Param->getType()
1903 << Arg->getSourceRange();
1904 Diag(Param->getLocation(), diag::note_template_param_here);
1905 return true;
1906 }
1907
1908 // Check that we don't overflow the template parameter type.
1909 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1910 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00001911 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00001912 diag::err_template_arg_too_large)
1913 << Value.toString(10) << Param->getType()
1914 << Arg->getSourceRange();
1915 Diag(Param->getLocation(), diag::note_template_param_here);
1916 return true;
1917 }
1918
1919 if (Value.getBitWidth() != AllowedBits)
1920 Value.extOrTrunc(AllowedBits);
1921 Value.setIsSigned(IntegerType->isSignedIntegerType());
1922 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001923
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001924 // Add the value of this argument to the list of converted
1925 // arguments. We use the bitwidth and signedness of the template
1926 // parameter.
1927 if (Arg->isValueDependent()) {
1928 // The argument is value-dependent. Create a new
1929 // TemplateArgument with the converted expression.
1930 Converted = TemplateArgument(Arg);
1931 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001932 }
1933
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001934 Converted = TemplateArgument(StartLoc, Value,
Mike Stump11289f42009-09-09 15:08:12 +00001935 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001936 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00001937 return false;
1938 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001939
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001940 // Handle pointer-to-function, reference-to-function, and
1941 // pointer-to-member-function all in (roughly) the same way.
1942 if (// -- For a non-type template-parameter of type pointer to
1943 // function, only the function-to-pointer conversion (4.3) is
1944 // applied. If the template-argument represents a set of
1945 // overloaded functions (or a pointer to such), the matching
1946 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00001947 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001948 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001949 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001950 // -- For a non-type template-parameter of type reference to
1951 // function, no conversions apply. If the template-argument
1952 // represents a set of overloaded functions, the matching
1953 // function is selected from the set (13.4).
1954 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001955 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001956 // -- For a non-type template-parameter of type pointer to
1957 // member function, no conversions apply. If the
1958 // template-argument represents a set of overloaded member
1959 // functions, the matching member function is selected from
1960 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00001961 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001962 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001963 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001964 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00001965 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00001966 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001967 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00001968 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1969 ParamType->isMemberPointerType())) {
1970 ArgType = ParamType;
1971 ImpCastExprToType(Arg, ParamType);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001972 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001973 ArgType = Context.getPointerType(ArgType);
1974 ImpCastExprToType(Arg, ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001975 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001976 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00001977 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1978 return true;
1979
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001980 FixOverloadedFunctionReference(Arg, Fn);
1981 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00001982 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001983 ArgType = Context.getPointerType(Arg->getType());
1984 ImpCastExprToType(Arg, ArgType);
1985 }
1986 }
1987
Mike Stump11289f42009-09-09 15:08:12 +00001988 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00001989 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001990 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00001991 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001992 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00001993 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001994 Diag(Param->getLocation(), diag::note_template_param_here);
1995 return true;
1996 }
Mike Stump11289f42009-09-09 15:08:12 +00001997
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001998 if (ParamType->isMemberPointerType()) {
1999 NamedDecl *Member = 0;
2000 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2001 return true;
2002
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002003 if (Member)
2004 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002005 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002006 return false;
2007 }
Mike Stump11289f42009-09-09 15:08:12 +00002008
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002009 NamedDecl *Entity = 0;
2010 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2011 return true;
2012
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002013 if (Entity)
2014 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002015 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002016 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002017 }
2018
Chris Lattner696197c2009-02-20 21:37:53 +00002019 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002020 // -- for a non-type template-parameter of type pointer to
2021 // object, qualification conversions (4.4) and the
2022 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002023 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002024 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002025 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002026
Sebastian Redl576fd422009-05-10 18:38:11 +00002027 if (ArgType->isNullPtrType()) {
2028 ArgType = ParamType;
2029 ImpCastExprToType(Arg, ParamType);
2030 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002031 ArgType = Context.getArrayDecayedType(ArgType);
2032 ImpCastExprToType(Arg, ArgType);
Douglas Gregora9faa442009-02-11 00:44:29 +00002033 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002034
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002035 if (IsQualificationConversion(ArgType, ParamType)) {
2036 ArgType = ParamType;
2037 ImpCastExprToType(Arg, ParamType);
2038 }
Mike Stump11289f42009-09-09 15:08:12 +00002039
Douglas Gregor1515f762009-02-11 18:22:40 +00002040 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002041 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002042 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002043 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002044 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002045 Diag(Param->getLocation(), diag::note_template_param_here);
2046 return true;
2047 }
Mike Stump11289f42009-09-09 15:08:12 +00002048
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002049 NamedDecl *Entity = 0;
2050 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2051 return true;
2052
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002053 if (Entity)
2054 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002055 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002056 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002057 }
Mike Stump11289f42009-09-09 15:08:12 +00002058
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002059 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002060 // -- For a non-type template-parameter of type reference to
2061 // object, no conversions apply. The type referred to by the
2062 // reference may be more cv-qualified than the (otherwise
2063 // identical) type of the template-argument. The
2064 // template-parameter is bound directly to the
2065 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002066 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002067 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002068
Douglas Gregor1515f762009-02-11 18:22:40 +00002069 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002070 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002071 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002072 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002073 << Arg->getSourceRange();
2074 Diag(Param->getLocation(), diag::note_template_param_here);
2075 return true;
2076 }
2077
Mike Stump11289f42009-09-09 15:08:12 +00002078 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002079 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2080 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002081
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002082 if ((ParamQuals | ArgQuals) != ParamQuals) {
2083 Diag(Arg->getSourceRange().getBegin(),
2084 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002085 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002086 << Arg->getSourceRange();
2087 Diag(Param->getLocation(), diag::note_template_param_here);
2088 return true;
2089 }
Mike Stump11289f42009-09-09 15:08:12 +00002090
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002091 NamedDecl *Entity = 0;
2092 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2093 return true;
2094
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002095 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002096 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002097 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002098 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002099
2100 // -- For a non-type template-parameter of type pointer to data
2101 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002102 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002103 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2104
Douglas Gregor1515f762009-02-11 18:22:40 +00002105 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002106 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002107 } else if (ArgType->isNullPtrType()) {
2108 ImpCastExprToType(Arg, ParamType);
Douglas Gregor0e558532009-02-11 16:16:59 +00002109 } else if (IsQualificationConversion(ArgType, ParamType)) {
2110 ImpCastExprToType(Arg, ParamType);
2111 } else {
2112 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002113 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002114 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002115 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002116 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002117 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002118 }
2119
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002120 NamedDecl *Member = 0;
2121 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2122 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002123
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002124 if (Member)
2125 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002126 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002127 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00002128}
2129
2130/// \brief Check a template argument against its corresponding
2131/// template template parameter.
2132///
2133/// This routine implements the semantics of C++ [temp.arg.template].
2134/// It returns true if an error occurred, and false otherwise.
2135bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2136 DeclRefExpr *Arg) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002137 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2138 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2139
2140 // C++ [temp.arg.template]p1:
2141 // A template-argument for a template template-parameter shall be
2142 // the name of a class template, expressed as id-expression. Only
2143 // primary class templates are considered when matching the
2144 // template template argument with the corresponding parameter;
2145 // partial specializations are not considered even if their
2146 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002147 //
2148 // Note that we also allow template template parameters here, which
2149 // will happen when we are dealing with, e.g., class template
2150 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002151 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002152 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002153 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002154 "Only function templates are possible here");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002155 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2156 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002157 << Template;
2158 }
2159
2160 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2161 Param->getTemplateParameters(),
2162 true, true,
2163 Arg->getSourceRange().getBegin());
Douglas Gregord32e0282009-02-09 23:23:08 +00002164}
2165
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002166/// \brief Determine whether the given template parameter lists are
2167/// equivalent.
2168///
Mike Stump11289f42009-09-09 15:08:12 +00002169/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002170/// source code as part of a new template declaration.
2171///
2172/// \param Old The old template parameter list, typically found via
2173/// name lookup of the template declared with this template parameter
2174/// list.
2175///
2176/// \param Complain If true, this routine will produce a diagnostic if
2177/// the template parameter lists are not equivalent.
2178///
Douglas Gregor85e0f662009-02-10 00:24:35 +00002179/// \param IsTemplateTemplateParm If true, this routine is being
2180/// called to compare the template parameter lists of a template
2181/// template parameter.
2182///
2183/// \param TemplateArgLoc If this source location is valid, then we
2184/// are actually checking the template parameter list of a template
2185/// argument (New) against the template parameter list of its
2186/// corresponding template template parameter (Old). We produce
2187/// slightly different diagnostics in this scenario.
2188///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002189/// \returns True if the template parameter lists are equal, false
2190/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002191bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002192Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2193 TemplateParameterList *Old,
2194 bool Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002195 bool IsTemplateTemplateParm,
2196 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002197 if (Old->size() != New->size()) {
2198 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002199 unsigned NextDiag = diag::err_template_param_list_different_arity;
2200 if (TemplateArgLoc.isValid()) {
2201 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2202 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002203 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002204 Diag(New->getTemplateLoc(), NextDiag)
2205 << (New->size() > Old->size())
2206 << IsTemplateTemplateParm
2207 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002208 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2209 << IsTemplateTemplateParm
2210 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2211 }
2212
2213 return false;
2214 }
2215
2216 for (TemplateParameterList::iterator OldParm = Old->begin(),
2217 OldParmEnd = Old->end(), NewParm = New->begin();
2218 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2219 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002220 if (Complain) {
2221 unsigned NextDiag = diag::err_template_param_different_kind;
2222 if (TemplateArgLoc.isValid()) {
2223 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2224 NextDiag = diag::note_template_param_different_kind;
2225 }
2226 Diag((*NewParm)->getLocation(), NextDiag)
2227 << IsTemplateTemplateParm;
2228 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2229 << IsTemplateTemplateParm;
Douglas Gregor85e0f662009-02-10 00:24:35 +00002230 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002231 return false;
2232 }
2233
2234 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2235 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002236 // know we're at the same index).
2237#if 0
Mike Stump87c57ac2009-05-16 07:39:55 +00002238 // FIXME: Enable this code in debug mode *after* we properly go through
2239 // and "instantiate" the template parameter lists of template template
2240 // parameters. It's only after this instantiation that (1) any dependent
2241 // types within the template parameter list of the template template
2242 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregor85e0f662009-02-10 00:24:35 +00002243 // will match up.
Mike Stump11289f42009-09-09 15:08:12 +00002244 QualType OldParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002245 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
Mike Stump11289f42009-09-09 15:08:12 +00002246 QualType NewParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002247 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
Mike Stump11289f42009-09-09 15:08:12 +00002248 assert(Context.getCanonicalType(OldParmType) ==
2249 Context.getCanonicalType(NewParmType) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002250 "type parameter mismatch?");
2251#endif
Mike Stump11289f42009-09-09 15:08:12 +00002252 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002253 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2254 // The types of non-type template parameters must agree.
2255 NonTypeTemplateParmDecl *NewNTTP
2256 = cast<NonTypeTemplateParmDecl>(*NewParm);
2257 if (Context.getCanonicalType(OldNTTP->getType()) !=
2258 Context.getCanonicalType(NewNTTP->getType())) {
2259 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002260 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2261 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002262 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002263 diag::err_template_arg_template_params_mismatch);
2264 NextDiag = diag::note_template_nontype_parm_different_type;
2265 }
2266 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002267 << NewNTTP->getType()
2268 << IsTemplateTemplateParm;
Mike Stump11289f42009-09-09 15:08:12 +00002269 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002270 diag::note_template_nontype_parm_prev_declaration)
2271 << OldNTTP->getType();
2272 }
2273 return false;
2274 }
2275 } else {
2276 // The template parameter lists of template template
2277 // parameters must agree.
2278 // FIXME: Could we perform a faster "type" comparison here?
Mike Stump11289f42009-09-09 15:08:12 +00002279 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002280 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002281 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002282 = cast<TemplateTemplateParmDecl>(*OldParm);
2283 TemplateTemplateParmDecl *NewTTP
2284 = cast<TemplateTemplateParmDecl>(*NewParm);
2285 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2286 OldTTP->getTemplateParameters(),
2287 Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002288 /*IsTemplateTemplateParm=*/true,
2289 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002290 return false;
2291 }
2292 }
2293
2294 return true;
2295}
2296
2297/// \brief Check whether a template can be declared within this scope.
2298///
2299/// If the template declaration is valid in this scope, returns
2300/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002301bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002302Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002303 // Find the nearest enclosing declaration scope.
2304 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2305 (S->getFlags() & Scope::TemplateParamScope) != 0)
2306 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002307
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002308 // C++ [temp]p2:
2309 // A template-declaration can appear only as a namespace scope or
2310 // class scope declaration.
2311 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002312 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2313 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002314 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002315 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002316
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002317 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002318 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002319
2320 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2321 return false;
2322
Mike Stump11289f42009-09-09 15:08:12 +00002323 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002324 diag::err_template_outside_namespace_or_class_scope)
2325 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002326}
Douglas Gregor67a65642009-02-17 23:15:12 +00002327
Douglas Gregorf61eca92009-05-13 18:28:20 +00002328/// \brief Check whether a class template specialization or explicit
2329/// instantiation in the current context is well-formed.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002330///
Douglas Gregorf61eca92009-05-13 18:28:20 +00002331/// This routine determines whether a class template specialization or
Mike Stump11289f42009-09-09 15:08:12 +00002332/// explicit instantiation can be declared in the current context
2333/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2334/// appropriate diagnostics if there was an error. It returns true if
Douglas Gregorf61eca92009-05-13 18:28:20 +00002335// there was an error that we cannot recover from, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002336bool
Douglas Gregorf47b9112009-02-25 22:02:03 +00002337Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2338 ClassTemplateSpecializationDecl *PrevDecl,
2339 SourceLocation TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002340 SourceRange ScopeSpecifierRange,
Douglas Gregor30b01972009-06-12 22:21:45 +00002341 bool PartialSpecialization,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002342 bool ExplicitInstantiation) {
Douglas Gregorf47b9112009-02-25 22:02:03 +00002343 // C++ [temp.expl.spec]p2:
2344 // An explicit specialization shall be declared in the namespace
2345 // of which the template is a member, or, for member templates, in
2346 // the namespace of which the enclosing class or enclosing class
2347 // template is a member. An explicit specialization of a member
2348 // function, member class or static data member of a class
2349 // template shall be declared in the namespace of which the class
2350 // template is a member. Such a declaration may also be a
2351 // definition. If the declaration is not a definition, the
2352 // specialization may be defined later in the name- space in which
2353 // the explicit specialization was declared, or in a namespace
2354 // that encloses the one in which the explicit specialization was
2355 // declared.
2356 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor30b01972009-06-12 22:21:45 +00002357 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002358 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002359 << Kind << ClassTemplate;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002360 return true;
2361 }
2362
2363 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00002364 DeclContext *TemplateContext
Douglas Gregorf47b9112009-02-25 22:02:03 +00002365 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorf61eca92009-05-13 18:28:20 +00002366 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2367 !ExplicitInstantiation) {
Douglas Gregorf47b9112009-02-25 22:02:03 +00002368 // There is no prior declaration of this entity, so this
2369 // specialization must be in the same context as the template
2370 // itself.
2371 if (DC != TemplateContext) {
2372 if (isa<TranslationUnitDecl>(TemplateContext))
2373 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor30b01972009-06-12 22:21:45 +00002374 << PartialSpecialization
Douglas Gregorf47b9112009-02-25 22:02:03 +00002375 << ClassTemplate << ScopeSpecifierRange;
2376 else if (isa<NamespaceDecl>(TemplateContext))
2377 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Mike Stump11289f42009-09-09 15:08:12 +00002378 << PartialSpecialization << ClassTemplate
Douglas Gregor30b01972009-06-12 22:21:45 +00002379 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002380
2381 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2382 }
2383
2384 return false;
2385 }
2386
2387 // We have a previous declaration of this entity. Make sure that
2388 // this redeclaration (or definition) occurs in an enclosing namespace.
2389 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002390 // FIXME: In C++98, we would like to turn these errors into warnings,
2391 // dependent on a -Wc++0x flag.
Douglas Gregorf61eca92009-05-13 18:28:20 +00002392 bool SuppressedDiag = false;
Douglas Gregor30b01972009-06-12 22:21:45 +00002393 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorf61eca92009-05-13 18:28:20 +00002394 if (isa<TranslationUnitDecl>(TemplateContext)) {
2395 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2396 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002397 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorf61eca92009-05-13 18:28:20 +00002398 else
2399 SuppressedDiag = true;
2400 } else if (isa<NamespaceDecl>(TemplateContext)) {
2401 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2402 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor30b01972009-06-12 22:21:45 +00002403 << Kind << ClassTemplate
Douglas Gregorf61eca92009-05-13 18:28:20 +00002404 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Mike Stump11289f42009-09-09 15:08:12 +00002405 else
Douglas Gregorf61eca92009-05-13 18:28:20 +00002406 SuppressedDiag = true;
2407 }
Mike Stump11289f42009-09-09 15:08:12 +00002408
Douglas Gregorf61eca92009-05-13 18:28:20 +00002409 if (!SuppressedDiag)
2410 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002411 }
2412
2413 return false;
2414}
2415
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002416/// \brief Check the non-type template arguments of a class template
2417/// partial specialization according to C++ [temp.class.spec]p9.
2418///
Douglas Gregor09a30232009-06-12 22:08:06 +00002419/// \param TemplateParams the template parameters of the primary class
2420/// template.
2421///
2422/// \param TemplateArg the template arguments of the class template
2423/// partial specialization.
2424///
2425/// \param MirrorsPrimaryTemplate will be set true if the class
2426/// template partial specialization arguments are identical to the
2427/// implicit template arguments of the primary template. This is not
2428/// necessarily an error (C++0x), and it is left to the caller to diagnose
2429/// this condition when it is an error.
2430///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002431/// \returns true if there was an error, false otherwise.
2432bool Sema::CheckClassTemplatePartialSpecializationArgs(
2433 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002434 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002435 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002436 // FIXME: the interface to this function will have to change to
2437 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002438 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002439
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002440 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002441
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002442 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002443 // Determine whether the template argument list of the partial
2444 // specialization is identical to the implicit argument list of
2445 // the primary template. The caller may need to diagnostic this as
2446 // an error per C++ [temp.class.spec]p9b3.
2447 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002448 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002449 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2450 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002451 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002452 MirrorsPrimaryTemplate = false;
2453 } else if (TemplateTemplateParmDecl *TTP
2454 = dyn_cast<TemplateTemplateParmDecl>(
2455 TemplateParams->getParam(I))) {
2456 // FIXME: We should settle on either Declaration storage or
2457 // Expression storage for template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002458 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor09a30232009-06-12 22:08:06 +00002459 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson40c1d492009-06-13 18:20:51 +00002460 ArgList[I].getAsDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002461 if (!ArgDecl)
Mike Stump11289f42009-09-09 15:08:12 +00002462 if (DeclRefExpr *DRE
Anders Carlsson40c1d492009-06-13 18:20:51 +00002463 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002464 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2465
2466 if (!ArgDecl ||
2467 ArgDecl->getIndex() != TTP->getIndex() ||
2468 ArgDecl->getDepth() != TTP->getDepth())
2469 MirrorsPrimaryTemplate = false;
2470 }
2471 }
2472
Mike Stump11289f42009-09-09 15:08:12 +00002473 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002474 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002475 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002476 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002477 }
2478
Anders Carlsson40c1d492009-06-13 18:20:51 +00002479 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002480 if (!ArgExpr) {
2481 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002482 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002483 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002484
2485 // C++ [temp.class.spec]p8:
2486 // A non-type argument is non-specialized if it is the name of a
2487 // non-type parameter. All other non-type arguments are
2488 // specialized.
2489 //
2490 // Below, we check the two conditions that only apply to
2491 // specialized non-type arguments, so skip any non-specialized
2492 // arguments.
2493 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002494 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002495 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002496 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002497 (Param->getIndex() != NTTP->getIndex() ||
2498 Param->getDepth() != NTTP->getDepth()))
2499 MirrorsPrimaryTemplate = false;
2500
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002501 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002502 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002503
2504 // C++ [temp.class.spec]p9:
2505 // Within the argument list of a class template partial
2506 // specialization, the following restrictions apply:
2507 // -- A partially specialized non-type argument expression
2508 // shall not involve a template parameter of the partial
2509 // specialization except when the argument expression is a
2510 // simple identifier.
2511 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002512 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002513 diag::err_dependent_non_type_arg_in_partial_spec)
2514 << ArgExpr->getSourceRange();
2515 return true;
2516 }
2517
2518 // -- The type of a template parameter corresponding to a
2519 // specialized non-type argument shall not be dependent on a
2520 // parameter of the specialization.
2521 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002522 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002523 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2524 << Param->getType()
2525 << ArgExpr->getSourceRange();
2526 Diag(Param->getLocation(), diag::note_template_param_here);
2527 return true;
2528 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002529
2530 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002531 }
2532
2533 return false;
2534}
2535
Douglas Gregorc08f4892009-03-25 00:13:59 +00002536Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002537Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2538 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002539 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002540 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002541 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002542 SourceLocation TemplateNameLoc,
2543 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002544 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002545 SourceLocation *TemplateArgLocs,
2546 SourceLocation RAngleLoc,
2547 AttributeList *Attr,
2548 MultiTemplateParamsArg TemplateParameterLists) {
John McCall06f6fe8d2009-09-04 01:14:41 +00002549 assert(TUK == TUK_Declaration || TUK == TUK_Definition);
2550
Douglas Gregor67a65642009-02-17 23:15:12 +00002551 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002552 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002553 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002554 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002555
Douglas Gregor2373c592009-05-31 09:31:02 +00002556 bool isPartialSpecialization = false;
2557
Douglas Gregorf47b9112009-02-25 22:02:03 +00002558 // Check the validity of the template headers that introduce this
2559 // template.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002560 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002561 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2562 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002563 TemplateParameterLists.size());
2564 if (TemplateParams && TemplateParams->size() > 0) {
2565 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002566
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002567 // C++ [temp.class.spec]p10:
2568 // The template parameter list of a specialization shall not
2569 // contain default template argument values.
2570 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2571 Decl *Param = TemplateParams->getParam(I);
2572 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2573 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002574 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002575 diag::err_default_arg_in_partial_spec);
2576 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2577 }
2578 } else if (NonTypeTemplateParmDecl *NTTP
2579 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2580 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002581 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002582 diag::err_default_arg_in_partial_spec)
2583 << DefArg->getSourceRange();
2584 NTTP->setDefaultArgument(0);
2585 DefArg->Destroy(Context);
2586 }
2587 } else {
2588 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2589 if (Expr *DefArg = TTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002590 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002591 diag::err_default_arg_in_partial_spec)
2592 << DefArg->getSourceRange();
2593 TTP->setDefaultArgument(0);
2594 DefArg->Destroy(Context);
Douglas Gregord5222052009-06-12 19:43:02 +00002595 }
2596 }
2597 }
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002598 } else if (!TemplateParams)
2599 Diag(KWLoc, diag::err_template_spec_needs_header)
2600 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregorf47b9112009-02-25 22:02:03 +00002601
Douglas Gregor67a65642009-02-17 23:15:12 +00002602 // Check that the specialization uses the same tag kind as the
2603 // original template.
2604 TagDecl::TagKind Kind;
2605 switch (TagSpec) {
2606 default: assert(0 && "Unknown tag type!");
2607 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2608 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2609 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2610 }
Douglas Gregord9034f02009-05-14 16:41:31 +00002611 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00002612 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00002613 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00002614 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00002615 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00002616 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00002617 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00002618 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00002619 diag::note_previous_use);
2620 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2621 }
2622
Douglas Gregorc40290e2009-03-09 23:48:35 +00002623 // Translate the parser's template argument list in our AST format.
2624 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2625 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2626
Douglas Gregor67a65642009-02-17 23:15:12 +00002627 // Check that the template argument list is well-formed for this
2628 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002629 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2630 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00002631 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002632 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00002633 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002634 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002635
Mike Stump11289f42009-09-09 15:08:12 +00002636 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00002637 ClassTemplate->getTemplateParameters()->size()) &&
2638 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00002639
Douglas Gregor2373c592009-05-31 09:31:02 +00002640 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00002641 // corresponds to these arguments.
2642 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00002643 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002644 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002645 if (CheckClassTemplatePartialSpecializationArgs(
2646 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002647 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002648 return true;
2649
Douglas Gregor09a30232009-06-12 22:08:06 +00002650 if (MirrorsPrimaryTemplate) {
2651 // C++ [temp.class.spec]p9b3:
2652 //
Mike Stump11289f42009-09-09 15:08:12 +00002653 // -- The argument list of the specialization shall not be identical
2654 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00002655 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00002656 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00002657 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00002658 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00002659 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00002660 ClassTemplate->getIdentifier(),
2661 TemplateNameLoc,
2662 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002663 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00002664 AS_none);
2665 }
2666
Douglas Gregor2373c592009-05-31 09:31:02 +00002667 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00002668 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002669 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002670 Converted.flatSize(),
2671 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002672 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002673 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002674 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002675 Converted.flatSize(),
2676 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00002677 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002678 ClassTemplateSpecializationDecl *PrevDecl = 0;
2679
2680 if (isPartialSpecialization)
2681 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00002682 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00002683 InsertPos);
2684 else
2685 PrevDecl
2686 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00002687
2688 ClassTemplateSpecializationDecl *Specialization = 0;
2689
Douglas Gregorf47b9112009-02-25 22:02:03 +00002690 // Check whether we can declare a class template specialization in
2691 // the current scope.
2692 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002693 TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002694 SS.getRange(),
Douglas Gregor30b01972009-06-12 22:21:45 +00002695 isPartialSpecialization,
Douglas Gregorf61eca92009-05-13 18:28:20 +00002696 /*ExplicitInstantiation=*/false))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002697 return true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002698
Douglas Gregor15301382009-07-30 17:40:51 +00002699 // The canonical type
2700 QualType CanonType;
Douglas Gregor67a65642009-02-17 23:15:12 +00002701 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2702 // Since the only prior class template specialization with these
2703 // arguments was referenced but not declared, reuse that
2704 // declaration node as our own, updating its source location to
2705 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002706 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00002707 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00002708 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00002709 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00002710 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00002711 // Build the canonical type that describes the converted template
2712 // arguments of the class template partial specialization.
2713 CanonType = Context.getTemplateSpecializationType(
2714 TemplateName(ClassTemplate),
2715 Converted.getFlatArguments(),
2716 Converted.flatSize());
2717
Douglas Gregor2373c592009-05-31 09:31:02 +00002718 // Create a new class template partial specialization declaration node.
Mike Stump11289f42009-09-09 15:08:12 +00002719 TemplateParameterList *TemplateParams
Douglas Gregor2373c592009-05-31 09:31:02 +00002720 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2721 ClassTemplatePartialSpecializationDecl *PrevPartial
2722 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002723 ClassTemplatePartialSpecializationDecl *Partial
2724 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00002725 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002726 TemplateNameLoc,
2727 TemplateParams,
2728 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002729 Converted,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002730 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00002731
2732 if (PrevPartial) {
2733 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2734 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2735 } else {
2736 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2737 }
2738 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00002739
2740 // Check that all of the template parameters of the class template
2741 // partial specialization are deducible from the template
2742 // arguments. If not, this class template partial specialization
2743 // will never be used.
2744 llvm::SmallVector<bool, 8> DeducibleParams;
2745 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002746 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2747 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00002748 unsigned NumNonDeducible = 0;
2749 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2750 if (!DeducibleParams[I])
2751 ++NumNonDeducible;
2752
2753 if (NumNonDeducible) {
2754 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2755 << (NumNonDeducible > 1)
2756 << SourceRange(TemplateNameLoc, RAngleLoc);
2757 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2758 if (!DeducibleParams[I]) {
2759 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2760 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00002761 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002762 diag::note_partial_spec_unused_parameter)
2763 << Param->getDeclName();
2764 else
Mike Stump11289f42009-09-09 15:08:12 +00002765 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002766 diag::note_partial_spec_unused_parameter)
2767 << std::string("<anonymous>");
2768 }
2769 }
2770 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002771 } else {
2772 // Create a new class template specialization declaration node for
2773 // this explicit specialization.
2774 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00002775 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00002776 ClassTemplate->getDeclContext(),
2777 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002778 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002779 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00002780 PrevDecl);
2781
2782 if (PrevDecl) {
2783 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2784 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2785 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002786 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00002787 InsertPos);
2788 }
Douglas Gregor15301382009-07-30 17:40:51 +00002789
2790 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002791 }
2792
2793 // Note that this is an explicit specialization.
2794 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2795
2796 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002797 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002798 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002799 // FIXME: Should also handle explicit specialization after implicit
2800 // instantiation with a special diagnostic.
Douglas Gregor67a65642009-02-17 23:15:12 +00002801 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002802 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00002803 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00002804 Diag(Def->getLocation(), diag::note_previous_definition);
2805 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00002806 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002807 }
2808 }
2809
Douglas Gregord56a91e2009-02-26 22:19:44 +00002810 // Build the fully-sugared type for this class template
2811 // specialization as the user wrote in the specialization
2812 // itself. This means that we'll pretty-print the type retrieved
2813 // from the specialization's declaration the way that the user
2814 // actually wrote the specialization, rather than formatting the
2815 // name based on the "canonical" representation used to store the
2816 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002817 QualType WrittenTy
2818 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002819 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00002820 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00002821 CanonType);
Douglas Gregordc572a32009-03-30 22:58:21 +00002822 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002823 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00002824
Douglas Gregor1e249f82009-02-25 22:18:32 +00002825 // C++ [temp.expl.spec]p9:
2826 // A template explicit specialization is in the scope of the
2827 // namespace in which the template was defined.
2828 //
2829 // We actually implement this paragraph where we set the semantic
2830 // context (in the creation of the ClassTemplateSpecializationDecl),
2831 // but we also maintain the lexical context where the actual
2832 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00002833 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00002834
Douglas Gregor67a65642009-02-17 23:15:12 +00002835 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00002836 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00002837 Specialization->startDefinition();
2838
2839 // Add the specialization into its lexical context, so that it can
2840 // be seen when iterating through the list of declarations in that
2841 // context. However, specializations are not found by name lookup.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002842 CurContext->addDecl(Specialization);
Chris Lattner83f095c2009-03-28 19:18:32 +00002843 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002844}
Douglas Gregor333489b2009-03-27 23:10:48 +00002845
Mike Stump11289f42009-09-09 15:08:12 +00002846Sema::DeclPtrTy
2847Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002848 MultiTemplateParamsArg TemplateParameterLists,
2849 Declarator &D) {
2850 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2851}
2852
Mike Stump11289f42009-09-09 15:08:12 +00002853Sema::DeclPtrTy
2854Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002855 MultiTemplateParamsArg TemplateParameterLists,
2856 Declarator &D) {
2857 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2858 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2859 "Not a function declarator!");
2860 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00002861
Douglas Gregor17a7c122009-06-24 00:54:41 +00002862 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00002863 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00002864 }
Mike Stump11289f42009-09-09 15:08:12 +00002865
Douglas Gregor17a7c122009-06-24 00:54:41 +00002866 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002867
2868 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00002869 move(TemplateParameterLists),
2870 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002871 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00002872 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00002873 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002874 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00002875 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2876 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002877 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00002878}
2879
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002880/// \brief Perform semantic analysis for the given function template
2881/// specialization.
2882///
2883/// This routine performs all of the semantic analysis required for an
2884/// explicit function template specialization. On successful completion,
2885/// the function declaration \p FD will become a function template
2886/// specialization.
2887///
2888/// \param FD the function declaration, which will be updated to become a
2889/// function template specialization.
2890///
2891/// \param HasExplicitTemplateArgs whether any template arguments were
2892/// explicitly provided.
2893///
2894/// \param LAngleLoc the location of the left angle bracket ('<'), if
2895/// template arguments were explicitly provided.
2896///
2897/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
2898/// if any.
2899///
2900/// \param NumExplicitTemplateArgs the number of explicitly-provided template
2901/// arguments. This number may be zero even when HasExplicitTemplateArgs is
2902/// true as in, e.g., \c void sort<>(char*, char*);
2903///
2904/// \param RAngleLoc the location of the right angle bracket ('>'), if
2905/// template arguments were explicitly provided.
2906///
2907/// \param PrevDecl the set of declarations that
2908bool
2909Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
2910 bool HasExplicitTemplateArgs,
2911 SourceLocation LAngleLoc,
2912 const TemplateArgument *ExplicitTemplateArgs,
2913 unsigned NumExplicitTemplateArgs,
2914 SourceLocation RAngleLoc,
2915 NamedDecl *&PrevDecl) {
2916 // The set of function template specializations that could match this
2917 // explicit function template specialization.
2918 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
2919 CandidateSet Candidates;
2920
2921 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
2922 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2923 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
2924 // Only consider templates found within the same semantic lookup scope as
2925 // FD.
2926 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
2927 continue;
2928
2929 // C++ [temp.expl.spec]p11:
2930 // A trailing template-argument can be left unspecified in the
2931 // template-id naming an explicit function template specialization
2932 // provided it can be deduced from the function argument type.
2933 // Perform template argument deduction to determine whether we may be
2934 // specializing this template.
2935 // FIXME: It is somewhat wasteful to build
2936 TemplateDeductionInfo Info(Context);
2937 FunctionDecl *Specialization = 0;
2938 if (TemplateDeductionResult TDK
2939 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
2940 ExplicitTemplateArgs,
2941 NumExplicitTemplateArgs,
2942 FD->getType(),
2943 Specialization,
2944 Info)) {
2945 // FIXME: Template argument deduction failed; record why it failed, so
2946 // that we can provide nifty diagnostics.
2947 (void)TDK;
2948 continue;
2949 }
2950
2951 // Record this candidate.
2952 Candidates.push_back(Specialization);
2953 }
2954 }
2955
2956 if (Candidates.empty()) {
2957 Diag(FD->getLocation(), diag::err_function_template_spec_no_match)
2958 << FD->getDeclName();
2959 // FIXME: Print the almost-ran candidates.
2960 return true;
2961 }
2962
2963 if (Candidates.size() > 1) {
2964 // C++ [temp.func.order]p1:
2965 // Partial ordering of overloaded function template declarations is used
2966 // [...] when [...] an explicit specialization (14.7.3) refers to a
2967 // function template specialization.
2968 CandidateSet::iterator Best = Candidates.begin();
2969 for (CandidateSet::iterator C = Best + 1, CEnd = Candidates.end();
2970 C != CEnd; ++C) {
2971 if (getMoreSpecializedTemplate((*Best)->getPrimaryTemplate(),
2972 (*C)->getPrimaryTemplate(),
2973 TPOC_Other)
2974 == (*C)->getPrimaryTemplate())
2975 Best = C;
2976 }
2977
2978 bool Ambiguous = false;
2979 for (CandidateSet::iterator C = Candidates.begin(), CEnd = Candidates.end();
2980 C != CEnd; ++C) {
2981 if (C != Best &&
2982 getMoreSpecializedTemplate((*Best)->getPrimaryTemplate(),
2983 (*C)->getPrimaryTemplate(),
2984 TPOC_Other)
2985 != (*Best)->getPrimaryTemplate()) {
2986 Ambiguous = true;
2987 break;
2988 }
2989 }
2990
2991 if (Ambiguous) {
2992 // Partial ordering was ambiguous.
2993 Diag(FD->getLocation(), diag::err_function_template_spec_ambiguous)
2994 << FD->getDeclName()
2995 << HasExplicitTemplateArgs;
2996
2997 for (CandidateSet::iterator C = Candidates.begin(),
2998 CEnd = Candidates.end();
2999 C != CEnd; ++C)
3000 Diag((*C)->getLocation(), diag::note_function_template_spec_matched)
3001 << getTemplateArgumentBindingsText(
3002 (*C)->getPrimaryTemplate()->getTemplateParameters(),
3003 *(*C)->getTemplateSpecializationArgs());
3004
3005 return true;
3006 }
3007
3008 // Move the best candidate to the front of the candidates list.
3009 std::swap(*Best, Candidates.front());
3010 }
3011
3012 // The first candidate is a prior declaration of the function template
3013 // specialization we're declared here, which we may have created above.
3014 FunctionDecl *Specialization = Candidates.front();
3015
3016 // FIXME: Check if the prior specialization has a point of instantiation.
3017 // If so, we have run afoul of C++ [temp.expl.spec]p6.
3018
3019 // Mark the prior declaration as an explicit specialization, so that later
3020 // clients know that this is an explicit specialization.
3021 // FIXME: Check for prior explicit instantiations?
3022 Specialization->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
3023
3024 // Turn the given function declaration into a function template
3025 // specialization, with the template arguments from the previous
3026 // specialization.
3027 FD->setFunctionTemplateSpecialization(Context,
3028 Specialization->getPrimaryTemplate(),
3029 new (Context) TemplateArgumentList(
3030 *Specialization->getTemplateSpecializationArgs()),
3031 /*InsertPos=*/0,
3032 TSK_ExplicitSpecialization);
3033
3034 // The "previous declaration" for this function template specialization is
3035 // the prior function template specialization.
3036 PrevDecl = Specialization;
3037 return false;
3038}
3039
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003040// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003041// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003042Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003043Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003044 SourceLocation ExternLoc,
3045 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003046 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003047 SourceLocation KWLoc,
3048 const CXXScopeSpec &SS,
3049 TemplateTy TemplateD,
3050 SourceLocation TemplateNameLoc,
3051 SourceLocation LAngleLoc,
3052 ASTTemplateArgsPtr TemplateArgsIn,
3053 SourceLocation *TemplateArgLocs,
3054 SourceLocation RAngleLoc,
3055 AttributeList *Attr) {
3056 // Find the class template we're specializing
3057 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003058 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003059 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3060
3061 // Check that the specialization uses the same tag kind as the
3062 // original template.
3063 TagDecl::TagKind Kind;
3064 switch (TagSpec) {
3065 default: assert(0 && "Unknown tag type!");
3066 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3067 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3068 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3069 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003070 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003071 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003072 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003073 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003074 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003075 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003076 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003077 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003078 diag::note_previous_use);
3079 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3080 }
3081
Douglas Gregorf61eca92009-05-13 18:28:20 +00003082 // C++0x [temp.explicit]p2:
3083 // [...] An explicit instantiation shall appear in an enclosing
3084 // namespace of its template. [...]
3085 //
3086 // This is C++ DR 275.
3087 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
Mike Stump11289f42009-09-09 15:08:12 +00003088 TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003089 SS.getRange(),
Douglas Gregor30b01972009-06-12 22:21:45 +00003090 /*PartialSpecialization=*/false,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003091 /*ExplicitInstantiation=*/true))
3092 return true;
3093
Douglas Gregora1f49972009-05-13 00:25:59 +00003094 // Translate the parser's template argument list in our AST format.
3095 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
3096 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3097
3098 // Check that the template argument list is well-formed for this
3099 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003100 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3101 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003102 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003103 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003104 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003105 return true;
3106
Mike Stump11289f42009-09-09 15:08:12 +00003107 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003108 ClassTemplate->getTemplateParameters()->size()) &&
3109 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003110
Douglas Gregora1f49972009-05-13 00:25:59 +00003111 // Find the class template specialization declaration that
3112 // corresponds to these arguments.
3113 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003114 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003115 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003116 Converted.flatSize(),
3117 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003118 void *InsertPos = 0;
3119 ClassTemplateSpecializationDecl *PrevDecl
3120 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3121
3122 ClassTemplateSpecializationDecl *Specialization = 0;
3123
Douglas Gregorf61eca92009-05-13 18:28:20 +00003124 bool SpecializationRequiresInstantiation = true;
Douglas Gregora1f49972009-05-13 00:25:59 +00003125 if (PrevDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003126 if (PrevDecl->getSpecializationKind()
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003127 == TSK_ExplicitInstantiationDefinition) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003128 // This particular specialization has already been declared or
3129 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorf61eca92009-05-13 18:28:20 +00003130 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
3131 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003132 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003133 diag::note_previous_explicit_instantiation);
Douglas Gregora1f49972009-05-13 00:25:59 +00003134 return DeclPtrTy::make(PrevDecl);
3135 }
3136
Douglas Gregorf61eca92009-05-13 18:28:20 +00003137 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003138 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorf61eca92009-05-13 18:28:20 +00003139 // For a given set of template parameters, if an explicit
3140 // instantiation of a template appears after a declaration of
3141 // an explicit specialization for that template, the explicit
3142 // instantiation has no effect.
3143 if (!getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00003144 Diag(TemplateNameLoc,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003145 diag::ext_explicit_instantiation_after_specialization)
3146 << Context.getTypeDeclType(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003147 Diag(PrevDecl->getLocation(),
Douglas Gregorf61eca92009-05-13 18:28:20 +00003148 diag::note_previous_template_specialization);
3149 }
3150
3151 // Create a new class template specialization declaration node
3152 // for this explicit specialization. This node is only used to
3153 // record the existence of this explicit instantiation for
3154 // accurate reproduction of the source code; we don't actually
3155 // use it for anything, since it is semantically irrelevant.
3156 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003157 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorf61eca92009-05-13 18:28:20 +00003158 ClassTemplate->getDeclContext(),
3159 TemplateNameLoc,
3160 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003161 Converted, 0);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003162 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003163 CurContext->addDecl(Specialization);
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003164 return DeclPtrTy::make(PrevDecl);
Douglas Gregorf61eca92009-05-13 18:28:20 +00003165 }
3166
3167 // If we have already (implicitly) instantiated this
3168 // specialization, there is less work to do.
3169 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
3170 SpecializationRequiresInstantiation = false;
3171
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003172 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3173 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3174 // Since the only prior class template specialization with these
3175 // arguments was referenced but not declared, reuse that
3176 // declaration node as our own, updating its source location to
3177 // reflect our new declaration.
3178 Specialization = PrevDecl;
3179 Specialization->setLocation(TemplateNameLoc);
3180 PrevDecl = 0;
3181 }
3182 }
3183
3184 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003185 // Create a new class template specialization declaration node for
3186 // this explicit specialization.
3187 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003188 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003189 ClassTemplate->getDeclContext(),
3190 TemplateNameLoc,
3191 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003192 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003193
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003194 if (PrevDecl) {
3195 // Remove the previous declaration from the folding set, since we want
3196 // to introduce a new declaration.
3197 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3198 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3199 }
3200
3201 // Insert the new specialization.
3202 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003203 }
3204
3205 // Build the fully-sugared type for this explicit instantiation as
3206 // the user wrote in the explicit instantiation itself. This means
3207 // that we'll pretty-print the type retrieved from the
3208 // specialization's declaration the way that the user actually wrote
3209 // the explicit instantiation, rather than formatting the name based
3210 // on the "canonical" representation used to store the template
3211 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003212 QualType WrittenTy
3213 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003214 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003215 TemplateArgs.size(),
3216 Context.getTypeDeclType(Specialization));
3217 Specialization->setTypeAsWritten(WrittenTy);
3218 TemplateArgsIn.release();
3219
3220 // Add the explicit instantiation into its lexical context. However,
3221 // since explicit instantiations are never found by name lookup, we
3222 // just put it into the declaration context directly.
3223 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003224 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003225
John McCall1806c272009-09-11 07:25:08 +00003226 Specialization->setPointOfInstantiation(TemplateNameLoc);
3227
Douglas Gregora1f49972009-05-13 00:25:59 +00003228 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003229 // A definition of a class template or class member template
3230 // shall be in scope at the point of the explicit instantiation of
3231 // the class template or class member template.
3232 //
3233 // This check comes when we actually try to perform the
3234 // instantiation.
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003235 TemplateSpecializationKind TSK
Mike Stump11289f42009-09-09 15:08:12 +00003236 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003237 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor67da0d92009-05-15 17:59:04 +00003238 if (SpecializationRequiresInstantiation)
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003239 InstantiateClassTemplateSpecialization(Specialization, TSK);
Douglas Gregor85673582009-05-18 17:01:57 +00003240 else // Instantiate the members of this class template specialization.
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003241 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization,
3242 TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003243
3244 return DeclPtrTy::make(Specialization);
3245}
3246
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003247// Explicit instantiation of a member class of a class template.
3248Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003249Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003250 SourceLocation ExternLoc,
3251 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003252 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003253 SourceLocation KWLoc,
3254 const CXXScopeSpec &SS,
3255 IdentifierInfo *Name,
3256 SourceLocation NameLoc,
3257 AttributeList *Attr) {
3258
Douglas Gregord6ab8742009-05-28 23:31:59 +00003259 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003260 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00003261 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00003262 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00003263 MultiTemplateParamsArg(*this, 0, 0),
3264 Owned, IsDependent);
3265 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3266
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003267 if (!TagD)
3268 return true;
3269
3270 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3271 if (Tag->isEnum()) {
3272 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3273 << Context.getTypeDeclType(Tag);
3274 return true;
3275 }
3276
Douglas Gregorb8006faf2009-05-27 17:30:49 +00003277 if (Tag->isInvalidDecl())
3278 return true;
3279
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003280 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3281 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3282 if (!Pattern) {
3283 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3284 << Context.getTypeDeclType(Record);
3285 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3286 return true;
3287 }
3288
3289 // C++0x [temp.explicit]p2:
3290 // [...] An explicit instantiation shall appear in an enclosing
3291 // namespace of its template. [...]
3292 //
3293 // This is C++ DR 275.
3294 if (getLangOptions().CPlusPlus0x) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003295 // FIXME: In C++98, we would like to turn these errors into warnings,
3296 // dependent on a -Wc++0x flag.
Mike Stump11289f42009-09-09 15:08:12 +00003297 DeclContext *PatternContext
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003298 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
3299 if (!CurContext->Encloses(PatternContext)) {
3300 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
3301 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
3302 Diag(Pattern->getLocation(), diag::note_previous_declaration);
3303 }
3304 }
3305
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003306 TemplateSpecializationKind TSK
Mike Stump11289f42009-09-09 15:08:12 +00003307 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003308 : TSK_ExplicitInstantiationDeclaration;
Mike Stump11289f42009-09-09 15:08:12 +00003309
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003310 if (!Record->getDefinition(Context)) {
3311 // If the class has a definition, instantiate it (and all of its
3312 // members, recursively).
3313 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
Mike Stump11289f42009-09-09 15:08:12 +00003314 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregorb4850462009-05-14 23:26:13 +00003315 getTemplateInstantiationArgs(Record),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003316 TSK))
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003317 return true;
John McCall76d824f2009-08-25 22:02:44 +00003318 } else // Instantiate all of the members of the class.
Mike Stump11289f42009-09-09 15:08:12 +00003319 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003320 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003321
Mike Stump87c57ac2009-05-16 07:39:55 +00003322 // FIXME: We don't have any representation for explicit instantiations of
3323 // member classes. Such a representation is not needed for compilation, but it
3324 // should be available for clients that want to see all of the declarations in
3325 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003326 return TagD;
3327}
3328
Douglas Gregor333489b2009-03-27 23:10:48 +00003329Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00003330Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3331 const CXXScopeSpec &SS, IdentifierInfo *Name,
3332 SourceLocation TagLoc, SourceLocation NameLoc) {
3333 // This has to hold, because SS is expected to be defined.
3334 assert(Name && "Expected a name in a dependent tag");
3335
3336 NestedNameSpecifier *NNS
3337 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3338 if (!NNS)
3339 return true;
3340
3341 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
3342 if (T.isNull())
3343 return true;
3344
3345 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
3346 QualType ElabType = Context.getElaboratedType(T, TagKind);
3347
3348 return ElabType.getAsOpaquePtr();
3349}
3350
3351Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00003352Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3353 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00003354 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00003355 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3356 if (!NNS)
3357 return true;
3358
3359 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003360 if (T.isNull())
3361 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00003362 return T.getAsOpaquePtr();
3363}
3364
Douglas Gregordce2b622009-04-01 00:28:59 +00003365Sema::TypeResult
3366Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3367 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003368 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003369 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00003370 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00003371 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00003372 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00003373 assert(TemplateId && "Expected a template specialization type");
3374
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003375 if (computeDeclContext(SS, false)) {
3376 // If we can compute a declaration context, then the "typename"
3377 // keyword was superfluous. Just build a QualifiedNameType to keep
3378 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00003379
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003380 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
3381 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
3382 }
Mike Stump11289f42009-09-09 15:08:12 +00003383
Douglas Gregor12bbfe12009-09-02 13:05:45 +00003384 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00003385}
3386
Douglas Gregor333489b2009-03-27 23:10:48 +00003387/// \brief Build the type that describes a C++ typename specifier,
3388/// e.g., "typename T::type".
3389QualType
3390Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
3391 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003392 CXXRecordDecl *CurrentInstantiation = 0;
3393 if (NNS->isDependent()) {
3394 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00003395
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003396 // If the nested-name-specifier does not refer to the current
3397 // instantiation, then build a typename type.
3398 if (!CurrentInstantiation)
3399 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00003400
Douglas Gregorc707da62009-09-02 13:12:51 +00003401 // The nested-name-specifier refers to the current instantiation, so the
3402 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00003403 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00003404 // extraneous "typename" keywords, and we retroactively apply this DR to
3405 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003406 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003407
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003408 DeclContext *Ctx = 0;
3409
3410 if (CurrentInstantiation)
3411 Ctx = CurrentInstantiation;
3412 else {
3413 CXXScopeSpec SS;
3414 SS.setScopeRep(NNS);
3415 SS.setRange(Range);
3416 if (RequireCompleteDeclContext(SS))
3417 return QualType();
3418
3419 Ctx = computeDeclContext(SS);
3420 }
Douglas Gregor333489b2009-03-27 23:10:48 +00003421 assert(Ctx && "No declaration context?");
3422
3423 DeclarationName Name(&II);
Mike Stump11289f42009-09-09 15:08:12 +00003424 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
Douglas Gregor333489b2009-03-27 23:10:48 +00003425 false);
3426 unsigned DiagID = 0;
3427 Decl *Referenced = 0;
3428 switch (Result.getKind()) {
3429 case LookupResult::NotFound:
3430 if (Ctx->isTranslationUnit())
3431 DiagID = diag::err_typename_nested_not_found_global;
3432 else
3433 DiagID = diag::err_typename_nested_not_found;
3434 break;
3435
3436 case LookupResult::Found:
3437 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3438 // We found a type. Build a QualifiedNameType, since the
3439 // typename-specifier was just sugar. FIXME: Tell
3440 // QualifiedNameType that it has a "typename" prefix.
3441 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3442 }
3443
3444 DiagID = diag::err_typename_nested_not_type;
3445 Referenced = Result.getAsDecl();
3446 break;
3447
3448 case LookupResult::FoundOverloaded:
3449 DiagID = diag::err_typename_nested_not_type;
3450 Referenced = *Result.begin();
3451 break;
3452
3453 case LookupResult::AmbiguousBaseSubobjectTypes:
3454 case LookupResult::AmbiguousBaseSubobjects:
3455 case LookupResult::AmbiguousReference:
3456 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3457 return QualType();
3458 }
3459
3460 // If we get here, it's because name lookup did not find a
3461 // type. Emit an appropriate diagnostic and return an error.
3462 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3463 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3464 else
3465 Diag(Range.getEnd(), DiagID) << Range << Name;
3466 if (Referenced)
3467 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3468 << Name;
3469 return QualType();
3470}
Douglas Gregor15acfb92009-08-06 16:20:37 +00003471
3472namespace {
3473 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00003474 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3475 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00003476 SourceLocation Loc;
3477 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00003478
Douglas Gregor15acfb92009-08-06 16:20:37 +00003479 public:
Mike Stump11289f42009-09-09 15:08:12 +00003480 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00003481 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003482 DeclarationName Entity)
3483 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00003484 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00003485
3486 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00003487 /// transformed.
3488 ///
3489 /// For the purposes of type reconstruction, a type has already been
3490 /// transformed if it is NULL or if it is not dependent.
3491 bool AlreadyTransformed(QualType T) {
3492 return T.isNull() || !T->isDependentType();
3493 }
Mike Stump11289f42009-09-09 15:08:12 +00003494
3495 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00003496 /// rebuilt.
3497 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00003498
Douglas Gregor15acfb92009-08-06 16:20:37 +00003499 /// \brief Returns the name of the entity whose type is being rebuilt.
3500 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00003501
Douglas Gregor15acfb92009-08-06 16:20:37 +00003502 /// \brief Transforms an expression by returning the expression itself
3503 /// (an identity function).
3504 ///
3505 /// FIXME: This is completely unsafe; we will need to actually clone the
3506 /// expressions.
3507 Sema::OwningExprResult TransformExpr(Expr *E) {
3508 return getSema().Owned(E);
3509 }
Mike Stump11289f42009-09-09 15:08:12 +00003510
Douglas Gregor15acfb92009-08-06 16:20:37 +00003511 /// \brief Transforms a typename type by determining whether the type now
3512 /// refers to a member of the current instantiation, and then
3513 /// type-checking and building a QualifiedNameType (when possible).
3514 QualType TransformTypenameType(const TypenameType *T);
3515 };
3516}
3517
Mike Stump11289f42009-09-09 15:08:12 +00003518QualType
Douglas Gregor15acfb92009-08-06 16:20:37 +00003519CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3520 NestedNameSpecifier *NNS
3521 = TransformNestedNameSpecifier(T->getQualifier(),
3522 /*FIXME:*/SourceRange(getBaseLocation()));
3523 if (!NNS)
3524 return QualType();
3525
3526 // If the nested-name-specifier did not change, and we cannot compute the
3527 // context corresponding to the nested-name-specifier, then this
3528 // typename type will not change; exit early.
3529 CXXScopeSpec SS;
3530 SS.setRange(SourceRange(getBaseLocation()));
3531 SS.setScopeRep(NNS);
3532 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3533 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003534
3535 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00003536 // QualifiedNameType.
3537 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00003538 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00003539 = TransformType(QualType(TemplateId, 0));
3540 if (NewTemplateId.isNull())
3541 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003542
Douglas Gregor15acfb92009-08-06 16:20:37 +00003543 if (NNS == T->getQualifier() &&
3544 NewTemplateId == QualType(TemplateId, 0))
3545 return QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003546
Douglas Gregor15acfb92009-08-06 16:20:37 +00003547 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3548 }
Mike Stump11289f42009-09-09 15:08:12 +00003549
Douglas Gregor15acfb92009-08-06 16:20:37 +00003550 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3551}
3552
3553/// \brief Rebuilds a type within the context of the current instantiation.
3554///
Mike Stump11289f42009-09-09 15:08:12 +00003555/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00003556/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00003557/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00003558/// partial specialization thereof). This routine will rebuild that type now
3559/// that we have entered the declarator's scope, which may produce different
3560/// canonical types, e.g.,
3561///
3562/// \code
3563/// template<typename T>
3564/// struct X {
3565/// typedef T* pointer;
3566/// pointer data();
3567/// };
3568///
3569/// template<typename T>
3570/// typename X<T>::pointer X<T>::data() { ... }
3571/// \endcode
3572///
3573/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3574/// since we do not know that we can look into X<T> when we parsed the type.
3575/// This function will rebuild the type, performing the lookup of "pointer"
3576/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3577/// as the canonical type of T*, allowing the return types of the out-of-line
3578/// definition and the declaration to match.
3579QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3580 DeclarationName Name) {
3581 if (T.isNull() || !T->isDependentType())
3582 return T;
Mike Stump11289f42009-09-09 15:08:12 +00003583
Douglas Gregor15acfb92009-08-06 16:20:37 +00003584 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3585 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00003586}
Douglas Gregorbe999392009-09-15 16:23:51 +00003587
3588/// \brief Produces a formatted string that describes the binding of
3589/// template parameters to template arguments.
3590std::string
3591Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3592 const TemplateArgumentList &Args) {
3593 std::string Result;
3594
3595 if (!Params || Params->size() == 0)
3596 return Result;
3597
3598 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3599 if (I == 0)
3600 Result += "[with ";
3601 else
3602 Result += ", ";
3603
3604 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
3605 Result += Id->getName();
3606 } else {
3607 Result += '$';
3608 Result += llvm::utostr(I);
3609 }
3610
3611 Result += " = ";
3612
3613 switch (Args[I].getKind()) {
3614 case TemplateArgument::Null:
3615 Result += "<no value>";
3616 break;
3617
3618 case TemplateArgument::Type: {
3619 std::string TypeStr;
3620 Args[I].getAsType().getAsStringInternal(TypeStr,
3621 Context.PrintingPolicy);
3622 Result += TypeStr;
3623 break;
3624 }
3625
3626 case TemplateArgument::Declaration: {
3627 bool Unnamed = true;
3628 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
3629 if (ND->getDeclName()) {
3630 Unnamed = false;
3631 Result += ND->getNameAsString();
3632 }
3633 }
3634
3635 if (Unnamed) {
3636 Result += "<anonymous>";
3637 }
3638 break;
3639 }
3640
3641 case TemplateArgument::Integral: {
3642 Result += Args[I].getAsIntegral()->toString(10);
3643 break;
3644 }
3645
3646 case TemplateArgument::Expression: {
3647 assert(false && "No expressions in deduced template arguments!");
3648 Result += "<expression>";
3649 break;
3650 }
3651
3652 case TemplateArgument::Pack:
3653 // FIXME: Format template argument packs
3654 Result += "<template argument pack>";
3655 break;
3656 }
3657 }
3658
3659 Result += ']';
3660 return Result;
3661}