blob: c243765bec78aea05d84899fb3b81c3f52cc193f [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-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 Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000020#include "llvm/Support/Compiler.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000021
22using namespace clang;
23
Douglas Gregor2dd078a2009-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;
30
31 if (isa<TemplateDecl>(D))
32 return D;
33
34 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 }
55
56 return 0;
57 }
58
59 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
60 if (!Ovl)
61 return 0;
62
63 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 }
74
75 if (F != FEnd) {
76 // Build an overloaded function decl containing only the
77 // function templates in Ovl.
78 OverloadedFunctionDecl *OvlTemplate
79 = 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 }
88
89 return OvlTemplate;
90 }
91
92 return FuncTmpl;
93 }
94 }
95
96 return 0;
97}
98
99TemplateNameKind Sema::isTemplateName(Scope *S,
100 const IdentifierInfo &II,
101 SourceLocation IdLoc,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000102 const CXXScopeSpec *SS,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000103 TypeTy *ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000104 bool EnteringContext,
Douglas Gregor2dd078a2009-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.
112 assert((!SS || !SS->isSet()) &&
113 "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 }
124
125 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
130 // expression or the declaration context associated with a prior
131 // nested-name-specifier.
132
133 // The declaration context must be complete.
134 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
135 return TNK_Non_template;
136
137 Found = LookupQualifiedName(LookupCtx, &II, LookupOrdinaryName);
138
139 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
142 // immediately followed by an identifier followed by a <, the
143 // identifier must be looked up to determine whether the < is the
144 // beginning of a template argument list (14.2) or a less-than operator.
145 // 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
147 // 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) {
156 // We cannot look into a dependent object type or
157 return TNK_Non_template;
158 } else {
159 // Perform unqualified name lookup in the current scope.
160 Found = LookupName(S, &II, LookupOrdinaryName);
161 }
Douglas Gregor495c35d2009-08-25 22:51:20 +0000162
163 // FIXME: Cope with ambiguous name-lookup results.
164 assert(!Found.isAmbiguous() &&
165 "Cannot handle template name-lookup ambiguities");
Douglas Gregor7532dc62009-03-30 22:58:21 +0000166
Douglas Gregor2dd078a2009-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:
173 // [...] If the lookup in the class of the object expression finds a
174 // 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);
180
181 if (!OuterTemplate) {
182 // - if the name is not found, the name found in the class of the
183 // object expression is used, otherwise
184 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
185 // - if the name is found in the context of the entire
186 // postfix-expression and does not name a class template, the name
187 // 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
190 // entity as the one found in the class of the object expression,
191 // 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);
198
199 // Recover by taking the template that we found in the object
200 // expression's type.
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000201 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000202 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000203 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000204
205 if (SS && SS->isSet() && !SS->isInvalid()) {
206 NestedNameSpecifier *Qualifier
207 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
208 if (OverloadedFunctionDecl *Ovl
209 = dyn_cast<OverloadedFunctionDecl>(Template))
210 TemplateResult
211 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
212 Ovl));
213 else
214 TemplateResult
215 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
216 cast<TemplateDecl>(Template)));
217 } else if (OverloadedFunctionDecl *Ovl
218 = dyn_cast<OverloadedFunctionDecl>(Template)) {
219 TemplateResult = TemplateTy::make(TemplateName(Ovl));
220 } else {
221 TemplateResult = TemplateTy::make(
222 TemplateName(cast<TemplateDecl>(Template)));
223 }
224
225 if (isa<ClassTemplateDecl>(Template) ||
226 isa<TemplateTemplateParmDecl>(Template))
227 return TNK_Type_template;
228
229 assert((isa<FunctionTemplateDecl>(Template) ||
230 isa<OverloadedFunctionDecl>(Template)) &&
231 "Unhandled template kind in Sema::isTemplateName");
232 return TNK_Function_template;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000233}
234
Douglas Gregor72c3f312008-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 Gregorf57172b2008-12-08 18:40:42 +0000240 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-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).
249 Diag(Loc, diag::err_template_param_shadow)
250 << cast<NamedDecl>(PrevDecl)->getDeclName();
251 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
252 return true;
253}
254
Douglas Gregor2943aed2009-03-03 04:44:36 +0000255/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-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 Lattnerb28317a2009-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 Gregoraaba5e32009-02-04 19:02:06 +0000261 return Temp;
262 }
263 return 0;
264}
265
Douglas Gregor72c3f312008-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
272/// ParamName is the location of the parameter name (if any).
273/// If the type parameter has a default argument, it will be added
274/// later via ActOnTypeParameterDefault.
Anders Carlsson941df7d2009-06-12 19:58:00 +0000275Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
276 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000277 SourceLocation KeyLoc,
278 IdentifierInfo *ParamName,
279 SourceLocation ParamNameLoc,
280 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000281 assert(S->isTemplateParamScope() &&
282 "Template type parameter not in template parameter scope!");
283 bool Invalid = false;
284
285 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000286 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000287 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000288 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
289 PrevDecl);
290 }
291
Douglas Gregorddc29e12009-02-06 22:42:48 +0000292 SourceLocation Loc = ParamNameLoc;
293 if (!ParamName)
294 Loc = KeyLoc;
295
Douglas Gregor72c3f312008-12-05 18:15:24 +0000296 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000297 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000298 Depth, Position, ParamName, Typename,
299 Ellipsis);
Douglas Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000305 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000306 IdResolver.AddDecl(Param);
307 }
308
Chris Lattnerb28317a2009-03-28 19:18:32 +0000309 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000310}
311
Douglas Gregord684b002009-02-10 19:49:53 +0000312/// ActOnTypeParameterDefault - Adds a default argument (the type
313/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000314void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000315 SourceLocation EqualLoc,
316 SourceLocation DefaultLoc,
317 TypeTy *DefaultT) {
318 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000319 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000320 // FIXME: Preserve type source info.
321 QualType Default = GetTypeFromParser(DefaultT);
Douglas Gregord684b002009-02-10 19:49:53 +0000322
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000323 // C++0x [temp.param]p9:
324 // A default template-argument may be specified for any kind of
325 // template-parameter that is not a template parameter pack.
326 if (Parm->isParameterPack()) {
327 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000328 return;
329 }
330
Douglas Gregord684b002009-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.
334
335 // 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 Gregor2943aed2009-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.
349QualType
350Sema::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() ||
358 // -- pointer to object or pointer to function,
359 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000360 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
361 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Douglas Gregor2943aed2009-03-03 04:44:36 +0000362 // -- reference to object or reference to function,
363 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 Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000392Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
393 unsigned Depth,
394 unsigned Position) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000395 DeclaratorInfo *DInfo = 0;
396 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000397
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000398 assert(S->isTemplateParamScope() &&
399 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000400 bool Invalid = false;
401
402 IdentifierInfo *ParamName = D.getIdentifier();
403 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000404 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000405 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000406 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000407 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000408 }
409
Douglas Gregor2943aed2009-03-03 04:44:36 +0000410 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000411 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000412 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000413 Invalid = true;
414 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000415
Douglas Gregor72c3f312008-12-05 18:15:24 +0000416 NonTypeTemplateParmDecl *Param
417 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000418 Depth, Position, ParamName, T, DInfo);
Douglas Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000424 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000425 IdResolver.AddDecl(Param);
426 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000427 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000428}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000429
Douglas Gregord684b002009-02-10 19:49:53 +0000430/// \brief Adds a default argument to the given non-type template
431/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000432void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000433 SourceLocation EqualLoc,
434 ExprArg DefaultE) {
435 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000436 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000437 Expr *Default = static_cast<Expr *>(DefaultE.get());
438
439 // 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.
442
443 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000444 TemplateArgument Converted;
445 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
446 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000447 TemplateParm->setInvalidDecl();
448 return;
449 }
450
Anders Carlssone9146f22009-05-01 19:49:17 +0000451 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000452}
453
Douglas Gregoraaba5e32009-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 Lattnerb28317a2009-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,
464 unsigned Position)
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000465{
466 assert(S->isTemplateParamScope() &&
467 "Template template parameter not in template parameter scope!");
468
469 // Construct the parameter object.
470 TemplateTemplateParmDecl *Param =
471 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
472 Position, Name,
473 (TemplateParameterList*)Params);
474
475 // Make sure the parameter is valid.
476 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
477 // do anything yet. However, if the template parameter list or (eventual)
478 // default value is ever invalidated, that will propagate here.
479 bool Invalid = false;
480 if (Invalid) {
481 Param->setInvalidDecl();
482 }
483
484 // If the tt-param has a name, then link the identifier into the scope
485 // and lookup mechanisms.
486 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000487 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000488 IdResolver.AddDecl(Param);
489 }
490
Chris Lattnerb28317a2009-03-28 19:18:32 +0000491 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000492}
493
Douglas Gregord684b002009-02-10 19:49:53 +0000494/// \brief Adds a default argument to the given template template
495/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000496void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000497 SourceLocation EqualLoc,
498 ExprArg DefaultE) {
499 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000500 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000501
502 // Since a template-template parameter's default argument is an
503 // id-expression, it must be a DeclRefExpr.
504 DeclRefExpr *Default
505 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
506
507 // C++ [temp.param]p14:
508 // A template-parameter shall not be used in its own default argument.
509 // FIXME: Implement this check! Needs a recursive walk over the types.
510
511 // Check the well-formedness of the template argument.
512 if (!isa<TemplateDecl>(Default->getDecl())) {
513 Diag(Default->getSourceRange().getBegin(),
514 diag::err_template_arg_must_be_template)
515 << Default->getSourceRange();
516 TemplateParm->setInvalidDecl();
517 return;
518 }
519 if (CheckTemplateArgument(TemplateParm, Default)) {
520 TemplateParm->setInvalidDecl();
521 return;
522 }
523
524 DefaultE.release();
525 TemplateParm->setDefaultArgument(Default);
526}
527
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000528/// ActOnTemplateParameterList - Builds a TemplateParameterList that
529/// contains the template parameters in Params/NumParams.
530Sema::TemplateParamsTy *
531Sema::ActOnTemplateParameterList(unsigned Depth,
532 SourceLocation ExportLoc,
533 SourceLocation TemplateLoc,
534 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000535 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000536 SourceLocation RAngleLoc) {
537 if (ExportLoc.isValid())
538 Diag(ExportLoc, diag::note_template_export_unsupported);
539
Douglas Gregorddc29e12009-02-06 22:42:48 +0000540 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
541 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000542}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000543
Douglas Gregor212e81c2009-03-25 00:13:59 +0000544Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000545Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000546 SourceLocation KWLoc, const CXXScopeSpec &SS,
547 IdentifierInfo *Name, SourceLocation NameLoc,
548 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000549 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000550 AccessSpecifier AS) {
Douglas Gregor05396e22009-08-25 17:23:04 +0000551 assert(TemplateParams && TemplateParams->size() > 0 &&
552 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000553 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000554 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000555
556 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000557 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000558 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000559
560 TagDecl::TagKind Kind;
561 switch (TagSpec) {
562 default: assert(0 && "Unknown tag type!");
563 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
564 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
565 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
566 }
567
568 // There is no such thing as an unnamed class template.
569 if (!Name) {
570 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000571 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000572 }
573
574 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000575 DeclContext *SemanticContext;
576 LookupResult Previous;
577 if (SS.isNotEmpty() && !SS.isInvalid()) {
578 SemanticContext = computeDeclContext(SS, true);
579 if (!SemanticContext) {
580 // FIXME: Produce a reasonable diagnostic here
581 return true;
582 }
583
584 Previous = LookupQualifiedName(SemanticContext, Name, LookupOrdinaryName,
585 true);
586 } else {
587 SemanticContext = CurContext;
588 Previous = LookupName(S, Name, LookupOrdinaryName, true);
589 }
590
Douglas Gregorddc29e12009-02-06 22:42:48 +0000591 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
592 NamedDecl *PrevDecl = 0;
593 if (Previous.begin() != Previous.end())
594 PrevDecl = *Previous.begin();
595
Douglas Gregor05396e22009-08-25 17:23:04 +0000596 if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000597 PrevDecl = 0;
598
Douglas Gregorddc29e12009-02-06 22:42:48 +0000599 // If there is a previous declaration with the same name, check
600 // whether this is a valid redeclaration.
601 ClassTemplateDecl *PrevClassTemplate
602 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
603 if (PrevClassTemplate) {
604 // Ensure that the template parameter lists are compatible.
605 if (!TemplateParameterListsAreEqual(TemplateParams,
606 PrevClassTemplate->getTemplateParameters(),
607 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000608 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000609
610 // C++ [temp.class]p4:
611 // In a redeclaration, partial specialization, explicit
612 // specialization or explicit instantiation of a class template,
613 // the class-key shall agree in kind with the original class
614 // template declaration (7.1.5.3).
615 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000616 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000617 Diag(KWLoc, diag::err_use_with_wrong_tag)
618 << Name
619 << CodeModificationHint::CreateReplacement(KWLoc,
620 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000621 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000622 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000623 }
624
Douglas Gregorddc29e12009-02-06 22:42:48 +0000625 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000626 if (TUK == TUK_Definition) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000627 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
628 Diag(NameLoc, diag::err_redefinition) << Name;
629 Diag(Def->getLocation(), diag::note_previous_definition);
630 // FIXME: Would it make sense to try to "forget" the previous
631 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000632 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000633 }
634 }
635 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
636 // Maybe we will complain about the shadowed template parameter.
637 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
638 // Just pretend that we didn't see the previous declaration.
639 PrevDecl = 0;
640 } else if (PrevDecl) {
641 // C++ [temp]p5:
642 // A class template shall not have the same name as any other
643 // template, class, function, object, enumeration, enumerator,
644 // namespace, or type in the same scope (3.3), except as specified
645 // in (14.5.4).
646 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
647 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000648 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000649 }
650
Douglas Gregord684b002009-02-10 19:49:53 +0000651 // Check the template parameter list of this declaration, possibly
652 // merging in the template parameter list from the previous class
653 // template declaration.
654 if (CheckTemplateParameterList(TemplateParams,
655 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
656 Invalid = true;
657
Douglas Gregor7da97d02009-05-10 22:57:19 +0000658 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000659 // declaration!
660
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000661 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000662 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000663 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000664 PrevClassTemplate->getTemplatedDecl() : 0,
665 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000666
667 ClassTemplateDecl *NewTemplate
668 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
669 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000670 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000671 NewClass->setDescribedClassTemplate(NewTemplate);
672
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000673 // Build the type for the class template declaration now.
674 QualType T =
675 Context.getTypeDeclType(NewClass,
676 PrevClassTemplate?
677 PrevClassTemplate->getTemplatedDecl() : 0);
678 assert(T->isDependentType() && "Class template type is not dependent?");
679 (void)T;
680
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000681 // Set the access specifier.
682 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
683
Douglas Gregorddc29e12009-02-06 22:42:48 +0000684 // Set the lexical context of these templates
685 NewClass->setLexicalDeclContext(CurContext);
686 NewTemplate->setLexicalDeclContext(CurContext);
687
John McCall0f434ec2009-07-31 02:45:11 +0000688 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000689 NewClass->startDefinition();
690
691 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000692 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000693
694 PushOnScopeChains(NewTemplate, S);
695
Douglas Gregord684b002009-02-10 19:49:53 +0000696 if (Invalid) {
697 NewTemplate->setInvalidDecl();
698 NewClass->setInvalidDecl();
699 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000700 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000701}
702
Douglas Gregord684b002009-02-10 19:49:53 +0000703/// \brief Checks the validity of a template parameter list, possibly
704/// considering the template parameter list from a previous
705/// declaration.
706///
707/// If an "old" template parameter list is provided, it must be
708/// equivalent (per TemplateParameterListsAreEqual) to the "new"
709/// template parameter list.
710///
711/// \param NewParams Template parameter list for a new template
712/// declaration. This template parameter list will be updated with any
713/// default arguments that are carried through from the previous
714/// template parameter list.
715///
716/// \param OldParams If provided, template parameter list from a
717/// previous declaration of the same template. Default template
718/// arguments will be merged from the old template parameter list to
719/// the new template parameter list.
720///
721/// \returns true if an error occurred, false otherwise.
722bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
723 TemplateParameterList *OldParams) {
724 bool Invalid = false;
725
726 // C++ [temp.param]p10:
727 // The set of default template-arguments available for use with a
728 // template declaration or definition is obtained by merging the
729 // default arguments from the definition (if in scope) and all
730 // declarations in scope in the same way default function
731 // arguments are (8.3.6).
732 bool SawDefaultArgument = false;
733 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000734
Anders Carlsson49d25572009-06-12 23:20:15 +0000735 bool SawParameterPack = false;
736 SourceLocation ParameterPackLoc;
737
Mike Stump1a35fde2009-02-11 23:03:27 +0000738 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000739 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000740 if (OldParams)
741 OldParam = OldParams->begin();
742
743 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
744 NewParamEnd = NewParams->end();
745 NewParam != NewParamEnd; ++NewParam) {
746 // Variables used to diagnose redundant default arguments
747 bool RedundantDefaultArg = false;
748 SourceLocation OldDefaultLoc;
749 SourceLocation NewDefaultLoc;
750
751 // Variables used to diagnose missing default arguments
752 bool MissingDefaultArg = false;
753
Anders Carlsson49d25572009-06-12 23:20:15 +0000754 // C++0x [temp.param]p11:
755 // If a template parameter of a class template is a template parameter pack,
756 // it must be the last template parameter.
757 if (SawParameterPack) {
758 Diag(ParameterPackLoc,
759 diag::err_template_param_pack_must_be_last_template_parameter);
760 Invalid = true;
761 }
762
Douglas Gregord684b002009-02-10 19:49:53 +0000763 // Merge default arguments for template type parameters.
764 if (TemplateTypeParmDecl *NewTypeParm
765 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
766 TemplateTypeParmDecl *OldTypeParm
767 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
768
Anders Carlsson49d25572009-06-12 23:20:15 +0000769 if (NewTypeParm->isParameterPack()) {
770 assert(!NewTypeParm->hasDefaultArgument() &&
771 "Parameter packs can't have a default argument!");
772 SawParameterPack = true;
773 ParameterPackLoc = NewTypeParm->getLocation();
774 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000775 NewTypeParm->hasDefaultArgument()) {
776 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
777 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
778 SawDefaultArgument = true;
779 RedundantDefaultArg = true;
780 PreviousDefaultArgLoc = NewDefaultLoc;
781 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
782 // Merge the default argument from the old declaration to the
783 // new declaration.
784 SawDefaultArgument = true;
785 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
786 OldTypeParm->getDefaultArgumentLoc(),
787 true);
788 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
789 } else if (NewTypeParm->hasDefaultArgument()) {
790 SawDefaultArgument = true;
791 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
792 } else if (SawDefaultArgument)
793 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000794 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +0000795 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000796 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000797 NonTypeTemplateParmDecl *OldNonTypeParm
798 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
799 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
800 NewNonTypeParm->hasDefaultArgument()) {
801 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
802 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
803 SawDefaultArgument = true;
804 RedundantDefaultArg = true;
805 PreviousDefaultArgLoc = NewDefaultLoc;
806 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
807 // Merge the default argument from the old declaration to the
808 // new declaration.
809 SawDefaultArgument = true;
810 // FIXME: We need to create a new kind of "default argument"
811 // expression that points to a previous template template
812 // parameter.
813 NewNonTypeParm->setDefaultArgument(
814 OldNonTypeParm->getDefaultArgument());
815 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
816 } else if (NewNonTypeParm->hasDefaultArgument()) {
817 SawDefaultArgument = true;
818 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
819 } else if (SawDefaultArgument)
820 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000821 } else {
Douglas Gregord684b002009-02-10 19:49:53 +0000822 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000823 TemplateTemplateParmDecl *NewTemplateParm
824 = cast<TemplateTemplateParmDecl>(*NewParam);
825 TemplateTemplateParmDecl *OldTemplateParm
826 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
827 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
828 NewTemplateParm->hasDefaultArgument()) {
829 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
830 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
831 SawDefaultArgument = true;
832 RedundantDefaultArg = true;
833 PreviousDefaultArgLoc = NewDefaultLoc;
834 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
835 // Merge the default argument from the old declaration to the
836 // new declaration.
837 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000838 // FIXME: We need to create a new kind of "default argument" expression
839 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000840 NewTemplateParm->setDefaultArgument(
841 OldTemplateParm->getDefaultArgument());
842 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
843 } else if (NewTemplateParm->hasDefaultArgument()) {
844 SawDefaultArgument = true;
845 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
846 } else if (SawDefaultArgument)
847 MissingDefaultArg = true;
848 }
849
850 if (RedundantDefaultArg) {
851 // C++ [temp.param]p12:
852 // A template-parameter shall not be given default arguments
853 // by two different declarations in the same scope.
854 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
855 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
856 Invalid = true;
857 } else if (MissingDefaultArg) {
858 // C++ [temp.param]p11:
859 // If a template-parameter has a default template-argument,
860 // all subsequent template-parameters shall have a default
861 // template-argument supplied.
862 Diag((*NewParam)->getLocation(),
863 diag::err_template_param_default_arg_missing);
864 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
865 Invalid = true;
866 }
867
868 // If we have an old template parameter list that we're merging
869 // in, move on to the next parameter.
870 if (OldParams)
871 ++OldParam;
872 }
873
874 return Invalid;
875}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000876
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000877/// \brief Match the given template parameter lists to the given scope
878/// specifier, returning the template parameter list that applies to the
879/// name.
880///
881/// \param DeclStartLoc the start of the declaration that has a scope
882/// specifier or a template parameter list.
883///
884/// \param SS the scope specifier that will be matched to the given template
885/// parameter lists. This scope specifier precedes a qualified name that is
886/// being declared.
887///
888/// \param ParamLists the template parameter lists, from the outermost to the
889/// innermost template parameter lists.
890///
891/// \param NumParamLists the number of template parameter lists in ParamLists.
892///
893/// \returns the template parameter list, if any, that corresponds to the
894/// name that is preceded by the scope specifier @p SS. This template
895/// parameter list may be have template parameters (if we're declaring a
896/// template) or may have no template parameters (if we're declaring a
897/// template specialization), or may be NULL (if we were's declaring isn't
898/// itself a template).
899TemplateParameterList *
900Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
901 const CXXScopeSpec &SS,
902 TemplateParameterList **ParamLists,
903 unsigned NumParamLists) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000904 // Find the template-ids that occur within the nested-name-specifier. These
905 // template-ids will match up with the template parameter lists.
906 llvm::SmallVector<const TemplateSpecializationType *, 4>
907 TemplateIdsInSpecifier;
908 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
909 NNS; NNS = NNS->getPrefix()) {
910 if (const TemplateSpecializationType *SpecType
911 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
912 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
913 if (!Template)
914 continue; // FIXME: should this be an error? probably...
915
Ted Kremenek6217b802009-07-29 21:53:49 +0000916 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000917 ClassTemplateSpecializationDecl *SpecDecl
918 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
919 // If the nested name specifier refers to an explicit specialization,
920 // we don't need a template<> header.
Douglas Gregorb88e8882009-07-30 17:40:51 +0000921 // FIXME: revisit this approach once we cope with specialization
922 // properly.
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000923 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
924 continue;
925 }
926
927 TemplateIdsInSpecifier.push_back(SpecType);
928 }
929 }
930
931 // Reverse the list of template-ids in the scope specifier, so that we can
932 // more easily match up the template-ids and the template parameter lists.
933 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
934
935 SourceLocation FirstTemplateLoc = DeclStartLoc;
936 if (NumParamLists)
937 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
938
939 // Match the template-ids found in the specifier to the template parameter
940 // lists.
941 unsigned Idx = 0;
942 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
943 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +0000944 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
945 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000946 if (Idx >= NumParamLists) {
947 // We have a template-id without a corresponding template parameter
948 // list.
949 if (DependentTemplateId) {
950 // FIXME: the location information here isn't great.
951 Diag(SS.getRange().getBegin(),
952 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +0000953 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000954 << SS.getRange();
955 } else {
956 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
957 << SS.getRange()
958 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
959 "template<> ");
960 }
961 return 0;
962 }
963
964 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +0000965 if (DependentTemplateId) {
966 TemplateDecl *Template
967 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
968
969 if (ClassTemplateDecl *ClassTemplate
970 = dyn_cast<ClassTemplateDecl>(Template)) {
971 TemplateParameterList *ExpectedTemplateParams = 0;
972 // Is this template-id naming the primary template?
973 if (Context.hasSameType(TemplateId,
974 ClassTemplate->getInjectedClassNameType(Context)))
975 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
976 // ... or a partial specialization?
977 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
978 = ClassTemplate->findPartialSpecialization(TemplateId))
979 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
980
981 if (ExpectedTemplateParams)
982 TemplateParameterListsAreEqual(ParamLists[Idx],
983 ExpectedTemplateParams,
984 true);
985 }
986 } else if (ParamLists[Idx]->size() > 0)
987 Diag(ParamLists[Idx]->getTemplateLoc(),
988 diag::err_template_param_list_matches_nontemplate)
989 << TemplateId
990 << ParamLists[Idx]->getSourceRange();
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000991 }
992
993 // If there were at least as many template-ids as there were template
994 // parameter lists, then there are no template parameter lists remaining for
995 // the declaration itself.
996 if (Idx >= NumParamLists)
997 return 0;
998
999 // If there were too many template parameter lists, complain about that now.
1000 if (Idx != NumParamLists - 1) {
1001 while (Idx < NumParamLists - 1) {
1002 Diag(ParamLists[Idx]->getTemplateLoc(),
1003 diag::err_template_spec_extra_headers)
1004 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1005 ParamLists[Idx]->getRAngleLoc());
1006 ++Idx;
1007 }
1008 }
1009
1010 // Return the last template parameter list, which corresponds to the
1011 // entity being declared.
1012 return ParamLists[NumParamLists - 1];
1013}
1014
Douglas Gregor40808ce2009-03-09 23:48:35 +00001015/// \brief Translates template arguments as provided by the parser
1016/// into template arguments used by semantic analysis.
1017static void
1018translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
1019 SourceLocation *TemplateArgLocs,
1020 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
1021 TemplateArgs.reserve(TemplateArgsIn.size());
1022
1023 void **Args = TemplateArgsIn.getArgs();
1024 bool *ArgIsType = TemplateArgsIn.getArgIsType();
1025 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
1026 TemplateArgs.push_back(
1027 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001028 //FIXME: Preserve type source info.
1029 Sema::GetTypeFromParser(Args[Arg]))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001030 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
1031 }
1032}
1033
Douglas Gregor7532dc62009-03-30 22:58:21 +00001034QualType Sema::CheckTemplateIdType(TemplateName Name,
1035 SourceLocation TemplateLoc,
1036 SourceLocation LAngleLoc,
1037 const TemplateArgument *TemplateArgs,
1038 unsigned NumTemplateArgs,
1039 SourceLocation RAngleLoc) {
1040 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001041 if (!Template) {
1042 // The template name does not resolve to a template, so we just
1043 // build a dependent template-id type.
Douglas Gregorc45c2322009-03-31 00:43:58 +00001044 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001045 NumTemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001046 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001047
Douglas Gregor40808ce2009-03-09 23:48:35 +00001048 // Check that the template argument list is well-formed for this
1049 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001050 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1051 NumTemplateArgs);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001052 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001053 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001054 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001055 return QualType();
1056
Anders Carlssonfb250522009-06-23 01:26:57 +00001057 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001058 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001059 "Converted template argument list is too short!");
1060
1061 QualType CanonType;
1062
Douglas Gregor7532dc62009-03-30 22:58:21 +00001063 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +00001064 TemplateArgs,
1065 NumTemplateArgs)) {
1066 // This class template specialization is a dependent
1067 // type. Therefore, its canonical type is another class template
1068 // specialization type that contains all of the converted
1069 // arguments in canonical form. This ensures that, e.g., A<T> and
1070 // A<T, T> have identical types when A is declared as:
1071 //
1072 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001073 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
1074 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001075 Converted.getFlatArguments(),
1076 Converted.flatSize());
Douglas Gregor1275ae02009-07-28 23:00:59 +00001077
1078 // FIXME: CanonType is not actually the canonical type, and unfortunately
1079 // it is a TemplateTypeSpecializationType that we will never use again.
1080 // In the future, we need to teach getTemplateSpecializationType to only
1081 // build the canonical type and return that to us.
1082 CanonType = Context.getCanonicalType(CanonType);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001083 } else if (ClassTemplateDecl *ClassTemplate
1084 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001085 // Find the class template specialization declaration that
1086 // corresponds to these arguments.
1087 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001088 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001089 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001090 Converted.flatSize(),
1091 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001092 void *InsertPos = 0;
1093 ClassTemplateSpecializationDecl *Decl
1094 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1095 if (!Decl) {
1096 // This is the first time we have referenced this class template
1097 // specialization. Create the canonical declaration and add it to
1098 // the set of specializations.
1099 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001100 ClassTemplate->getDeclContext(),
1101 TemplateLoc,
1102 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001103 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001104 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1105 Decl->setLexicalDeclContext(CurContext);
1106 }
1107
1108 CanonType = Context.getTypeDeclType(Decl);
1109 }
1110
1111 // Build the fully-sugared type for this class template
1112 // specialization, which refers back to the class template
1113 // specialization we created or found.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001114 //FIXME: Preserve type source info.
Douglas Gregor7532dc62009-03-30 22:58:21 +00001115 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1116 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001117}
1118
Douglas Gregorcc636682009-02-17 23:15:12 +00001119Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001120Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1121 SourceLocation LAngleLoc,
1122 ASTTemplateArgsPtr TemplateArgsIn,
1123 SourceLocation *TemplateArgLocs,
John McCallf1bbbb42009-09-04 01:14:41 +00001124 SourceLocation RAngleLoc,
1125 DeclSpec::TST TagSpec,
1126 SourceLocation TagLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001127 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001128
Douglas Gregor40808ce2009-03-09 23:48:35 +00001129 // Translate the parser's template argument list in our AST format.
1130 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1131 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001132
Douglas Gregor7532dc62009-03-30 22:58:21 +00001133 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001134 TemplateArgs.data(),
1135 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00001136 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001137 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001138
1139 if (Result.isNull())
1140 return true;
1141
John McCallf1bbbb42009-09-04 01:14:41 +00001142 // If we were given a tag specifier, verify it.
1143 if (TagSpec != DeclSpec::TST_unspecified) {
1144 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
1145
1146 if (const RecordType *T = Result->getAs<RecordType>()) {
1147 RecordDecl *D = T->getDecl();
1148
1149 IdentifierInfo *Id = D->getIdentifier();
1150 assert(Id && "templated class must have an identifier");
1151
1152 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1153 Diag(TagLoc, diag::err_use_with_wrong_tag)
1154 << Id
1155 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1156 D->getKindName());
1157 }
1158 }
1159 }
1160
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001161 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001162}
1163
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001164Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1165 SourceLocation TemplateNameLoc,
1166 SourceLocation LAngleLoc,
1167 const TemplateArgument *TemplateArgs,
1168 unsigned NumTemplateArgs,
1169 SourceLocation RAngleLoc) {
1170 // FIXME: Can we do any checking at this point? I guess we could check the
1171 // template arguments that we have against the template name, if the template
1172 // name refers to a single template. That's not a terribly common case,
1173 // though.
1174 return Owned(TemplateIdRefExpr::Create(Context,
1175 /*FIXME: New type?*/Context.OverloadTy,
1176 /*FIXME: Necessary?*/0,
1177 /*FIXME: Necessary?*/SourceRange(),
1178 Template, TemplateNameLoc, LAngleLoc,
1179 TemplateArgs,
1180 NumTemplateArgs, RAngleLoc));
1181}
1182
1183Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1184 SourceLocation TemplateNameLoc,
1185 SourceLocation LAngleLoc,
1186 ASTTemplateArgsPtr TemplateArgsIn,
1187 SourceLocation *TemplateArgLocs,
1188 SourceLocation RAngleLoc) {
1189 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1190
1191 // Translate the parser's template argument list in our AST format.
1192 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1193 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001194 TemplateArgsIn.release();
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001195
1196 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1197 TemplateArgs.data(), TemplateArgs.size(),
1198 RAngleLoc);
1199}
1200
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001201Sema::OwningExprResult
1202Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base,
1203 SourceLocation OpLoc,
1204 tok::TokenKind OpKind,
1205 const CXXScopeSpec &SS,
1206 TemplateTy TemplateD,
1207 SourceLocation TemplateNameLoc,
1208 SourceLocation LAngleLoc,
1209 ASTTemplateArgsPtr TemplateArgsIn,
1210 SourceLocation *TemplateArgLocs,
1211 SourceLocation RAngleLoc) {
1212 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1213
1214 // FIXME: We're going to end up looking up the template based on its name,
1215 // twice!
1216 DeclarationName Name;
1217 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
1218 Name = ActualTemplate->getDeclName();
1219 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
1220 Name = Ovl->getDeclName();
1221 else
1222 assert(false && "Cannot support dependent template names yet");
1223
1224 // Translate the parser's template argument list in our AST format.
1225 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1226 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1227 TemplateArgsIn.release();
1228
1229 // Do we have the save the actual template name? We might need it...
1230 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc,
1231 Name, true, LAngleLoc,
1232 TemplateArgs.data(), TemplateArgs.size(),
1233 RAngleLoc, DeclPtrTy(), &SS);
1234}
1235
Douglas Gregorc45c2322009-03-31 00:43:58 +00001236/// \brief Form a dependent template name.
1237///
1238/// This action forms a dependent template name given the template
1239/// name and its (presumably dependent) scope specifier. For
1240/// example, given "MetaFun::template apply", the scope specifier \p
1241/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1242/// of the "template" keyword, and "apply" is the \p Name.
1243Sema::TemplateTy
1244Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1245 const IdentifierInfo &Name,
1246 SourceLocation NameLoc,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001247 const CXXScopeSpec &SS,
1248 TypeTy *ObjectType) {
1249 if ((ObjectType &&
1250 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1251 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001252 // C++0x [temp.names]p5:
1253 // If a name prefixed by the keyword template is not the name of
1254 // a template, the program is ill-formed. [Note: the keyword
1255 // template may not be applied to non-template members of class
1256 // templates. -end note ] [ Note: as is the case with the
1257 // typename prefix, the template prefix is allowed in cases
1258 // where it is not strictly necessary; i.e., when the
1259 // nested-name-specifier or the expression on the left of the ->
1260 // or . is not dependent on a template-parameter, or the use
1261 // does not appear in the scope of a template. -end note]
1262 //
1263 // Note: C++03 was more strict here, because it banned the use of
1264 // the "template" keyword prior to a template-name that was not a
1265 // dependent name. C++ DR468 relaxed this requirement (the
1266 // "template" keyword is now permitted). We follow the C++0x
1267 // rules, even in C++03 mode, retroactively applying the DR.
1268 TemplateTy Template;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001269 TemplateNameKind TNK = isTemplateName(0, Name, NameLoc, &SS, ObjectType,
1270 false, Template);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001271 if (TNK == TNK_Non_template) {
1272 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1273 << &Name;
1274 return TemplateTy();
1275 }
1276
1277 return Template;
1278 }
1279
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001280 // FIXME: We need to be able to create a dependent template name with just
1281 // an identifier, to handle the x->template f<T> case.
1282 assert(!ObjectType &&
1283 "Cannot handle dependent template names without a nested-name-specifier");
1284
1285 NestedNameSpecifier *Qualifier
1286 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorc45c2322009-03-31 00:43:58 +00001287 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1288}
1289
Anders Carlsson436b1562009-06-13 00:33:33 +00001290bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1291 const TemplateArgument &Arg,
1292 TemplateArgumentListBuilder &Converted) {
1293 // Check template type parameter.
1294 if (Arg.getKind() != TemplateArgument::Type) {
1295 // C++ [temp.arg.type]p1:
1296 // A template-argument for a template-parameter which is a
1297 // type shall be a type-id.
1298
1299 // We have a template type parameter but the template argument
1300 // is not a type.
1301 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1302 Diag(Param->getLocation(), diag::note_template_param_here);
1303
1304 return true;
1305 }
1306
1307 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1308 return true;
1309
1310 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001311 Converted.Append(
Anders Carlsson436b1562009-06-13 00:33:33 +00001312 TemplateArgument(Arg.getLocation(),
1313 Context.getCanonicalType(Arg.getAsType())));
1314 return false;
1315}
1316
Douglas Gregorc15cb382009-02-09 23:23:08 +00001317/// \brief Check that the given template argument list is well-formed
1318/// for specializing the given template.
1319bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1320 SourceLocation TemplateLoc,
1321 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001322 const TemplateArgument *TemplateArgs,
1323 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001324 SourceLocation RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001325 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001326 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001327 TemplateParameterList *Params = Template->getTemplateParameters();
1328 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001329 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001330 bool Invalid = false;
1331
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001332 bool HasParameterPack =
1333 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1334
1335 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00001336 (NumArgs < Params->getMinRequiredArguments() &&
1337 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001338 // FIXME: point at either the first arg beyond what we can handle,
1339 // or the '>', depending on whether we have too many or too few
1340 // arguments.
1341 SourceRange Range;
1342 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001343 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001344 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1345 << (NumArgs > NumParams)
1346 << (isa<ClassTemplateDecl>(Template)? 0 :
1347 isa<FunctionTemplateDecl>(Template)? 1 :
1348 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1349 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001350 Diag(Template->getLocation(), diag::note_template_decl_here)
1351 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001352 Invalid = true;
1353 }
1354
1355 // C++ [temp.arg]p1:
1356 // [...] The type and form of each template-argument specified in
1357 // a template-id shall match the type and form specified for the
1358 // corresponding parameter declared by the template in its
1359 // template-parameter-list.
1360 unsigned ArgIdx = 0;
1361 for (TemplateParameterList::iterator Param = Params->begin(),
1362 ParamEnd = Params->end();
1363 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00001364 if (ArgIdx > NumArgs && PartialTemplateArgs)
1365 break;
1366
Douglas Gregorc15cb382009-02-09 23:23:08 +00001367 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001368 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001369 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001370 // Retrieve the default template argument from the template
1371 // parameter.
1372 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001373 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001374 // We have an empty argument pack.
1375 Converted.BeginPack();
1376 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001377 break;
1378 }
1379
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001380 if (!TTP->hasDefaultArgument())
1381 break;
1382
Douglas Gregor40808ce2009-03-09 23:48:35 +00001383 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001384
1385 // If the argument type is dependent, instantiate it now based
1386 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001387 if (ArgType->isDependentType()) {
1388 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001389 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001390 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001391 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001392
Anders Carlssone9c904b2009-06-05 04:47:51 +00001393 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001394 /*TakeArgs=*/false);
Douglas Gregord6350ae2009-08-28 20:31:08 +00001395 ArgType = SubstType(ArgType,
1396 MultiLevelTemplateArgumentList(TemplateArgs),
John McCallce3ff2b2009-08-25 22:02:44 +00001397 TTP->getDefaultArgumentLoc(),
1398 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001399 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001400
1401 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001402 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001403
Douglas Gregor40808ce2009-03-09 23:48:35 +00001404 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001405 } else if (NonTypeTemplateParmDecl *NTTP
1406 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1407 if (!NTTP->hasDefaultArgument())
1408 break;
1409
Anders Carlsson3b56c002009-06-11 16:06:49 +00001410 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001411 Template, Converted.getFlatArguments(),
Anders Carlsson3b56c002009-06-11 16:06:49 +00001412 Converted.flatSize(),
1413 SourceRange(TemplateLoc, RAngleLoc));
1414
1415 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001416 /*TakeArgs=*/false);
Anders Carlsson3b56c002009-06-11 16:06:49 +00001417
Douglas Gregord6350ae2009-08-28 20:31:08 +00001418 Sema::OwningExprResult E
1419 = SubstExpr(NTTP->getDefaultArgument(),
1420 MultiLevelTemplateArgumentList(TemplateArgs));
Anders Carlsson3b56c002009-06-11 16:06:49 +00001421 if (E.isInvalid())
1422 return true;
1423
1424 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001425 } else {
1426 TemplateTemplateParmDecl *TempParm
1427 = cast<TemplateTemplateParmDecl>(*Param);
1428
1429 if (!TempParm->hasDefaultArgument())
1430 break;
1431
John McCallce3ff2b2009-08-25 22:02:44 +00001432 // FIXME: Subst default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001433 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001434 }
1435 } else {
1436 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001437 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001438 }
1439
Douglas Gregorc15cb382009-02-09 23:23:08 +00001440
1441 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001442 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001443 Converted.BeginPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001444 // Check all the remaining arguments (if any).
1445 for (; ArgIdx < NumArgs; ++ArgIdx) {
1446 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1447 Invalid = true;
1448 }
1449
Anders Carlssonfb250522009-06-23 01:26:57 +00001450 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001451 } else {
1452 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1453 Invalid = true;
1454 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001455 } else if (NonTypeTemplateParmDecl *NTTP
1456 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1457 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001458
John McCallce3ff2b2009-08-25 22:02:44 +00001459 // Do substitution on the type of the non-type template parameter
1460 // with the template arguments we've seen thus far.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001461 QualType NTTPType = NTTP->getType();
1462 if (NTTPType->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +00001463 // Do substitution on the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001464 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001465 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001466 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001467 SourceRange(TemplateLoc, RAngleLoc));
1468
Anders Carlssone9c904b2009-06-05 04:47:51 +00001469 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001470 /*TakeArgs=*/false);
Douglas Gregor357bbd02009-08-28 20:50:45 +00001471 NTTPType = SubstType(NTTPType,
1472 MultiLevelTemplateArgumentList(TemplateArgs),
John McCallce3ff2b2009-08-25 22:02:44 +00001473 NTTP->getLocation(),
1474 NTTP->getDeclName());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001475 // If that worked, check the non-type template parameter type
1476 // for validity.
1477 if (!NTTPType.isNull())
1478 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1479 NTTP->getLocation());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001480 if (NTTPType.isNull()) {
1481 Invalid = true;
1482 break;
1483 }
1484 }
1485
Douglas Gregor40808ce2009-03-09 23:48:35 +00001486 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001487 case TemplateArgument::Null:
1488 assert(false && "Should never see a NULL template argument here");
1489 break;
1490
Douglas Gregor40808ce2009-03-09 23:48:35 +00001491 case TemplateArgument::Expression: {
1492 Expr *E = Arg.getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001493 TemplateArgument Result;
1494 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001495 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001496 else
Anders Carlssonfb250522009-06-23 01:26:57 +00001497 Converted.Append(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001498 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001499 }
1500
Douglas Gregor40808ce2009-03-09 23:48:35 +00001501 case TemplateArgument::Declaration:
1502 case TemplateArgument::Integral:
1503 // We've already checked this template argument, so just copy
1504 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001505 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001506 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001507
Douglas Gregor40808ce2009-03-09 23:48:35 +00001508 case TemplateArgument::Type:
1509 // We have a non-type template parameter but the template
1510 // argument is a type.
1511
1512 // C++ [temp.arg]p2:
1513 // In a template-argument, an ambiguity between a type-id and
1514 // an expression is resolved to a type-id, regardless of the
1515 // form of the corresponding template-parameter.
1516 //
1517 // We warn specifically about this case, since it can be rather
1518 // confusing for users.
1519 if (Arg.getAsType()->isFunctionType())
1520 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1521 << Arg.getAsType();
1522 else
1523 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1524 Diag((*Param)->getLocation(), diag::note_template_param_here);
1525 Invalid = true;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001526 break;
1527
1528 case TemplateArgument::Pack:
1529 assert(0 && "FIXME: Implement!");
1530 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001531 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001532 } else {
1533 // Check template template parameters.
1534 TemplateTemplateParmDecl *TempParm
1535 = cast<TemplateTemplateParmDecl>(*Param);
1536
Douglas Gregor40808ce2009-03-09 23:48:35 +00001537 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001538 case TemplateArgument::Null:
1539 assert(false && "Should never see a NULL template argument here");
1540 break;
1541
Douglas Gregor40808ce2009-03-09 23:48:35 +00001542 case TemplateArgument::Expression: {
1543 Expr *ArgExpr = Arg.getAsExpr();
1544 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1545 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1546 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1547 Invalid = true;
1548
1549 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001550 Decl *D
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001551 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonfb250522009-06-23 01:26:57 +00001552 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001553 continue;
1554 }
1555 }
1556 // fall through
1557
1558 case TemplateArgument::Type: {
1559 // We have a template template parameter but the template
1560 // argument does not refer to a template.
1561 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1562 Invalid = true;
1563 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001564 }
1565
Douglas Gregor40808ce2009-03-09 23:48:35 +00001566 case TemplateArgument::Declaration:
1567 // We've already checked this template argument, so just copy
1568 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001569 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001570 break;
1571
1572 case TemplateArgument::Integral:
1573 assert(false && "Integral argument with template template parameter");
1574 break;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001575
1576 case TemplateArgument::Pack:
1577 assert(0 && "FIXME: Implement!");
1578 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001579 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001580 }
1581 }
1582
1583 return Invalid;
1584}
1585
1586/// \brief Check a template argument against its corresponding
1587/// template type parameter.
1588///
1589/// This routine implements the semantics of C++ [temp.arg.type]. It
1590/// returns true if an error occurred, and false otherwise.
1591bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1592 QualType Arg, SourceLocation ArgLoc) {
1593 // C++ [temp.arg.type]p2:
1594 // A local type, a type with no linkage, an unnamed type or a type
1595 // compounded from any of these types shall not be used as a
1596 // template-argument for a template type-parameter.
1597 //
1598 // FIXME: Perform the recursive and no-linkage type checks.
1599 const TagType *Tag = 0;
1600 if (const EnumType *EnumT = Arg->getAsEnumType())
1601 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00001602 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001603 Tag = RecordT;
1604 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1605 return Diag(ArgLoc, diag::err_template_arg_local_type)
1606 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001607 else if (Tag && !Tag->getDecl()->getDeclName() &&
1608 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001609 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1610 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1611 return true;
1612 }
1613
1614 return false;
1615}
1616
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001617/// \brief Checks whether the given template argument is the address
1618/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001619bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1620 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001621 bool Invalid = false;
1622
1623 // See through any implicit casts we added to fix the type.
1624 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1625 Arg = Cast->getSubExpr();
1626
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001627 // C++0x allows nullptr, and there's no further checking to be done for that.
1628 if (Arg->getType()->isNullPtrType())
1629 return false;
1630
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001631 // C++ [temp.arg.nontype]p1:
1632 //
1633 // A template-argument for a non-type, non-template
1634 // template-parameter shall be one of: [...]
1635 //
1636 // -- the address of an object or function with external
1637 // linkage, including function templates and function
1638 // template-ids but excluding non-static class members,
1639 // expressed as & id-expression where the & is optional if
1640 // the name refers to a function or array, or if the
1641 // corresponding template-parameter is a reference; or
1642 DeclRefExpr *DRE = 0;
1643
1644 // Ignore (and complain about) any excess parentheses.
1645 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1646 if (!Invalid) {
1647 Diag(Arg->getSourceRange().getBegin(),
1648 diag::err_template_arg_extra_parens)
1649 << Arg->getSourceRange();
1650 Invalid = true;
1651 }
1652
1653 Arg = Parens->getSubExpr();
1654 }
1655
1656 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1657 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1658 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1659 } else
1660 DRE = dyn_cast<DeclRefExpr>(Arg);
1661
1662 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1663 return Diag(Arg->getSourceRange().getBegin(),
1664 diag::err_template_arg_not_object_or_func_form)
1665 << Arg->getSourceRange();
1666
1667 // Cannot refer to non-static data members
1668 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1669 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1670 << Field << Arg->getSourceRange();
1671
1672 // Cannot refer to non-static member functions
1673 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1674 if (!Method->isStatic())
1675 return Diag(Arg->getSourceRange().getBegin(),
1676 diag::err_template_arg_method)
1677 << Method << Arg->getSourceRange();
1678
1679 // Functions must have external linkage.
1680 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1681 if (Func->getStorageClass() == FunctionDecl::Static) {
1682 Diag(Arg->getSourceRange().getBegin(),
1683 diag::err_template_arg_function_not_extern)
1684 << Func << Arg->getSourceRange();
1685 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1686 << true;
1687 return true;
1688 }
1689
1690 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001691 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001692 return Invalid;
1693 }
1694
1695 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1696 if (!Var->hasGlobalStorage()) {
1697 Diag(Arg->getSourceRange().getBegin(),
1698 diag::err_template_arg_object_not_extern)
1699 << Var << Arg->getSourceRange();
1700 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1701 << true;
1702 return true;
1703 }
1704
1705 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001706 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001707 return Invalid;
1708 }
1709
1710 // We found something else, but we don't know specifically what it is.
1711 Diag(Arg->getSourceRange().getBegin(),
1712 diag::err_template_arg_not_object_or_func)
1713 << Arg->getSourceRange();
1714 Diag(DRE->getDecl()->getLocation(),
1715 diag::note_template_arg_refers_here);
1716 return true;
1717}
1718
1719/// \brief Checks whether the given template argument is a pointer to
1720/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001721bool
1722Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001723 bool Invalid = false;
1724
1725 // See through any implicit casts we added to fix the type.
1726 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1727 Arg = Cast->getSubExpr();
1728
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001729 // C++0x allows nullptr, and there's no further checking to be done for that.
1730 if (Arg->getType()->isNullPtrType())
1731 return false;
1732
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001733 // C++ [temp.arg.nontype]p1:
1734 //
1735 // A template-argument for a non-type, non-template
1736 // template-parameter shall be one of: [...]
1737 //
1738 // -- a pointer to member expressed as described in 5.3.1.
1739 QualifiedDeclRefExpr *DRE = 0;
1740
1741 // Ignore (and complain about) any excess parentheses.
1742 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1743 if (!Invalid) {
1744 Diag(Arg->getSourceRange().getBegin(),
1745 diag::err_template_arg_extra_parens)
1746 << Arg->getSourceRange();
1747 Invalid = true;
1748 }
1749
1750 Arg = Parens->getSubExpr();
1751 }
1752
1753 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1754 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1755 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1756
1757 if (!DRE)
1758 return Diag(Arg->getSourceRange().getBegin(),
1759 diag::err_template_arg_not_pointer_to_member_form)
1760 << Arg->getSourceRange();
1761
1762 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1763 assert((isa<FieldDecl>(DRE->getDecl()) ||
1764 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1765 "Only non-static member pointers can make it here");
1766
1767 // Okay: this is the address of a non-static member, and therefore
1768 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001769 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001770 return Invalid;
1771 }
1772
1773 // We found something else, but we don't know specifically what it is.
1774 Diag(Arg->getSourceRange().getBegin(),
1775 diag::err_template_arg_not_pointer_to_member_form)
1776 << Arg->getSourceRange();
1777 Diag(DRE->getDecl()->getLocation(),
1778 diag::note_template_arg_refers_here);
1779 return true;
1780}
1781
Douglas Gregorc15cb382009-02-09 23:23:08 +00001782/// \brief Check a template argument against its corresponding
1783/// non-type template parameter.
1784///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001785/// This routine implements the semantics of C++ [temp.arg.nontype].
1786/// It returns true if an error occurred, and false otherwise. \p
1787/// InstantiatedParamType is the type of the non-type template
1788/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001789///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001790/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001791bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001792 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001793 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001794 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1795
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001796 // If either the parameter has a dependent type or the argument is
1797 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001798 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001799 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1800 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001801 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001802 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001803 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001804
1805 // C++ [temp.arg.nontype]p5:
1806 // The following conversions are performed on each expression used
1807 // as a non-type template-argument. If a non-type
1808 // template-argument cannot be converted to the type of the
1809 // corresponding template-parameter then the program is
1810 // ill-formed.
1811 //
1812 // -- for a non-type template-parameter of integral or
1813 // enumeration type, integral promotions (4.5) and integral
1814 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001815 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001816 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001817 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001818 // C++ [temp.arg.nontype]p1:
1819 // A template-argument for a non-type, non-template
1820 // template-parameter shall be one of:
1821 //
1822 // -- an integral constant-expression of integral or enumeration
1823 // type; or
1824 // -- the name of a non-type template-parameter; or
1825 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001826 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001827 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1828 Diag(Arg->getSourceRange().getBegin(),
1829 diag::err_template_arg_not_integral_or_enumeral)
1830 << ArgType << Arg->getSourceRange();
1831 Diag(Param->getLocation(), diag::note_template_param_here);
1832 return true;
1833 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001834 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001835 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1836 << ArgType << Arg->getSourceRange();
1837 return true;
1838 }
1839
1840 // FIXME: We need some way to more easily get the unqualified form
1841 // of the types without going all the way to the
1842 // canonical type.
1843 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1844 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1845 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1846 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1847
1848 // Try to convert the argument to the parameter's type.
1849 if (ParamType == ArgType) {
1850 // Okay: no conversion necessary
1851 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1852 !ParamType->isEnumeralType()) {
1853 // This is an integral promotion or conversion.
1854 ImpCastExprToType(Arg, ParamType);
1855 } else {
1856 // We can't perform this conversion.
1857 Diag(Arg->getSourceRange().getBegin(),
1858 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001859 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001860 Diag(Param->getLocation(), diag::note_template_param_here);
1861 return true;
1862 }
1863
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001864 QualType IntegerType = Context.getCanonicalType(ParamType);
1865 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001866 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001867
1868 if (!Arg->isValueDependent()) {
1869 // Check that an unsigned parameter does not receive a negative
1870 // value.
1871 if (IntegerType->isUnsignedIntegerType()
1872 && (Value.isSigned() && Value.isNegative())) {
1873 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1874 << Value.toString(10) << Param->getType()
1875 << Arg->getSourceRange();
1876 Diag(Param->getLocation(), diag::note_template_param_here);
1877 return true;
1878 }
1879
1880 // Check that we don't overflow the template parameter type.
1881 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1882 if (Value.getActiveBits() > AllowedBits) {
1883 Diag(Arg->getSourceRange().getBegin(),
1884 diag::err_template_arg_too_large)
1885 << Value.toString(10) << Param->getType()
1886 << Arg->getSourceRange();
1887 Diag(Param->getLocation(), diag::note_template_param_here);
1888 return true;
1889 }
1890
1891 if (Value.getBitWidth() != AllowedBits)
1892 Value.extOrTrunc(AllowedBits);
1893 Value.setIsSigned(IntegerType->isSignedIntegerType());
1894 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001895
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001896 // Add the value of this argument to the list of converted
1897 // arguments. We use the bitwidth and signedness of the template
1898 // parameter.
1899 if (Arg->isValueDependent()) {
1900 // The argument is value-dependent. Create a new
1901 // TemplateArgument with the converted expression.
1902 Converted = TemplateArgument(Arg);
1903 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001904 }
1905
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001906 Converted = TemplateArgument(StartLoc, Value,
1907 ParamType->isEnumeralType() ? ParamType
1908 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001909 return false;
1910 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001911
Douglas Gregorb86b0572009-02-11 01:18:59 +00001912 // Handle pointer-to-function, reference-to-function, and
1913 // pointer-to-member-function all in (roughly) the same way.
1914 if (// -- For a non-type template-parameter of type pointer to
1915 // function, only the function-to-pointer conversion (4.3) is
1916 // applied. If the template-argument represents a set of
1917 // overloaded functions (or a pointer to such), the matching
1918 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001919 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001920 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001921 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001922 // -- For a non-type template-parameter of type reference to
1923 // function, no conversions apply. If the template-argument
1924 // represents a set of overloaded functions, the matching
1925 // function is selected from the set (13.4).
1926 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001927 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001928 // -- For a non-type template-parameter of type pointer to
1929 // member function, no conversions apply. If the
1930 // template-argument represents a set of overloaded member
1931 // functions, the matching member function is selected from
1932 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001933 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001934 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001935 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001936 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001937 if (Context.hasSameUnqualifiedType(ArgType,
1938 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001939 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001940 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1941 ParamType->isMemberPointerType())) {
1942 ArgType = ParamType;
1943 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001944 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001945 ArgType = Context.getPointerType(ArgType);
1946 ImpCastExprToType(Arg, ArgType);
1947 } else if (FunctionDecl *Fn
1948 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001949 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1950 return true;
1951
Douglas Gregora35284b2009-02-11 00:19:33 +00001952 FixOverloadedFunctionReference(Arg, Fn);
1953 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001954 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001955 ArgType = Context.getPointerType(Arg->getType());
1956 ImpCastExprToType(Arg, ArgType);
1957 }
1958 }
1959
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001960 if (!Context.hasSameUnqualifiedType(ArgType,
1961 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001962 // We can't perform this conversion.
1963 Diag(Arg->getSourceRange().getBegin(),
1964 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001965 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001966 Diag(Param->getLocation(), diag::note_template_param_here);
1967 return true;
1968 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001969
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001970 if (ParamType->isMemberPointerType()) {
1971 NamedDecl *Member = 0;
1972 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1973 return true;
1974
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001975 if (Member)
1976 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001977 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001978 return false;
1979 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001980
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001981 NamedDecl *Entity = 0;
1982 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1983 return true;
1984
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001985 if (Entity)
1986 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001987 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001988 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001989 }
1990
Chris Lattnerfe90de72009-02-20 21:37:53 +00001991 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001992 // -- for a non-type template-parameter of type pointer to
1993 // object, qualification conversions (4.4) and the
1994 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001995 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00001996 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001997 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001998
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001999 if (ArgType->isNullPtrType()) {
2000 ArgType = ParamType;
2001 ImpCastExprToType(Arg, ParamType);
2002 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002003 ArgType = Context.getArrayDecayedType(ArgType);
2004 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002005 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002006
Douglas Gregorb86b0572009-02-11 01:18:59 +00002007 if (IsQualificationConversion(ArgType, ParamType)) {
2008 ArgType = ParamType;
2009 ImpCastExprToType(Arg, ParamType);
2010 }
2011
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002012 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002013 // We can't perform this conversion.
2014 Diag(Arg->getSourceRange().getBegin(),
2015 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002016 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002017 Diag(Param->getLocation(), diag::note_template_param_here);
2018 return true;
2019 }
2020
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002021 NamedDecl *Entity = 0;
2022 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2023 return true;
2024
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002025 if (Entity)
2026 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002027 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002028 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002029 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00002030
Ted Kremenek6217b802009-07-29 21:53:49 +00002031 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002032 // -- For a non-type template-parameter of type reference to
2033 // object, no conversions apply. The type referred to by the
2034 // reference may be more cv-qualified than the (otherwise
2035 // identical) type of the template-argument. The
2036 // template-parameter is bound directly to the
2037 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002038 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002039 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002040
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002041 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002042 Diag(Arg->getSourceRange().getBegin(),
2043 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002044 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002045 << Arg->getSourceRange();
2046 Diag(Param->getLocation(), diag::note_template_param_here);
2047 return true;
2048 }
2049
2050 unsigned ParamQuals
2051 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2052 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
2053
2054 if ((ParamQuals | ArgQuals) != ParamQuals) {
2055 Diag(Arg->getSourceRange().getBegin(),
2056 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002057 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002058 << Arg->getSourceRange();
2059 Diag(Param->getLocation(), diag::note_template_param_here);
2060 return true;
2061 }
2062
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002063 NamedDecl *Entity = 0;
2064 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2065 return true;
2066
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002067 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002068 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002069 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002070 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002071
2072 // -- For a non-type template-parameter of type pointer to data
2073 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002074 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00002075 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2076
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002077 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002078 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002079 } else if (ArgType->isNullPtrType()) {
2080 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002081 } else if (IsQualificationConversion(ArgType, ParamType)) {
2082 ImpCastExprToType(Arg, ParamType);
2083 } else {
2084 // We can't perform this conversion.
2085 Diag(Arg->getSourceRange().getBegin(),
2086 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002087 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002088 Diag(Param->getLocation(), diag::note_template_param_here);
2089 return true;
2090 }
2091
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002092 NamedDecl *Member = 0;
2093 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2094 return true;
2095
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002096 if (Member)
2097 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002098 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002099 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002100}
2101
2102/// \brief Check a template argument against its corresponding
2103/// template template parameter.
2104///
2105/// This routine implements the semantics of C++ [temp.arg.template].
2106/// It returns true if an error occurred, and false otherwise.
2107bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2108 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002109 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2110 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2111
2112 // C++ [temp.arg.template]p1:
2113 // A template-argument for a template template-parameter shall be
2114 // the name of a class template, expressed as id-expression. Only
2115 // primary class templates are considered when matching the
2116 // template template argument with the corresponding parameter;
2117 // partial specializations are not considered even if their
2118 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002119 //
2120 // Note that we also allow template template parameters here, which
2121 // will happen when we are dealing with, e.g., class template
2122 // partial specializations.
2123 if (!isa<ClassTemplateDecl>(Template) &&
2124 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002125 assert(isa<FunctionTemplateDecl>(Template) &&
2126 "Only function templates are possible here");
Douglas Gregore53060f2009-06-25 22:08:12 +00002127 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2128 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002129 << Template;
2130 }
2131
2132 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2133 Param->getTemplateParameters(),
2134 true, true,
2135 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002136}
2137
Douglas Gregorddc29e12009-02-06 22:42:48 +00002138/// \brief Determine whether the given template parameter lists are
2139/// equivalent.
2140///
2141/// \param New The new template parameter list, typically written in the
2142/// source code as part of a new template declaration.
2143///
2144/// \param Old The old template parameter list, typically found via
2145/// name lookup of the template declared with this template parameter
2146/// list.
2147///
2148/// \param Complain If true, this routine will produce a diagnostic if
2149/// the template parameter lists are not equivalent.
2150///
Douglas Gregordd0574e2009-02-10 00:24:35 +00002151/// \param IsTemplateTemplateParm If true, this routine is being
2152/// called to compare the template parameter lists of a template
2153/// template parameter.
2154///
2155/// \param TemplateArgLoc If this source location is valid, then we
2156/// are actually checking the template parameter list of a template
2157/// argument (New) against the template parameter list of its
2158/// corresponding template template parameter (Old). We produce
2159/// slightly different diagnostics in this scenario.
2160///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002161/// \returns True if the template parameter lists are equal, false
2162/// otherwise.
2163bool
2164Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2165 TemplateParameterList *Old,
2166 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002167 bool IsTemplateTemplateParm,
2168 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002169 if (Old->size() != New->size()) {
2170 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002171 unsigned NextDiag = diag::err_template_param_list_different_arity;
2172 if (TemplateArgLoc.isValid()) {
2173 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2174 NextDiag = diag::note_template_param_list_different_arity;
2175 }
2176 Diag(New->getTemplateLoc(), NextDiag)
2177 << (New->size() > Old->size())
2178 << IsTemplateTemplateParm
2179 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002180 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2181 << IsTemplateTemplateParm
2182 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2183 }
2184
2185 return false;
2186 }
2187
2188 for (TemplateParameterList::iterator OldParm = Old->begin(),
2189 OldParmEnd = Old->end(), NewParm = New->begin();
2190 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2191 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002192 if (Complain) {
2193 unsigned NextDiag = diag::err_template_param_different_kind;
2194 if (TemplateArgLoc.isValid()) {
2195 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2196 NextDiag = diag::note_template_param_different_kind;
2197 }
2198 Diag((*NewParm)->getLocation(), NextDiag)
2199 << IsTemplateTemplateParm;
2200 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2201 << IsTemplateTemplateParm;
Douglas Gregordd0574e2009-02-10 00:24:35 +00002202 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002203 return false;
2204 }
2205
2206 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2207 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002208 // know we're at the same index).
2209#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00002210 // FIXME: Enable this code in debug mode *after* we properly go through
2211 // and "instantiate" the template parameter lists of template template
2212 // parameters. It's only after this instantiation that (1) any dependent
2213 // types within the template parameter list of the template template
2214 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00002215 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00002216 QualType OldParmType
2217 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2218 QualType NewParmType
2219 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2220 assert(Context.getCanonicalType(OldParmType) ==
2221 Context.getCanonicalType(NewParmType) &&
2222 "type parameter mismatch?");
2223#endif
2224 } else if (NonTypeTemplateParmDecl *OldNTTP
2225 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2226 // The types of non-type template parameters must agree.
2227 NonTypeTemplateParmDecl *NewNTTP
2228 = cast<NonTypeTemplateParmDecl>(*NewParm);
2229 if (Context.getCanonicalType(OldNTTP->getType()) !=
2230 Context.getCanonicalType(NewNTTP->getType())) {
2231 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002232 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2233 if (TemplateArgLoc.isValid()) {
2234 Diag(TemplateArgLoc,
2235 diag::err_template_arg_template_params_mismatch);
2236 NextDiag = diag::note_template_nontype_parm_different_type;
2237 }
2238 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002239 << NewNTTP->getType()
2240 << IsTemplateTemplateParm;
2241 Diag(OldNTTP->getLocation(),
2242 diag::note_template_nontype_parm_prev_declaration)
2243 << OldNTTP->getType();
2244 }
2245 return false;
2246 }
2247 } else {
2248 // The template parameter lists of template template
2249 // parameters must agree.
2250 // FIXME: Could we perform a faster "type" comparison here?
2251 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2252 "Only template template parameters handled here");
2253 TemplateTemplateParmDecl *OldTTP
2254 = cast<TemplateTemplateParmDecl>(*OldParm);
2255 TemplateTemplateParmDecl *NewTTP
2256 = cast<TemplateTemplateParmDecl>(*NewParm);
2257 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2258 OldTTP->getTemplateParameters(),
2259 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002260 /*IsTemplateTemplateParm=*/true,
2261 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002262 return false;
2263 }
2264 }
2265
2266 return true;
2267}
2268
2269/// \brief Check whether a template can be declared within this scope.
2270///
2271/// If the template declaration is valid in this scope, returns
2272/// false. Otherwise, issues a diagnostic and returns true.
2273bool
Douglas Gregor05396e22009-08-25 17:23:04 +00002274Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002275 // Find the nearest enclosing declaration scope.
2276 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2277 (S->getFlags() & Scope::TemplateParamScope) != 0)
2278 S = S->getParent();
2279
Douglas Gregorddc29e12009-02-06 22:42:48 +00002280 // C++ [temp]p2:
2281 // A template-declaration can appear only as a namespace scope or
2282 // class scope declaration.
2283 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002284 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2285 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Douglas Gregor05396e22009-08-25 17:23:04 +00002286 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
2287 << TemplateParams->getSourceRange();
Eli Friedman1503f772009-07-31 01:43:05 +00002288
2289 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002290 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002291
2292 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2293 return false;
2294
Douglas Gregor05396e22009-08-25 17:23:04 +00002295 return Diag(TemplateParams->getTemplateLoc(),
2296 diag::err_template_outside_namespace_or_class_scope)
2297 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002298}
Douglas Gregorcc636682009-02-17 23:15:12 +00002299
Douglas Gregorff668032009-05-13 18:28:20 +00002300/// \brief Check whether a class template specialization or explicit
2301/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00002302///
Douglas Gregorff668032009-05-13 18:28:20 +00002303/// This routine determines whether a class template specialization or
2304/// explicit instantiation can be declared in the current context
2305/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2306/// appropriate diagnostics if there was an error. It returns true if
2307// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00002308bool
2309Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2310 ClassTemplateSpecializationDecl *PrevDecl,
2311 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002312 SourceRange ScopeSpecifierRange,
Douglas Gregor16df8502009-06-12 22:21:45 +00002313 bool PartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002314 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002315 // C++ [temp.expl.spec]p2:
2316 // An explicit specialization shall be declared in the namespace
2317 // of which the template is a member, or, for member templates, in
2318 // the namespace of which the enclosing class or enclosing class
2319 // template is a member. An explicit specialization of a member
2320 // function, member class or static data member of a class
2321 // template shall be declared in the namespace of which the class
2322 // template is a member. Such a declaration may also be a
2323 // definition. If the declaration is not a definition, the
2324 // specialization may be defined later in the name- space in which
2325 // the explicit specialization was declared, or in a namespace
2326 // that encloses the one in which the explicit specialization was
2327 // declared.
2328 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor16df8502009-06-12 22:21:45 +00002329 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor88b70942009-02-25 22:02:03 +00002330 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002331 << Kind << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00002332 return true;
2333 }
2334
2335 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2336 DeclContext *TemplateContext
2337 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00002338 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2339 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002340 // There is no prior declaration of this entity, so this
2341 // specialization must be in the same context as the template
2342 // itself.
2343 if (DC != TemplateContext) {
2344 if (isa<TranslationUnitDecl>(TemplateContext))
2345 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor16df8502009-06-12 22:21:45 +00002346 << PartialSpecialization
Douglas Gregor88b70942009-02-25 22:02:03 +00002347 << ClassTemplate << ScopeSpecifierRange;
2348 else if (isa<NamespaceDecl>(TemplateContext))
2349 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002350 << PartialSpecialization << ClassTemplate
2351 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor88b70942009-02-25 22:02:03 +00002352
2353 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2354 }
2355
2356 return false;
2357 }
2358
2359 // We have a previous declaration of this entity. Make sure that
2360 // this redeclaration (or definition) occurs in an enclosing namespace.
2361 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002362 // FIXME: In C++98, we would like to turn these errors into warnings,
2363 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00002364 bool SuppressedDiag = false;
Douglas Gregor16df8502009-06-12 22:21:45 +00002365 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorff668032009-05-13 18:28:20 +00002366 if (isa<TranslationUnitDecl>(TemplateContext)) {
2367 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2368 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002369 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorff668032009-05-13 18:28:20 +00002370 else
2371 SuppressedDiag = true;
2372 } else if (isa<NamespaceDecl>(TemplateContext)) {
2373 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2374 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002375 << Kind << ClassTemplate
Douglas Gregorff668032009-05-13 18:28:20 +00002376 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2377 else
2378 SuppressedDiag = true;
2379 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002380
Douglas Gregorff668032009-05-13 18:28:20 +00002381 if (!SuppressedDiag)
2382 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00002383 }
2384
2385 return false;
2386}
2387
Douglas Gregore94866f2009-06-12 21:21:02 +00002388/// \brief Check the non-type template arguments of a class template
2389/// partial specialization according to C++ [temp.class.spec]p9.
2390///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002391/// \param TemplateParams the template parameters of the primary class
2392/// template.
2393///
2394/// \param TemplateArg the template arguments of the class template
2395/// partial specialization.
2396///
2397/// \param MirrorsPrimaryTemplate will be set true if the class
2398/// template partial specialization arguments are identical to the
2399/// implicit template arguments of the primary template. This is not
2400/// necessarily an error (C++0x), and it is left to the caller to diagnose
2401/// this condition when it is an error.
2402///
Douglas Gregore94866f2009-06-12 21:21:02 +00002403/// \returns true if there was an error, false otherwise.
2404bool Sema::CheckClassTemplatePartialSpecializationArgs(
2405 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002406 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002407 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002408 // FIXME: the interface to this function will have to change to
2409 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002410 MirrorsPrimaryTemplate = true;
Anders Carlsson6360be72009-06-13 18:20:51 +00002411
Anders Carlssonfb250522009-06-23 01:26:57 +00002412 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson6360be72009-06-13 18:20:51 +00002413
Douglas Gregore94866f2009-06-12 21:21:02 +00002414 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002415 // Determine whether the template argument list of the partial
2416 // specialization is identical to the implicit argument list of
2417 // the primary template. The caller may need to diagnostic this as
2418 // an error per C++ [temp.class.spec]p9b3.
2419 if (MirrorsPrimaryTemplate) {
2420 if (TemplateTypeParmDecl *TTP
2421 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2422 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002423 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002424 MirrorsPrimaryTemplate = false;
2425 } else if (TemplateTemplateParmDecl *TTP
2426 = dyn_cast<TemplateTemplateParmDecl>(
2427 TemplateParams->getParam(I))) {
2428 // FIXME: We should settle on either Declaration storage or
2429 // Expression storage for template template parameters.
2430 TemplateTemplateParmDecl *ArgDecl
2431 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson6360be72009-06-13 18:20:51 +00002432 ArgList[I].getAsDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002433 if (!ArgDecl)
2434 if (DeclRefExpr *DRE
Anders Carlsson6360be72009-06-13 18:20:51 +00002435 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002436 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2437
2438 if (!ArgDecl ||
2439 ArgDecl->getIndex() != TTP->getIndex() ||
2440 ArgDecl->getDepth() != TTP->getDepth())
2441 MirrorsPrimaryTemplate = false;
2442 }
2443 }
2444
Douglas Gregore94866f2009-06-12 21:21:02 +00002445 NonTypeTemplateParmDecl *Param
2446 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002447 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002448 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002449 }
2450
Anders Carlsson6360be72009-06-13 18:20:51 +00002451 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002452 if (!ArgExpr) {
2453 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002454 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002455 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002456
2457 // C++ [temp.class.spec]p8:
2458 // A non-type argument is non-specialized if it is the name of a
2459 // non-type parameter. All other non-type arguments are
2460 // specialized.
2461 //
2462 // Below, we check the two conditions that only apply to
2463 // specialized non-type arguments, so skip any non-specialized
2464 // arguments.
2465 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002466 if (NonTypeTemplateParmDecl *NTTP
2467 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2468 if (MirrorsPrimaryTemplate &&
2469 (Param->getIndex() != NTTP->getIndex() ||
2470 Param->getDepth() != NTTP->getDepth()))
2471 MirrorsPrimaryTemplate = false;
2472
Douglas Gregore94866f2009-06-12 21:21:02 +00002473 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002474 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002475
2476 // C++ [temp.class.spec]p9:
2477 // Within the argument list of a class template partial
2478 // specialization, the following restrictions apply:
2479 // -- A partially specialized non-type argument expression
2480 // shall not involve a template parameter of the partial
2481 // specialization except when the argument expression is a
2482 // simple identifier.
2483 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2484 Diag(ArgExpr->getLocStart(),
2485 diag::err_dependent_non_type_arg_in_partial_spec)
2486 << ArgExpr->getSourceRange();
2487 return true;
2488 }
2489
2490 // -- The type of a template parameter corresponding to a
2491 // specialized non-type argument shall not be dependent on a
2492 // parameter of the specialization.
2493 if (Param->getType()->isDependentType()) {
2494 Diag(ArgExpr->getLocStart(),
2495 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2496 << Param->getType()
2497 << ArgExpr->getSourceRange();
2498 Diag(Param->getLocation(), diag::note_template_param_here);
2499 return true;
2500 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002501
2502 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002503 }
2504
2505 return false;
2506}
2507
Douglas Gregor212e81c2009-03-25 00:13:59 +00002508Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00002509Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2510 TagUseKind TUK,
Douglas Gregorcc636682009-02-17 23:15:12 +00002511 SourceLocation KWLoc,
2512 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002513 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002514 SourceLocation TemplateNameLoc,
2515 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002516 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002517 SourceLocation *TemplateArgLocs,
2518 SourceLocation RAngleLoc,
2519 AttributeList *Attr,
2520 MultiTemplateParamsArg TemplateParameterLists) {
John McCallf1bbbb42009-09-04 01:14:41 +00002521 assert(TUK == TUK_Declaration || TUK == TUK_Definition);
2522
Douglas Gregorcc636682009-02-17 23:15:12 +00002523 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002524 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002525 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002526 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002527
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002528 bool isPartialSpecialization = false;
2529
Douglas Gregor88b70942009-02-25 22:02:03 +00002530 // Check the validity of the template headers that introduce this
2531 // template.
Douglas Gregor05396e22009-08-25 17:23:04 +00002532 TemplateParameterList *TemplateParams
2533 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2534 (TemplateParameterList**)TemplateParameterLists.get(),
2535 TemplateParameterLists.size());
2536 if (TemplateParams && TemplateParams->size() > 0) {
2537 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002538
Douglas Gregor05396e22009-08-25 17:23:04 +00002539 // C++ [temp.class.spec]p10:
2540 // The template parameter list of a specialization shall not
2541 // contain default template argument values.
2542 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2543 Decl *Param = TemplateParams->getParam(I);
2544 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2545 if (TTP->hasDefaultArgument()) {
2546 Diag(TTP->getDefaultArgumentLoc(),
2547 diag::err_default_arg_in_partial_spec);
2548 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2549 }
2550 } else if (NonTypeTemplateParmDecl *NTTP
2551 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2552 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2553 Diag(NTTP->getDefaultArgumentLoc(),
2554 diag::err_default_arg_in_partial_spec)
2555 << DefArg->getSourceRange();
2556 NTTP->setDefaultArgument(0);
2557 DefArg->Destroy(Context);
2558 }
2559 } else {
2560 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2561 if (Expr *DefArg = TTP->getDefaultArgument()) {
2562 Diag(TTP->getDefaultArgumentLoc(),
2563 diag::err_default_arg_in_partial_spec)
2564 << DefArg->getSourceRange();
2565 TTP->setDefaultArgument(0);
2566 DefArg->Destroy(Context);
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002567 }
2568 }
2569 }
Douglas Gregor05396e22009-08-25 17:23:04 +00002570 } else if (!TemplateParams)
2571 Diag(KWLoc, diag::err_template_spec_needs_header)
2572 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor88b70942009-02-25 22:02:03 +00002573
Douglas Gregorcc636682009-02-17 23:15:12 +00002574 // Check that the specialization uses the same tag kind as the
2575 // original template.
2576 TagDecl::TagKind Kind;
2577 switch (TagSpec) {
2578 default: assert(0 && "Unknown tag type!");
2579 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2580 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2581 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2582 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002583 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2584 Kind, KWLoc,
2585 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002586 Diag(KWLoc, diag::err_use_with_wrong_tag)
2587 << ClassTemplate
2588 << CodeModificationHint::CreateReplacement(KWLoc,
2589 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002590 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2591 diag::note_previous_use);
2592 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2593 }
2594
Douglas Gregor40808ce2009-03-09 23:48:35 +00002595 // Translate the parser's template argument list in our AST format.
2596 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2597 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2598
Douglas Gregorcc636682009-02-17 23:15:12 +00002599 // Check that the template argument list is well-formed for this
2600 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002601 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2602 TemplateArgs.size());
Douglas Gregorcc636682009-02-17 23:15:12 +00002603 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00002604 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002605 RAngleLoc, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002606 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002607
Anders Carlssonfb250522009-06-23 01:26:57 +00002608 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00002609 ClassTemplate->getTemplateParameters()->size()) &&
2610 "Converted template argument list is too short!");
2611
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002612 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002613 // corresponds to these arguments.
2614 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002615 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002616 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00002617 if (CheckClassTemplatePartialSpecializationArgs(
2618 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00002619 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00002620 return true;
2621
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002622 if (MirrorsPrimaryTemplate) {
2623 // C++ [temp.class.spec]p9b3:
2624 //
2625 // -- The argument list of the specialization shall not be identical
2626 // to the implicit argument list of the primary template.
2627 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00002628 << (TUK == TUK_Definition)
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002629 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2630 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00002631 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002632 ClassTemplate->getIdentifier(),
2633 TemplateNameLoc,
2634 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00002635 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002636 AS_none);
2637 }
2638
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002639 // FIXME: Template parameter list matters, too
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002640 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002641 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002642 Converted.flatSize(),
2643 Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002644 } else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002645 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002646 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002647 Converted.flatSize(),
2648 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00002649 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002650 ClassTemplateSpecializationDecl *PrevDecl = 0;
2651
2652 if (isPartialSpecialization)
2653 PrevDecl
2654 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2655 InsertPos);
2656 else
2657 PrevDecl
2658 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002659
2660 ClassTemplateSpecializationDecl *Specialization = 0;
2661
Douglas Gregor88b70942009-02-25 22:02:03 +00002662 // Check whether we can declare a class template specialization in
2663 // the current scope.
2664 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2665 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002666 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002667 isPartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002668 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002669 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002670
Douglas Gregorb88e8882009-07-30 17:40:51 +00002671 // The canonical type
2672 QualType CanonType;
Douglas Gregorcc636682009-02-17 23:15:12 +00002673 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2674 // Since the only prior class template specialization with these
2675 // arguments was referenced but not declared, reuse that
2676 // declaration node as our own, updating its source location to
2677 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002678 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002679 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002680 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00002681 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002682 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00002683 // Build the canonical type that describes the converted template
2684 // arguments of the class template partial specialization.
2685 CanonType = Context.getTemplateSpecializationType(
2686 TemplateName(ClassTemplate),
2687 Converted.getFlatArguments(),
2688 Converted.flatSize());
2689
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002690 // Create a new class template partial specialization declaration node.
2691 TemplateParameterList *TemplateParams
2692 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2693 ClassTemplatePartialSpecializationDecl *PrevPartial
2694 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2695 ClassTemplatePartialSpecializationDecl *Partial
2696 = ClassTemplatePartialSpecializationDecl::Create(Context,
2697 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002698 TemplateNameLoc,
2699 TemplateParams,
2700 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002701 Converted,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002702 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002703
2704 if (PrevPartial) {
2705 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2706 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2707 } else {
2708 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2709 }
2710 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00002711
2712 // Check that all of the template parameters of the class template
2713 // partial specialization are deducible from the template
2714 // arguments. If not, this class template partial specialization
2715 // will never be used.
2716 llvm::SmallVector<bool, 8> DeducibleParams;
2717 DeducibleParams.resize(TemplateParams->size());
2718 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2719 unsigned NumNonDeducible = 0;
2720 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2721 if (!DeducibleParams[I])
2722 ++NumNonDeducible;
2723
2724 if (NumNonDeducible) {
2725 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2726 << (NumNonDeducible > 1)
2727 << SourceRange(TemplateNameLoc, RAngleLoc);
2728 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2729 if (!DeducibleParams[I]) {
2730 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2731 if (Param->getDeclName())
2732 Diag(Param->getLocation(),
2733 diag::note_partial_spec_unused_parameter)
2734 << Param->getDeclName();
2735 else
2736 Diag(Param->getLocation(),
2737 diag::note_partial_spec_unused_parameter)
2738 << std::string("<anonymous>");
2739 }
2740 }
2741 }
Douglas Gregorcc636682009-02-17 23:15:12 +00002742 } else {
2743 // Create a new class template specialization declaration node for
2744 // this explicit specialization.
2745 Specialization
2746 = ClassTemplateSpecializationDecl::Create(Context,
2747 ClassTemplate->getDeclContext(),
2748 TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002749 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002750 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00002751 PrevDecl);
2752
2753 if (PrevDecl) {
2754 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2755 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2756 } else {
2757 ClassTemplate->getSpecializations().InsertNode(Specialization,
2758 InsertPos);
2759 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00002760
2761 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002762 }
2763
2764 // Note that this is an explicit specialization.
2765 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2766
2767 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00002768 if (TUK == TUK_Definition) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002769 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002770 // FIXME: Should also handle explicit specialization after implicit
2771 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002772 SourceRange Range(TemplateNameLoc, RAngleLoc);
2773 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002774 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002775 Diag(Def->getLocation(), diag::note_previous_definition);
2776 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002777 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002778 }
2779 }
2780
Douglas Gregorfc705b82009-02-26 22:19:44 +00002781 // Build the fully-sugared type for this class template
2782 // specialization as the user wrote in the specialization
2783 // itself. This means that we'll pretty-print the type retrieved
2784 // from the specialization's declaration the way that the user
2785 // actually wrote the specialization, rather than formatting the
2786 // name based on the "canonical" representation used to store the
2787 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002788 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002789 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00002790 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00002791 TemplateArgs.size(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00002792 CanonType);
Douglas Gregor7532dc62009-03-30 22:58:21 +00002793 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002794 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002795
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002796 // C++ [temp.expl.spec]p9:
2797 // A template explicit specialization is in the scope of the
2798 // namespace in which the template was defined.
2799 //
2800 // We actually implement this paragraph where we set the semantic
2801 // context (in the creation of the ClassTemplateSpecializationDecl),
2802 // but we also maintain the lexical context where the actual
2803 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002804 Specialization->setLexicalDeclContext(CurContext);
2805
2806 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00002807 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00002808 Specialization->startDefinition();
2809
2810 // Add the specialization into its lexical context, so that it can
2811 // be seen when iterating through the list of declarations in that
2812 // context. However, specializations are not found by name lookup.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002813 CurContext->addDecl(Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002814 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002815}
Douglas Gregord57959a2009-03-27 23:10:48 +00002816
Douglas Gregore542c862009-06-23 23:11:28 +00002817Sema::DeclPtrTy
2818Sema::ActOnTemplateDeclarator(Scope *S,
2819 MultiTemplateParamsArg TemplateParameterLists,
2820 Declarator &D) {
2821 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2822}
2823
Douglas Gregor52591bf2009-06-24 00:54:41 +00002824Sema::DeclPtrTy
2825Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2826 MultiTemplateParamsArg TemplateParameterLists,
2827 Declarator &D) {
2828 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2829 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2830 "Not a function declarator!");
2831 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2832
2833 if (FTI.hasPrototype) {
2834 // FIXME: Diagnose arguments without names in C.
2835 }
2836
2837 Scope *ParentScope = FnBodyScope->getParent();
2838
2839 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2840 move(TemplateParameterLists),
2841 /*IsFunctionDefinition=*/true);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002842 if (FunctionTemplateDecl *FunctionTemplate
2843 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregore53060f2009-06-25 22:08:12 +00002844 return ActOnStartOfFunctionDef(FnBodyScope,
2845 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002846 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2847 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00002848 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00002849}
2850
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002851// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00002852// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002853Sema::DeclResult
Douglas Gregor45f96552009-09-04 06:33:52 +00002854Sema::ActOnExplicitInstantiation(Scope *S,
2855 SourceLocation ExternLoc,
2856 SourceLocation TemplateLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002857 unsigned TagSpec,
2858 SourceLocation KWLoc,
2859 const CXXScopeSpec &SS,
2860 TemplateTy TemplateD,
2861 SourceLocation TemplateNameLoc,
2862 SourceLocation LAngleLoc,
2863 ASTTemplateArgsPtr TemplateArgsIn,
2864 SourceLocation *TemplateArgLocs,
2865 SourceLocation RAngleLoc,
2866 AttributeList *Attr) {
2867 // Find the class template we're specializing
2868 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2869 ClassTemplateDecl *ClassTemplate
2870 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2871
2872 // Check that the specialization uses the same tag kind as the
2873 // original template.
2874 TagDecl::TagKind Kind;
2875 switch (TagSpec) {
2876 default: assert(0 && "Unknown tag type!");
2877 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2878 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2879 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2880 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002881 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2882 Kind, KWLoc,
2883 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002884 Diag(KWLoc, diag::err_use_with_wrong_tag)
2885 << ClassTemplate
2886 << CodeModificationHint::CreateReplacement(KWLoc,
2887 ClassTemplate->getTemplatedDecl()->getKindName());
2888 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2889 diag::note_previous_use);
2890 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2891 }
2892
Douglas Gregorff668032009-05-13 18:28:20 +00002893 // C++0x [temp.explicit]p2:
2894 // [...] An explicit instantiation shall appear in an enclosing
2895 // namespace of its template. [...]
2896 //
2897 // This is C++ DR 275.
2898 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2899 TemplateNameLoc,
2900 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002901 /*PartialSpecialization=*/false,
Douglas Gregorff668032009-05-13 18:28:20 +00002902 /*ExplicitInstantiation=*/true))
2903 return true;
2904
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002905 // Translate the parser's template argument list in our AST format.
2906 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2907 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2908
2909 // Check that the template argument list is well-formed for this
2910 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002911 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2912 TemplateArgs.size());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002913 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00002914 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002915 RAngleLoc, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002916 return true;
2917
Anders Carlssonfb250522009-06-23 01:26:57 +00002918 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002919 ClassTemplate->getTemplateParameters()->size()) &&
2920 "Converted template argument list is too short!");
2921
2922 // Find the class template specialization declaration that
2923 // corresponds to these arguments.
2924 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002925 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002926 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002927 Converted.flatSize(),
2928 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002929 void *InsertPos = 0;
2930 ClassTemplateSpecializationDecl *PrevDecl
2931 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2932
2933 ClassTemplateSpecializationDecl *Specialization = 0;
2934
Douglas Gregorff668032009-05-13 18:28:20 +00002935 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002936 if (PrevDecl) {
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002937 if (PrevDecl->getSpecializationKind()
2938 == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002939 // This particular specialization has already been declared or
2940 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002941 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2942 << Context.getTypeDeclType(PrevDecl);
2943 Diag(PrevDecl->getLocation(),
2944 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002945 return DeclPtrTy::make(PrevDecl);
2946 }
2947
Douglas Gregorff668032009-05-13 18:28:20 +00002948 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002949 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002950 // For a given set of template parameters, if an explicit
2951 // instantiation of a template appears after a declaration of
2952 // an explicit specialization for that template, the explicit
2953 // instantiation has no effect.
2954 if (!getLangOptions().CPlusPlus0x) {
2955 Diag(TemplateNameLoc,
2956 diag::ext_explicit_instantiation_after_specialization)
2957 << Context.getTypeDeclType(PrevDecl);
2958 Diag(PrevDecl->getLocation(),
2959 diag::note_previous_template_specialization);
2960 }
2961
2962 // Create a new class template specialization declaration node
2963 // for this explicit specialization. This node is only used to
2964 // record the existence of this explicit instantiation for
2965 // accurate reproduction of the source code; we don't actually
2966 // use it for anything, since it is semantically irrelevant.
2967 Specialization
2968 = ClassTemplateSpecializationDecl::Create(Context,
2969 ClassTemplate->getDeclContext(),
2970 TemplateNameLoc,
2971 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002972 Converted, 0);
Douglas Gregorff668032009-05-13 18:28:20 +00002973 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002974 CurContext->addDecl(Specialization);
Douglas Gregorff668032009-05-13 18:28:20 +00002975 return DeclPtrTy::make(Specialization);
2976 }
2977
2978 // If we have already (implicitly) instantiated this
2979 // specialization, there is less work to do.
2980 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2981 SpecializationRequiresInstantiation = false;
2982
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002983 // Since the only prior class template specialization with these
2984 // arguments was referenced but not declared, reuse that
2985 // declaration node as our own, updating its source location to
2986 // reflect our new declaration.
2987 Specialization = PrevDecl;
2988 Specialization->setLocation(TemplateNameLoc);
2989 PrevDecl = 0;
2990 } else {
2991 // Create a new class template specialization declaration node for
2992 // this explicit specialization.
2993 Specialization
2994 = ClassTemplateSpecializationDecl::Create(Context,
2995 ClassTemplate->getDeclContext(),
2996 TemplateNameLoc,
2997 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002998 Converted, 0);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002999
3000 ClassTemplate->getSpecializations().InsertNode(Specialization,
3001 InsertPos);
3002 }
3003
3004 // Build the fully-sugared type for this explicit instantiation as
3005 // the user wrote in the explicit instantiation itself. This means
3006 // that we'll pretty-print the type retrieved from the
3007 // specialization's declaration the way that the user actually wrote
3008 // the explicit instantiation, rather than formatting the name based
3009 // on the "canonical" representation used to store the template
3010 // arguments in the specialization.
3011 QualType WrittenTy
3012 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00003013 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003014 TemplateArgs.size(),
3015 Context.getTypeDeclType(Specialization));
3016 Specialization->setTypeAsWritten(WrittenTy);
3017 TemplateArgsIn.release();
3018
3019 // Add the explicit instantiation into its lexical context. However,
3020 // since explicit instantiations are never found by name lookup, we
3021 // just put it into the declaration context directly.
3022 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003023 CurContext->addDecl(Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003024
3025 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003026 // A definition of a class template or class member template
3027 // shall be in scope at the point of the explicit instantiation of
3028 // the class template or class member template.
3029 //
3030 // This check comes when we actually try to perform the
3031 // instantiation.
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003032 TemplateSpecializationKind TSK
3033 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3034 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore2c31ff2009-05-15 17:59:04 +00003035 if (SpecializationRequiresInstantiation)
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003036 InstantiateClassTemplateSpecialization(Specialization, TSK);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00003037 else // Instantiate the members of this class template specialization.
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003038 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization,
3039 TSK);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003040
3041 return DeclPtrTy::make(Specialization);
3042}
3043
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003044// Explicit instantiation of a member class of a class template.
3045Sema::DeclResult
Douglas Gregor45f96552009-09-04 06:33:52 +00003046Sema::ActOnExplicitInstantiation(Scope *S,
3047 SourceLocation ExternLoc,
3048 SourceLocation TemplateLoc,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003049 unsigned TagSpec,
3050 SourceLocation KWLoc,
3051 const CXXScopeSpec &SS,
3052 IdentifierInfo *Name,
3053 SourceLocation NameLoc,
3054 AttributeList *Attr) {
3055
Douglas Gregor402abb52009-05-28 23:31:59 +00003056 bool Owned = false;
John McCall0f434ec2009-07-31 02:45:11 +00003057 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00003058 KWLoc, SS, Name, NameLoc, Attr, AS_none,
3059 MultiTemplateParamsArg(*this, 0, 0), Owned);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003060 if (!TagD)
3061 return true;
3062
3063 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3064 if (Tag->isEnum()) {
3065 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3066 << Context.getTypeDeclType(Tag);
3067 return true;
3068 }
3069
Douglas Gregord0c87372009-05-27 17:30:49 +00003070 if (Tag->isInvalidDecl())
3071 return true;
3072
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003073 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3074 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3075 if (!Pattern) {
3076 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3077 << Context.getTypeDeclType(Record);
3078 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3079 return true;
3080 }
3081
3082 // 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 (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003088 // FIXME: In C++98, we would like to turn these errors into warnings,
3089 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003090 DeclContext *PatternContext
3091 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
3092 if (!CurContext->Encloses(PatternContext)) {
3093 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
3094 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
3095 Diag(Pattern->getLocation(), diag::note_previous_declaration);
3096 }
3097 }
3098
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003099 TemplateSpecializationKind TSK
3100 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3101 : TSK_ExplicitInstantiationDeclaration;
3102
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003103 if (!Record->getDefinition(Context)) {
3104 // If the class has a definition, instantiate it (and all of its
3105 // members, recursively).
3106 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
3107 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00003108 getTemplateInstantiationArgs(Record),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003109 TSK))
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003110 return true;
John McCallce3ff2b2009-08-25 22:02:44 +00003111 } else // Instantiate all of the members of the class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003112 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003113 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003114
Mike Stump390b4cc2009-05-16 07:39:55 +00003115 // FIXME: We don't have any representation for explicit instantiations of
3116 // member classes. Such a representation is not needed for compilation, but it
3117 // should be available for clients that want to see all of the declarations in
3118 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003119 return TagD;
3120}
3121
Douglas Gregord57959a2009-03-27 23:10:48 +00003122Sema::TypeResult
3123Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3124 const IdentifierInfo &II, SourceLocation IdLoc) {
3125 NestedNameSpecifier *NNS
3126 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3127 if (!NNS)
3128 return true;
3129
3130 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00003131 if (T.isNull())
3132 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00003133 return T.getAsOpaquePtr();
3134}
3135
Douglas Gregor17343172009-04-01 00:28:59 +00003136Sema::TypeResult
3137Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3138 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003139 QualType T = GetTypeFromParser(Ty);
Douglas Gregor17343172009-04-01 00:28:59 +00003140 NestedNameSpecifier *NNS
3141 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3142 const TemplateSpecializationType *TemplateId
3143 = T->getAsTemplateSpecializationType();
3144 assert(TemplateId && "Expected a template specialization type");
3145
Douglas Gregor6946baf2009-09-02 13:05:45 +00003146 if (computeDeclContext(SS, false)) {
3147 // If we can compute a declaration context, then the "typename"
3148 // keyword was superfluous. Just build a QualifiedNameType to keep
3149 // track of the nested-name-specifier.
3150
3151 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
3152 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
3153 }
3154
3155 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00003156}
3157
Douglas Gregord57959a2009-03-27 23:10:48 +00003158/// \brief Build the type that describes a C++ typename specifier,
3159/// e.g., "typename T::type".
3160QualType
3161Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
3162 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00003163 CXXRecordDecl *CurrentInstantiation = 0;
3164 if (NNS->isDependent()) {
3165 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00003166
Douglas Gregor42af25f2009-05-11 19:58:34 +00003167 // If the nested-name-specifier does not refer to the current
3168 // instantiation, then build a typename type.
3169 if (!CurrentInstantiation)
3170 return Context.getTypenameType(NNS, &II);
Douglas Gregorde18d122009-09-02 13:12:51 +00003171
3172 // The nested-name-specifier refers to the current instantiation, so the
3173 // "typename" keyword itself is superfluous. In C++03, the program is
3174 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
3175 // extraneous "typename" keywords, and we retroactively apply this DR to
3176 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00003177 }
Douglas Gregord57959a2009-03-27 23:10:48 +00003178
Douglas Gregor42af25f2009-05-11 19:58:34 +00003179 DeclContext *Ctx = 0;
3180
3181 if (CurrentInstantiation)
3182 Ctx = CurrentInstantiation;
3183 else {
3184 CXXScopeSpec SS;
3185 SS.setScopeRep(NNS);
3186 SS.setRange(Range);
3187 if (RequireCompleteDeclContext(SS))
3188 return QualType();
3189
3190 Ctx = computeDeclContext(SS);
3191 }
Douglas Gregord57959a2009-03-27 23:10:48 +00003192 assert(Ctx && "No declaration context?");
3193
3194 DeclarationName Name(&II);
3195 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
3196 false);
3197 unsigned DiagID = 0;
3198 Decl *Referenced = 0;
3199 switch (Result.getKind()) {
3200 case LookupResult::NotFound:
3201 if (Ctx->isTranslationUnit())
3202 DiagID = diag::err_typename_nested_not_found_global;
3203 else
3204 DiagID = diag::err_typename_nested_not_found;
3205 break;
3206
3207 case LookupResult::Found:
3208 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3209 // We found a type. Build a QualifiedNameType, since the
3210 // typename-specifier was just sugar. FIXME: Tell
3211 // QualifiedNameType that it has a "typename" prefix.
3212 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3213 }
3214
3215 DiagID = diag::err_typename_nested_not_type;
3216 Referenced = Result.getAsDecl();
3217 break;
3218
3219 case LookupResult::FoundOverloaded:
3220 DiagID = diag::err_typename_nested_not_type;
3221 Referenced = *Result.begin();
3222 break;
3223
3224 case LookupResult::AmbiguousBaseSubobjectTypes:
3225 case LookupResult::AmbiguousBaseSubobjects:
3226 case LookupResult::AmbiguousReference:
3227 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3228 return QualType();
3229 }
3230
3231 // If we get here, it's because name lookup did not find a
3232 // type. Emit an appropriate diagnostic and return an error.
3233 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3234 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3235 else
3236 Diag(Range.getEnd(), DiagID) << Range << Name;
3237 if (Referenced)
3238 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3239 << Name;
3240 return QualType();
3241}
Douglas Gregor4a959d82009-08-06 16:20:37 +00003242
3243namespace {
3244 // See Sema::RebuildTypeInCurrentInstantiation
3245 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3246 : public TreeTransform<CurrentInstantiationRebuilder>
3247 {
3248 SourceLocation Loc;
3249 DeclarationName Entity;
3250
3251 public:
3252 CurrentInstantiationRebuilder(Sema &SemaRef,
3253 SourceLocation Loc,
3254 DeclarationName Entity)
3255 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
3256 Loc(Loc), Entity(Entity) { }
3257
3258 /// \brief Determine whether the given type \p T has already been
3259 /// transformed.
3260 ///
3261 /// For the purposes of type reconstruction, a type has already been
3262 /// transformed if it is NULL or if it is not dependent.
3263 bool AlreadyTransformed(QualType T) {
3264 return T.isNull() || !T->isDependentType();
3265 }
3266
3267 /// \brief Returns the location of the entity whose type is being
3268 /// rebuilt.
3269 SourceLocation getBaseLocation() { return Loc; }
3270
3271 /// \brief Returns the name of the entity whose type is being rebuilt.
3272 DeclarationName getBaseEntity() { return Entity; }
3273
3274 /// \brief Transforms an expression by returning the expression itself
3275 /// (an identity function).
3276 ///
3277 /// FIXME: This is completely unsafe; we will need to actually clone the
3278 /// expressions.
3279 Sema::OwningExprResult TransformExpr(Expr *E) {
3280 return getSema().Owned(E);
3281 }
3282
3283 /// \brief Transforms a typename type by determining whether the type now
3284 /// refers to a member of the current instantiation, and then
3285 /// type-checking and building a QualifiedNameType (when possible).
3286 QualType TransformTypenameType(const TypenameType *T);
3287 };
3288}
3289
3290QualType
3291CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3292 NestedNameSpecifier *NNS
3293 = TransformNestedNameSpecifier(T->getQualifier(),
3294 /*FIXME:*/SourceRange(getBaseLocation()));
3295 if (!NNS)
3296 return QualType();
3297
3298 // If the nested-name-specifier did not change, and we cannot compute the
3299 // context corresponding to the nested-name-specifier, then this
3300 // typename type will not change; exit early.
3301 CXXScopeSpec SS;
3302 SS.setRange(SourceRange(getBaseLocation()));
3303 SS.setScopeRep(NNS);
3304 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3305 return QualType(T, 0);
3306
3307 // Rebuild the typename type, which will probably turn into a
3308 // QualifiedNameType.
3309 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
3310 QualType NewTemplateId
3311 = TransformType(QualType(TemplateId, 0));
3312 if (NewTemplateId.isNull())
3313 return QualType();
3314
3315 if (NNS == T->getQualifier() &&
3316 NewTemplateId == QualType(TemplateId, 0))
3317 return QualType(T, 0);
3318
3319 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3320 }
3321
3322 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3323}
3324
3325/// \brief Rebuilds a type within the context of the current instantiation.
3326///
3327/// The type \p T is part of the type of an out-of-line member definition of
3328/// a class template (or class template partial specialization) that was parsed
3329/// and constructed before we entered the scope of the class template (or
3330/// partial specialization thereof). This routine will rebuild that type now
3331/// that we have entered the declarator's scope, which may produce different
3332/// canonical types, e.g.,
3333///
3334/// \code
3335/// template<typename T>
3336/// struct X {
3337/// typedef T* pointer;
3338/// pointer data();
3339/// };
3340///
3341/// template<typename T>
3342/// typename X<T>::pointer X<T>::data() { ... }
3343/// \endcode
3344///
3345/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3346/// since we do not know that we can look into X<T> when we parsed the type.
3347/// This function will rebuild the type, performing the lookup of "pointer"
3348/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3349/// as the canonical type of T*, allowing the return types of the out-of-line
3350/// definition and the declaration to match.
3351QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3352 DeclarationName Name) {
3353 if (T.isNull() || !T->isDependentType())
3354 return T;
3355
3356 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3357 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00003358}