blob: 773a2b1b925b2a175116f9c6d1b7d80bf851658f [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregor39a8de12009-02-25 19:37:18 +000029TemplateNameKind Sema::isTemplateName(IdentifierInfo &II, Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +000030 DeclPtrTy &Template,
Douglas Gregor39a8de12009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000033
34 if (IIDecl) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000035 if (isa<TemplateDecl>(IIDecl)) {
Chris Lattnerb28317a2009-03-28 19:18:32 +000036 Template = DeclPtrTy::make(IIDecl);
Douglas Gregor55f6b142009-02-09 18:46:07 +000037 if (isa<FunctionTemplateDecl>(IIDecl))
38 return TNK_Function_template;
Chris Lattnerb28317a2009-03-28 19:18:32 +000039 if (isa<ClassTemplateDecl>(IIDecl))
Douglas Gregor55f6b142009-02-09 18:46:07 +000040 return TNK_Class_template;
Chris Lattnerb28317a2009-03-28 19:18:32 +000041 assert(isa<TemplateTemplateParmDecl>(IIDecl) && "Unknown TemplateDecl");
42 return TNK_Template_template_parm;
Douglas Gregorbefc20e2009-03-26 00:10:35 +000043 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
44 // C++ [temp.local]p1:
45 // Like normal (non-template) classes, class templates have an
46 // injected-class-name (Clause 9). The injected-class-name
47 // can be used with or without a template-argument-list. When
48 // it is used without a template-argument-list, it is
49 // equivalent to the injected-class-name followed by the
50 // template-parameters of the class template enclosed in
51 // <>. When it is used with a template-argument-list, it
52 // refers to the specified class template specialization,
53 // which could be the current specialization or another
54 // specialization.
55 if (Record->isInjectedClassName()) {
56 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
Chris Lattnerb28317a2009-03-28 19:18:32 +000057 if ((Template = DeclPtrTy::make(Record->getDescribedClassTemplate())))
Douglas Gregorbefc20e2009-03-26 00:10:35 +000058 return TNK_Class_template;
Chris Lattnerb28317a2009-03-28 19:18:32 +000059 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregorbefc20e2009-03-26 00:10:35 +000060 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Chris Lattnerb28317a2009-03-28 19:18:32 +000061 Template = DeclPtrTy::make(Spec->getSpecializedTemplate());
Douglas Gregorbefc20e2009-03-26 00:10:35 +000062 return TNK_Class_template;
63 }
64 }
Douglas Gregor55f6b142009-02-09 18:46:07 +000065 }
Douglas Gregoraaba5e32009-02-04 19:02:06 +000066
Douglas Gregor55f6b142009-02-09 18:46:07 +000067 // FIXME: What follows is a gross hack.
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000068 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000069 if (FD->getType()->isDependentType()) {
Chris Lattnerb28317a2009-03-28 19:18:32 +000070 Template = DeclPtrTy::make(FD);
Douglas Gregor55f6b142009-02-09 18:46:07 +000071 return TNK_Function_template;
72 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000073 } else if (OverloadedFunctionDecl *Ovl
74 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
75 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
76 FEnd = Ovl->function_end();
77 F != FEnd; ++F) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000078 if ((*F)->getType()->isDependentType()) {
Chris Lattnerb28317a2009-03-28 19:18:32 +000079 Template = DeclPtrTy::make(Ovl);
Douglas Gregor55f6b142009-02-09 18:46:07 +000080 return TNK_Function_template;
81 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000082 }
83 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000084 }
Douglas Gregor55f6b142009-02-09 18:46:07 +000085 return TNK_Non_template;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000086}
87
Douglas Gregor72c3f312008-12-05 18:15:24 +000088/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
89/// that the template parameter 'PrevDecl' is being shadowed by a new
90/// declaration at location Loc. Returns true to indicate that this is
91/// an error, and false otherwise.
92bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +000093 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +000094
95 // Microsoft Visual C++ permits template parameters to be shadowed.
96 if (getLangOptions().Microsoft)
97 return false;
98
99 // C++ [temp.local]p4:
100 // A template-parameter shall not be redeclared within its
101 // scope (including nested scopes).
102 Diag(Loc, diag::err_template_param_shadow)
103 << cast<NamedDecl>(PrevDecl)->getDeclName();
104 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
105 return true;
106}
107
Douglas Gregor2943aed2009-03-03 04:44:36 +0000108/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000109/// the parameter D to reference the templated declaration and return a pointer
110/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000111TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
112 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
113 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000114 return Temp;
115 }
116 return 0;
117}
118
Douglas Gregor72c3f312008-12-05 18:15:24 +0000119/// ActOnTypeParameter - Called when a C++ template type parameter
120/// (e.g., "typename T") has been parsed. Typename specifies whether
121/// the keyword "typename" was used to declare the type parameter
122/// (otherwise, "class" was used), and KeyLoc is the location of the
123/// "class" or "typename" keyword. ParamName is the name of the
124/// parameter (NULL indicates an unnamed template parameter) and
125/// ParamName is the location of the parameter name (if any).
126/// If the type parameter has a default argument, it will be added
127/// later via ActOnTypeParameterDefault.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000128Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename,
129 SourceLocation KeyLoc,
130 IdentifierInfo *ParamName,
131 SourceLocation ParamNameLoc,
132 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000133 assert(S->isTemplateParamScope() &&
134 "Template type parameter not in template parameter scope!");
135 bool Invalid = false;
136
137 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000138 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000139 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000140 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
141 PrevDecl);
142 }
143
Douglas Gregorddc29e12009-02-06 22:42:48 +0000144 SourceLocation Loc = ParamNameLoc;
145 if (!ParamName)
146 Loc = KeyLoc;
147
Douglas Gregor72c3f312008-12-05 18:15:24 +0000148 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000149 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000150 Depth, Position, ParamName, Typename);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000151 if (Invalid)
152 Param->setInvalidDecl();
153
154 if (ParamName) {
155 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000156 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000157 IdResolver.AddDecl(Param);
158 }
159
Chris Lattnerb28317a2009-03-28 19:18:32 +0000160 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000161}
162
Douglas Gregord684b002009-02-10 19:49:53 +0000163/// ActOnTypeParameterDefault - Adds a default argument (the type
164/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000165void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000166 SourceLocation EqualLoc,
167 SourceLocation DefaultLoc,
168 TypeTy *DefaultT) {
169 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000170 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000171 QualType Default = QualType::getFromOpaquePtr(DefaultT);
172
173 // C++ [temp.param]p14:
174 // A template-parameter shall not be used in its own default argument.
175 // FIXME: Implement this check! Needs a recursive walk over the types.
176
177 // Check the template argument itself.
178 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
179 Parm->setInvalidDecl();
180 return;
181 }
182
183 Parm->setDefaultArgument(Default, DefaultLoc, false);
184}
185
Douglas Gregor2943aed2009-03-03 04:44:36 +0000186/// \brief Check that the type of a non-type template parameter is
187/// well-formed.
188///
189/// \returns the (possibly-promoted) parameter type if valid;
190/// otherwise, produces a diagnostic and returns a NULL type.
191QualType
192Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
193 // C++ [temp.param]p4:
194 //
195 // A non-type template-parameter shall have one of the following
196 // (optionally cv-qualified) types:
197 //
198 // -- integral or enumeration type,
199 if (T->isIntegralType() || T->isEnumeralType() ||
200 // -- pointer to object or pointer to function,
201 (T->isPointerType() &&
202 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
203 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
204 // -- reference to object or reference to function,
205 T->isReferenceType() ||
206 // -- pointer to member.
207 T->isMemberPointerType() ||
208 // If T is a dependent type, we can't do the check now, so we
209 // assume that it is well-formed.
210 T->isDependentType())
211 return T;
212 // C++ [temp.param]p8:
213 //
214 // A non-type template-parameter of type "array of T" or
215 // "function returning T" is adjusted to be of type "pointer to
216 // T" or "pointer to function returning T", respectively.
217 else if (T->isArrayType())
218 // FIXME: Keep the type prior to promotion?
219 return Context.getArrayDecayedType(T);
220 else if (T->isFunctionType())
221 // FIXME: Keep the type prior to promotion?
222 return Context.getPointerType(T);
223
224 Diag(Loc, diag::err_template_nontype_parm_bad_type)
225 << T;
226
227 return QualType();
228}
229
Douglas Gregor72c3f312008-12-05 18:15:24 +0000230/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
231/// template parameter (e.g., "int Size" in "template<int Size>
232/// class Array") has been parsed. S is the current scope and D is
233/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000234Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
235 unsigned Depth,
236 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000237 QualType T = GetTypeForDeclarator(D, S);
238
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000239 assert(S->isTemplateParamScope() &&
240 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000241 bool Invalid = false;
242
243 IdentifierInfo *ParamName = D.getIdentifier();
244 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000245 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000246 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000247 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000248 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000249 }
250
Douglas Gregor2943aed2009-03-03 04:44:36 +0000251 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000252 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000253 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000254 Invalid = true;
255 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000256
Douglas Gregor72c3f312008-12-05 18:15:24 +0000257 NonTypeTemplateParmDecl *Param
258 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000259 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000260 if (Invalid)
261 Param->setInvalidDecl();
262
263 if (D.getIdentifier()) {
264 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000265 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000266 IdResolver.AddDecl(Param);
267 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000268 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000269}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000270
Douglas Gregord684b002009-02-10 19:49:53 +0000271/// \brief Adds a default argument to the given non-type template
272/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000273void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000274 SourceLocation EqualLoc,
275 ExprArg DefaultE) {
276 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000277 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000278 Expr *Default = static_cast<Expr *>(DefaultE.get());
279
280 // C++ [temp.param]p14:
281 // A template-parameter shall not be used in its own default argument.
282 // FIXME: Implement this check! Needs a recursive walk over the types.
283
284 // Check the well-formedness of the default template argument.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000285 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000286 TemplateParm->setInvalidDecl();
287 return;
288 }
289
290 TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release()));
291}
292
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000293
294/// ActOnTemplateTemplateParameter - Called when a C++ template template
295/// parameter (e.g. T in template <template <typename> class T> class array)
296/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000297Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
298 SourceLocation TmpLoc,
299 TemplateParamsTy *Params,
300 IdentifierInfo *Name,
301 SourceLocation NameLoc,
302 unsigned Depth,
303 unsigned Position)
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000304{
305 assert(S->isTemplateParamScope() &&
306 "Template template parameter not in template parameter scope!");
307
308 // Construct the parameter object.
309 TemplateTemplateParmDecl *Param =
310 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
311 Position, Name,
312 (TemplateParameterList*)Params);
313
314 // Make sure the parameter is valid.
315 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
316 // do anything yet. However, if the template parameter list or (eventual)
317 // default value is ever invalidated, that will propagate here.
318 bool Invalid = false;
319 if (Invalid) {
320 Param->setInvalidDecl();
321 }
322
323 // If the tt-param has a name, then link the identifier into the scope
324 // and lookup mechanisms.
325 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000326 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000327 IdResolver.AddDecl(Param);
328 }
329
Chris Lattnerb28317a2009-03-28 19:18:32 +0000330 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000331}
332
Douglas Gregord684b002009-02-10 19:49:53 +0000333/// \brief Adds a default argument to the given template template
334/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000335void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000336 SourceLocation EqualLoc,
337 ExprArg DefaultE) {
338 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000339 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000340
341 // Since a template-template parameter's default argument is an
342 // id-expression, it must be a DeclRefExpr.
343 DeclRefExpr *Default
344 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
345
346 // C++ [temp.param]p14:
347 // A template-parameter shall not be used in its own default argument.
348 // FIXME: Implement this check! Needs a recursive walk over the types.
349
350 // Check the well-formedness of the template argument.
351 if (!isa<TemplateDecl>(Default->getDecl())) {
352 Diag(Default->getSourceRange().getBegin(),
353 diag::err_template_arg_must_be_template)
354 << Default->getSourceRange();
355 TemplateParm->setInvalidDecl();
356 return;
357 }
358 if (CheckTemplateArgument(TemplateParm, Default)) {
359 TemplateParm->setInvalidDecl();
360 return;
361 }
362
363 DefaultE.release();
364 TemplateParm->setDefaultArgument(Default);
365}
366
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000367/// ActOnTemplateParameterList - Builds a TemplateParameterList that
368/// contains the template parameters in Params/NumParams.
369Sema::TemplateParamsTy *
370Sema::ActOnTemplateParameterList(unsigned Depth,
371 SourceLocation ExportLoc,
372 SourceLocation TemplateLoc,
373 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000374 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000375 SourceLocation RAngleLoc) {
376 if (ExportLoc.isValid())
377 Diag(ExportLoc, diag::note_template_export_unsupported);
378
Douglas Gregorddc29e12009-02-06 22:42:48 +0000379 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
380 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000381}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000382
Douglas Gregor212e81c2009-03-25 00:13:59 +0000383Sema::DeclResult
Douglas Gregorddc29e12009-02-06 22:42:48 +0000384Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
385 SourceLocation KWLoc, const CXXScopeSpec &SS,
386 IdentifierInfo *Name, SourceLocation NameLoc,
387 AttributeList *Attr,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000388 MultiTemplateParamsArg TemplateParameterLists,
389 AccessSpecifier AS) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000390 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
391 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000392 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000393
394 // Check that we can declare a template here.
395 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000396 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000397
398 TagDecl::TagKind Kind;
399 switch (TagSpec) {
400 default: assert(0 && "Unknown tag type!");
401 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
402 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
403 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
404 }
405
406 // There is no such thing as an unnamed class template.
407 if (!Name) {
408 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000409 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000410 }
411
412 // Find any previous declaration with this name.
413 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
414 true);
415 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
416 NamedDecl *PrevDecl = 0;
417 if (Previous.begin() != Previous.end())
418 PrevDecl = *Previous.begin();
419
420 DeclContext *SemanticContext = CurContext;
421 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000422 SemanticContext = computeDeclContext(SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000423
424 // FIXME: need to match up several levels of template parameter
425 // lists here.
426 }
427
428 // FIXME: member templates!
429 TemplateParameterList *TemplateParams
430 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
431
432 // If there is a previous declaration with the same name, check
433 // whether this is a valid redeclaration.
434 ClassTemplateDecl *PrevClassTemplate
435 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
436 if (PrevClassTemplate) {
437 // Ensure that the template parameter lists are compatible.
438 if (!TemplateParameterListsAreEqual(TemplateParams,
439 PrevClassTemplate->getTemplateParameters(),
440 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000441 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000442
443 // C++ [temp.class]p4:
444 // In a redeclaration, partial specialization, explicit
445 // specialization or explicit instantiation of a class template,
446 // the class-key shall agree in kind with the original class
447 // template declaration (7.1.5.3).
448 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
449 if (PrevRecordDecl->getTagKind() != Kind) {
450 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
451 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000452 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000453 }
454
455
456 // Check for redefinition of this class template.
457 if (TK == TK_Definition) {
458 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
459 Diag(NameLoc, diag::err_redefinition) << Name;
460 Diag(Def->getLocation(), diag::note_previous_definition);
461 // FIXME: Would it make sense to try to "forget" the previous
462 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000463 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000464 }
465 }
466 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
467 // Maybe we will complain about the shadowed template parameter.
468 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
469 // Just pretend that we didn't see the previous declaration.
470 PrevDecl = 0;
471 } else if (PrevDecl) {
472 // C++ [temp]p5:
473 // A class template shall not have the same name as any other
474 // template, class, function, object, enumeration, enumerator,
475 // namespace, or type in the same scope (3.3), except as specified
476 // in (14.5.4).
477 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
478 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000479 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000480 }
481
Douglas Gregord684b002009-02-10 19:49:53 +0000482 // Check the template parameter list of this declaration, possibly
483 // merging in the template parameter list from the previous class
484 // template declaration.
485 if (CheckTemplateParameterList(TemplateParams,
486 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
487 Invalid = true;
488
Douglas Gregorddc29e12009-02-06 22:42:48 +0000489 // If we had a scope specifier, we better have a previous template
490 // declaration!
491
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000492 CXXRecordDecl *NewClass =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000493 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
494 PrevClassTemplate?
495 PrevClassTemplate->getTemplatedDecl() : 0);
496
497 ClassTemplateDecl *NewTemplate
498 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
499 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000500 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000501 NewClass->setDescribedClassTemplate(NewTemplate);
502
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000503 // Set the access specifier.
504 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
505
Douglas Gregorddc29e12009-02-06 22:42:48 +0000506 // Set the lexical context of these templates
507 NewClass->setLexicalDeclContext(CurContext);
508 NewTemplate->setLexicalDeclContext(CurContext);
509
510 if (TK == TK_Definition)
511 NewClass->startDefinition();
512
513 if (Attr)
514 ProcessDeclAttributeList(NewClass, Attr);
515
516 PushOnScopeChains(NewTemplate, S);
517
Douglas Gregord684b002009-02-10 19:49:53 +0000518 if (Invalid) {
519 NewTemplate->setInvalidDecl();
520 NewClass->setInvalidDecl();
521 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000522 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000523}
524
Douglas Gregord684b002009-02-10 19:49:53 +0000525/// \brief Checks the validity of a template parameter list, possibly
526/// considering the template parameter list from a previous
527/// declaration.
528///
529/// If an "old" template parameter list is provided, it must be
530/// equivalent (per TemplateParameterListsAreEqual) to the "new"
531/// template parameter list.
532///
533/// \param NewParams Template parameter list for a new template
534/// declaration. This template parameter list will be updated with any
535/// default arguments that are carried through from the previous
536/// template parameter list.
537///
538/// \param OldParams If provided, template parameter list from a
539/// previous declaration of the same template. Default template
540/// arguments will be merged from the old template parameter list to
541/// the new template parameter list.
542///
543/// \returns true if an error occurred, false otherwise.
544bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
545 TemplateParameterList *OldParams) {
546 bool Invalid = false;
547
548 // C++ [temp.param]p10:
549 // The set of default template-arguments available for use with a
550 // template declaration or definition is obtained by merging the
551 // default arguments from the definition (if in scope) and all
552 // declarations in scope in the same way default function
553 // arguments are (8.3.6).
554 bool SawDefaultArgument = false;
555 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000556
Mike Stump1a35fde2009-02-11 23:03:27 +0000557 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000558 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000559 if (OldParams)
560 OldParam = OldParams->begin();
561
562 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
563 NewParamEnd = NewParams->end();
564 NewParam != NewParamEnd; ++NewParam) {
565 // Variables used to diagnose redundant default arguments
566 bool RedundantDefaultArg = false;
567 SourceLocation OldDefaultLoc;
568 SourceLocation NewDefaultLoc;
569
570 // Variables used to diagnose missing default arguments
571 bool MissingDefaultArg = false;
572
573 // Merge default arguments for template type parameters.
574 if (TemplateTypeParmDecl *NewTypeParm
575 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
576 TemplateTypeParmDecl *OldTypeParm
577 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
578
579 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
580 NewTypeParm->hasDefaultArgument()) {
581 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
582 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
583 SawDefaultArgument = true;
584 RedundantDefaultArg = true;
585 PreviousDefaultArgLoc = NewDefaultLoc;
586 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
587 // Merge the default argument from the old declaration to the
588 // new declaration.
589 SawDefaultArgument = true;
590 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
591 OldTypeParm->getDefaultArgumentLoc(),
592 true);
593 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
594 } else if (NewTypeParm->hasDefaultArgument()) {
595 SawDefaultArgument = true;
596 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
597 } else if (SawDefaultArgument)
598 MissingDefaultArg = true;
599 }
600 // Merge default arguments for non-type template parameters
601 else if (NonTypeTemplateParmDecl *NewNonTypeParm
602 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
603 NonTypeTemplateParmDecl *OldNonTypeParm
604 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
605 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
606 NewNonTypeParm->hasDefaultArgument()) {
607 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
608 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
609 SawDefaultArgument = true;
610 RedundantDefaultArg = true;
611 PreviousDefaultArgLoc = NewDefaultLoc;
612 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
613 // Merge the default argument from the old declaration to the
614 // new declaration.
615 SawDefaultArgument = true;
616 // FIXME: We need to create a new kind of "default argument"
617 // expression that points to a previous template template
618 // parameter.
619 NewNonTypeParm->setDefaultArgument(
620 OldNonTypeParm->getDefaultArgument());
621 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
622 } else if (NewNonTypeParm->hasDefaultArgument()) {
623 SawDefaultArgument = true;
624 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
625 } else if (SawDefaultArgument)
626 MissingDefaultArg = true;
627 }
628 // Merge default arguments for template template parameters
629 else {
630 TemplateTemplateParmDecl *NewTemplateParm
631 = cast<TemplateTemplateParmDecl>(*NewParam);
632 TemplateTemplateParmDecl *OldTemplateParm
633 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
634 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
635 NewTemplateParm->hasDefaultArgument()) {
636 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
637 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
638 SawDefaultArgument = true;
639 RedundantDefaultArg = true;
640 PreviousDefaultArgLoc = NewDefaultLoc;
641 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
642 // Merge the default argument from the old declaration to the
643 // new declaration.
644 SawDefaultArgument = true;
645 // FIXME: We need to create a new kind of "default argument"
646 // expression that points to a previous template template
647 // parameter.
648 NewTemplateParm->setDefaultArgument(
649 OldTemplateParm->getDefaultArgument());
650 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
651 } else if (NewTemplateParm->hasDefaultArgument()) {
652 SawDefaultArgument = true;
653 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
654 } else if (SawDefaultArgument)
655 MissingDefaultArg = true;
656 }
657
658 if (RedundantDefaultArg) {
659 // C++ [temp.param]p12:
660 // A template-parameter shall not be given default arguments
661 // by two different declarations in the same scope.
662 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
663 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
664 Invalid = true;
665 } else if (MissingDefaultArg) {
666 // C++ [temp.param]p11:
667 // If a template-parameter has a default template-argument,
668 // all subsequent template-parameters shall have a default
669 // template-argument supplied.
670 Diag((*NewParam)->getLocation(),
671 diag::err_template_param_default_arg_missing);
672 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
673 Invalid = true;
674 }
675
676 // If we have an old template parameter list that we're merging
677 // in, move on to the next parameter.
678 if (OldParams)
679 ++OldParam;
680 }
681
682 return Invalid;
683}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000684
Douglas Gregor40808ce2009-03-09 23:48:35 +0000685/// \brief Translates template arguments as provided by the parser
686/// into template arguments used by semantic analysis.
687static void
688translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
689 SourceLocation *TemplateArgLocs,
690 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
691 TemplateArgs.reserve(TemplateArgsIn.size());
692
693 void **Args = TemplateArgsIn.getArgs();
694 bool *ArgIsType = TemplateArgsIn.getArgIsType();
695 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
696 TemplateArgs.push_back(
697 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
698 QualType::getFromOpaquePtr(Args[Arg]))
699 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
700 }
701}
702
703QualType Sema::CheckClassTemplateId(ClassTemplateDecl *ClassTemplate,
704 SourceLocation TemplateLoc,
705 SourceLocation LAngleLoc,
706 const TemplateArgument *TemplateArgs,
707 unsigned NumTemplateArgs,
708 SourceLocation RAngleLoc) {
709 // Check that the template argument list is well-formed for this
710 // template.
711 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
712 if (CheckTemplateArgumentList(ClassTemplate, TemplateLoc, LAngleLoc,
713 TemplateArgs, NumTemplateArgs, RAngleLoc,
714 ConvertedTemplateArgs))
715 return QualType();
716
717 assert((ConvertedTemplateArgs.size() ==
718 ClassTemplate->getTemplateParameters()->size()) &&
719 "Converted template argument list is too short!");
720
721 QualType CanonType;
722
723 if (ClassTemplateSpecializationType::anyDependentTemplateArguments(
724 TemplateArgs,
725 NumTemplateArgs)) {
726 // This class template specialization is a dependent
727 // type. Therefore, its canonical type is another class template
728 // specialization type that contains all of the converted
729 // arguments in canonical form. This ensures that, e.g., A<T> and
730 // A<T, T> have identical types when A is declared as:
731 //
732 // template<typename T, typename U = T> struct A;
733
734 CanonType = Context.getClassTemplateSpecializationType(ClassTemplate,
735 &ConvertedTemplateArgs[0],
736 ConvertedTemplateArgs.size());
737 } else {
738 // Find the class template specialization declaration that
739 // corresponds to these arguments.
740 llvm::FoldingSetNodeID ID;
741 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
742 ConvertedTemplateArgs.size());
743 void *InsertPos = 0;
744 ClassTemplateSpecializationDecl *Decl
745 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
746 if (!Decl) {
747 // This is the first time we have referenced this class template
748 // specialization. Create the canonical declaration and add it to
749 // the set of specializations.
750 Decl = ClassTemplateSpecializationDecl::Create(Context,
751 ClassTemplate->getDeclContext(),
752 TemplateLoc,
753 ClassTemplate,
754 &ConvertedTemplateArgs[0],
755 ConvertedTemplateArgs.size(),
756 0);
757 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
758 Decl->setLexicalDeclContext(CurContext);
759 }
760
761 CanonType = Context.getTypeDeclType(Decl);
762 }
763
764 // Build the fully-sugared type for this class template
765 // specialization, which refers back to the class template
766 // specialization we created or found.
767 return Context.getClassTemplateSpecializationType(ClassTemplate,
768 TemplateArgs,
769 NumTemplateArgs,
770 CanonType);
771}
772
Douglas Gregorcc636682009-02-17 23:15:12 +0000773Action::TypeResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000774Sema::ActOnClassTemplateId(DeclPtrTy TemplateD, SourceLocation TemplateLoc,
Douglas Gregorcc636682009-02-17 23:15:12 +0000775 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000776 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +0000777 SourceLocation *TemplateArgLocs,
778 SourceLocation RAngleLoc,
779 const CXXScopeSpec *SS) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000780 TemplateDecl *Template = cast<TemplateDecl>(TemplateD.getAs<Decl>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000781 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(Template);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000782
Douglas Gregor40808ce2009-03-09 23:48:35 +0000783 // Translate the parser's template argument list in our AST format.
784 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
785 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000786
Douglas Gregor40808ce2009-03-09 23:48:35 +0000787 QualType Result = CheckClassTemplateId(ClassTemplate, TemplateLoc,
788 LAngleLoc,
789 &TemplateArgs[0],
790 TemplateArgs.size(),
791 RAngleLoc);
Douglas Gregore6258932009-03-19 00:39:20 +0000792
793 if (SS)
794 Result = getQualifiedNameType(*SS, Result);
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000795
Douglas Gregor40808ce2009-03-09 23:48:35 +0000796 TemplateArgsIn.release();
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000797 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000798}
799
Douglas Gregorc15cb382009-02-09 23:23:08 +0000800/// \brief Check that the given template argument list is well-formed
801/// for specializing the given template.
802bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
803 SourceLocation TemplateLoc,
804 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000805 const TemplateArgument *TemplateArgs,
806 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000807 SourceLocation RAngleLoc,
808 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000809 TemplateParameterList *Params = Template->getTemplateParameters();
810 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +0000811 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000812 bool Invalid = false;
813
814 if (NumArgs > NumParams ||
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000815 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000816 // FIXME: point at either the first arg beyond what we can handle,
817 // or the '>', depending on whether we have too many or too few
818 // arguments.
819 SourceRange Range;
820 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +0000821 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000822 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
823 << (NumArgs > NumParams)
824 << (isa<ClassTemplateDecl>(Template)? 0 :
825 isa<FunctionTemplateDecl>(Template)? 1 :
826 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
827 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000828 Diag(Template->getLocation(), diag::note_template_decl_here)
829 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +0000830 Invalid = true;
831 }
832
833 // C++ [temp.arg]p1:
834 // [...] The type and form of each template-argument specified in
835 // a template-id shall match the type and form specified for the
836 // corresponding parameter declared by the template in its
837 // template-parameter-list.
838 unsigned ArgIdx = 0;
839 for (TemplateParameterList::iterator Param = Params->begin(),
840 ParamEnd = Params->end();
841 Param != ParamEnd; ++Param, ++ArgIdx) {
842 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +0000843 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000844 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000845 // Retrieve the default template argument from the template
846 // parameter.
847 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
848 if (!TTP->hasDefaultArgument())
849 break;
850
Douglas Gregor40808ce2009-03-09 23:48:35 +0000851 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +0000852
853 // If the argument type is dependent, instantiate it now based
854 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +0000855 if (ArgType->isDependentType()) {
856 InstantiatingTemplate Inst(*this, TemplateLoc,
857 Template, &Converted[0],
858 Converted.size(),
859 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor99ebf652009-02-27 19:31:52 +0000860 ArgType = InstantiateType(ArgType, &Converted[0], Converted.size(),
861 TTP->getDefaultArgumentLoc(),
862 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +0000863 }
Douglas Gregor99ebf652009-02-27 19:31:52 +0000864
865 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +0000866 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000867
Douglas Gregor40808ce2009-03-09 23:48:35 +0000868 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000869 } else if (NonTypeTemplateParmDecl *NTTP
870 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
871 if (!NTTP->hasDefaultArgument())
872 break;
873
Douglas Gregor2943aed2009-03-03 04:44:36 +0000874 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +0000875 Arg = TemplateArgument(NTTP->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000876 } else {
877 TemplateTemplateParmDecl *TempParm
878 = cast<TemplateTemplateParmDecl>(*Param);
879
880 if (!TempParm->hasDefaultArgument())
881 break;
882
Douglas Gregor2943aed2009-03-03 04:44:36 +0000883 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +0000884 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000885 }
886 } else {
887 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +0000888 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000889 }
890
Douglas Gregorc15cb382009-02-09 23:23:08 +0000891
892 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
893 // Check template type parameters.
Douglas Gregor40808ce2009-03-09 23:48:35 +0000894 if (Arg.getKind() == TemplateArgument::Type) {
895 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregorc15cb382009-02-09 23:23:08 +0000896 Invalid = true;
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000897
898 // Add the converted template type argument.
899 Converted.push_back(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000900 TemplateArgument(Arg.getLocation(),
901 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregorc15cb382009-02-09 23:23:08 +0000902 continue;
903 }
904
905 // C++ [temp.arg.type]p1:
906 // A template-argument for a template-parameter which is a
907 // type shall be a type-id.
908
909 // We have a template type parameter but the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +0000910 // is not a type.
911 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor8b642592009-02-10 00:53:15 +0000912 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000913 Invalid = true;
914 } else if (NonTypeTemplateParmDecl *NTTP
915 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
916 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000917
918 // Instantiate the type of the non-type template parameter with
919 // the template arguments we've seen thus far.
920 QualType NTTPType = NTTP->getType();
921 if (NTTPType->isDependentType()) {
922 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +0000923 InstantiatingTemplate Inst(*this, TemplateLoc,
924 Template, &Converted[0],
925 Converted.size(),
926 SourceRange(TemplateLoc, RAngleLoc));
927
Douglas Gregor2943aed2009-03-03 04:44:36 +0000928 NTTPType = InstantiateType(NTTPType,
929 &Converted[0], Converted.size(),
930 NTTP->getLocation(),
931 NTTP->getDeclName());
932 // If that worked, check the non-type template parameter type
933 // for validity.
934 if (!NTTPType.isNull())
935 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
936 NTTP->getLocation());
937
938 if (NTTPType.isNull()) {
939 Invalid = true;
940 break;
941 }
942 }
943
Douglas Gregor40808ce2009-03-09 23:48:35 +0000944 switch (Arg.getKind()) {
945 case TemplateArgument::Expression: {
946 Expr *E = Arg.getAsExpr();
947 if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted))
Douglas Gregorc15cb382009-02-09 23:23:08 +0000948 Invalid = true;
Douglas Gregor40808ce2009-03-09 23:48:35 +0000949 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000950 }
951
Douglas Gregor40808ce2009-03-09 23:48:35 +0000952 case TemplateArgument::Declaration:
953 case TemplateArgument::Integral:
954 // We've already checked this template argument, so just copy
955 // it to the list of converted arguments.
956 Converted.push_back(Arg);
957 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000958
Douglas Gregor40808ce2009-03-09 23:48:35 +0000959 case TemplateArgument::Type:
960 // We have a non-type template parameter but the template
961 // argument is a type.
962
963 // C++ [temp.arg]p2:
964 // In a template-argument, an ambiguity between a type-id and
965 // an expression is resolved to a type-id, regardless of the
966 // form of the corresponding template-parameter.
967 //
968 // We warn specifically about this case, since it can be rather
969 // confusing for users.
970 if (Arg.getAsType()->isFunctionType())
971 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
972 << Arg.getAsType();
973 else
974 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
975 Diag((*Param)->getLocation(), diag::note_template_param_here);
976 Invalid = true;
977 }
Douglas Gregorc15cb382009-02-09 23:23:08 +0000978 } else {
979 // Check template template parameters.
980 TemplateTemplateParmDecl *TempParm
981 = cast<TemplateTemplateParmDecl>(*Param);
982
Douglas Gregor40808ce2009-03-09 23:48:35 +0000983 switch (Arg.getKind()) {
984 case TemplateArgument::Expression: {
985 Expr *ArgExpr = Arg.getAsExpr();
986 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
987 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
988 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
989 Invalid = true;
990
991 // Add the converted template argument.
992 // FIXME: Need the "canonical" template declaration!
993 Converted.push_back(
994 TemplateArgument(Arg.getLocation(),
995 cast<DeclRefExpr>(ArgExpr)->getDecl()));
996 continue;
997 }
998 }
999 // fall through
1000
1001 case TemplateArgument::Type: {
1002 // We have a template template parameter but the template
1003 // argument does not refer to a template.
1004 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1005 Invalid = true;
1006 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001007 }
1008
Douglas Gregor40808ce2009-03-09 23:48:35 +00001009 case TemplateArgument::Declaration:
1010 // We've already checked this template argument, so just copy
1011 // it to the list of converted arguments.
1012 Converted.push_back(Arg);
1013 break;
1014
1015 case TemplateArgument::Integral:
1016 assert(false && "Integral argument with template template parameter");
1017 break;
1018 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001019 }
1020 }
1021
1022 return Invalid;
1023}
1024
1025/// \brief Check a template argument against its corresponding
1026/// template type parameter.
1027///
1028/// This routine implements the semantics of C++ [temp.arg.type]. It
1029/// returns true if an error occurred, and false otherwise.
1030bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1031 QualType Arg, SourceLocation ArgLoc) {
1032 // C++ [temp.arg.type]p2:
1033 // A local type, a type with no linkage, an unnamed type or a type
1034 // compounded from any of these types shall not be used as a
1035 // template-argument for a template type-parameter.
1036 //
1037 // FIXME: Perform the recursive and no-linkage type checks.
1038 const TagType *Tag = 0;
1039 if (const EnumType *EnumT = Arg->getAsEnumType())
1040 Tag = EnumT;
1041 else if (const RecordType *RecordT = Arg->getAsRecordType())
1042 Tag = RecordT;
1043 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1044 return Diag(ArgLoc, diag::err_template_arg_local_type)
1045 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001046 else if (Tag && !Tag->getDecl()->getDeclName() &&
1047 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001048 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1049 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1050 return true;
1051 }
1052
1053 return false;
1054}
1055
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001056/// \brief Checks whether the given template argument is the address
1057/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001058bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1059 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001060 bool Invalid = false;
1061
1062 // See through any implicit casts we added to fix the type.
1063 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1064 Arg = Cast->getSubExpr();
1065
1066 // C++ [temp.arg.nontype]p1:
1067 //
1068 // A template-argument for a non-type, non-template
1069 // template-parameter shall be one of: [...]
1070 //
1071 // -- the address of an object or function with external
1072 // linkage, including function templates and function
1073 // template-ids but excluding non-static class members,
1074 // expressed as & id-expression where the & is optional if
1075 // the name refers to a function or array, or if the
1076 // corresponding template-parameter is a reference; or
1077 DeclRefExpr *DRE = 0;
1078
1079 // Ignore (and complain about) any excess parentheses.
1080 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1081 if (!Invalid) {
1082 Diag(Arg->getSourceRange().getBegin(),
1083 diag::err_template_arg_extra_parens)
1084 << Arg->getSourceRange();
1085 Invalid = true;
1086 }
1087
1088 Arg = Parens->getSubExpr();
1089 }
1090
1091 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1092 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1093 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1094 } else
1095 DRE = dyn_cast<DeclRefExpr>(Arg);
1096
1097 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1098 return Diag(Arg->getSourceRange().getBegin(),
1099 diag::err_template_arg_not_object_or_func_form)
1100 << Arg->getSourceRange();
1101
1102 // Cannot refer to non-static data members
1103 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1104 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1105 << Field << Arg->getSourceRange();
1106
1107 // Cannot refer to non-static member functions
1108 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1109 if (!Method->isStatic())
1110 return Diag(Arg->getSourceRange().getBegin(),
1111 diag::err_template_arg_method)
1112 << Method << Arg->getSourceRange();
1113
1114 // Functions must have external linkage.
1115 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1116 if (Func->getStorageClass() == FunctionDecl::Static) {
1117 Diag(Arg->getSourceRange().getBegin(),
1118 diag::err_template_arg_function_not_extern)
1119 << Func << Arg->getSourceRange();
1120 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1121 << true;
1122 return true;
1123 }
1124
1125 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001126 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001127 return Invalid;
1128 }
1129
1130 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1131 if (!Var->hasGlobalStorage()) {
1132 Diag(Arg->getSourceRange().getBegin(),
1133 diag::err_template_arg_object_not_extern)
1134 << Var << Arg->getSourceRange();
1135 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1136 << true;
1137 return true;
1138 }
1139
1140 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001141 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001142 return Invalid;
1143 }
1144
1145 // We found something else, but we don't know specifically what it is.
1146 Diag(Arg->getSourceRange().getBegin(),
1147 diag::err_template_arg_not_object_or_func)
1148 << Arg->getSourceRange();
1149 Diag(DRE->getDecl()->getLocation(),
1150 diag::note_template_arg_refers_here);
1151 return true;
1152}
1153
1154/// \brief Checks whether the given template argument is a pointer to
1155/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001156bool
1157Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001158 bool Invalid = false;
1159
1160 // See through any implicit casts we added to fix the type.
1161 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1162 Arg = Cast->getSubExpr();
1163
1164 // C++ [temp.arg.nontype]p1:
1165 //
1166 // A template-argument for a non-type, non-template
1167 // template-parameter shall be one of: [...]
1168 //
1169 // -- a pointer to member expressed as described in 5.3.1.
1170 QualifiedDeclRefExpr *DRE = 0;
1171
1172 // Ignore (and complain about) any excess parentheses.
1173 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1174 if (!Invalid) {
1175 Diag(Arg->getSourceRange().getBegin(),
1176 diag::err_template_arg_extra_parens)
1177 << Arg->getSourceRange();
1178 Invalid = true;
1179 }
1180
1181 Arg = Parens->getSubExpr();
1182 }
1183
1184 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1185 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1186 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1187
1188 if (!DRE)
1189 return Diag(Arg->getSourceRange().getBegin(),
1190 diag::err_template_arg_not_pointer_to_member_form)
1191 << Arg->getSourceRange();
1192
1193 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1194 assert((isa<FieldDecl>(DRE->getDecl()) ||
1195 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1196 "Only non-static member pointers can make it here");
1197
1198 // Okay: this is the address of a non-static member, and therefore
1199 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001200 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001201 return Invalid;
1202 }
1203
1204 // We found something else, but we don't know specifically what it is.
1205 Diag(Arg->getSourceRange().getBegin(),
1206 diag::err_template_arg_not_pointer_to_member_form)
1207 << Arg->getSourceRange();
1208 Diag(DRE->getDecl()->getLocation(),
1209 diag::note_template_arg_refers_here);
1210 return true;
1211}
1212
Douglas Gregorc15cb382009-02-09 23:23:08 +00001213/// \brief Check a template argument against its corresponding
1214/// non-type template parameter.
1215///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001216/// This routine implements the semantics of C++ [temp.arg.nontype].
1217/// It returns true if an error occurred, and false otherwise. \p
1218/// InstantiatedParamType is the type of the non-type template
1219/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001220///
1221/// If Converted is non-NULL and no errors occur, the value
1222/// of this argument will be added to the end of the Converted vector.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001223bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001224 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001225 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001226 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1227
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001228 // If either the parameter has a dependent type or the argument is
1229 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001230 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001231 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1232 // FIXME: Produce a cloned, canonical expression?
1233 Converted->push_back(TemplateArgument(Arg));
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001234 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001235 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001236
1237 // C++ [temp.arg.nontype]p5:
1238 // The following conversions are performed on each expression used
1239 // as a non-type template-argument. If a non-type
1240 // template-argument cannot be converted to the type of the
1241 // corresponding template-parameter then the program is
1242 // ill-formed.
1243 //
1244 // -- for a non-type template-parameter of integral or
1245 // enumeration type, integral promotions (4.5) and integral
1246 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001247 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001248 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001249 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001250 // C++ [temp.arg.nontype]p1:
1251 // A template-argument for a non-type, non-template
1252 // template-parameter shall be one of:
1253 //
1254 // -- an integral constant-expression of integral or enumeration
1255 // type; or
1256 // -- the name of a non-type template-parameter; or
1257 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001258 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001259 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1260 Diag(Arg->getSourceRange().getBegin(),
1261 diag::err_template_arg_not_integral_or_enumeral)
1262 << ArgType << Arg->getSourceRange();
1263 Diag(Param->getLocation(), diag::note_template_param_here);
1264 return true;
1265 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001266 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001267 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1268 << ArgType << Arg->getSourceRange();
1269 return true;
1270 }
1271
1272 // FIXME: We need some way to more easily get the unqualified form
1273 // of the types without going all the way to the
1274 // canonical type.
1275 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1276 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1277 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1278 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1279
1280 // Try to convert the argument to the parameter's type.
1281 if (ParamType == ArgType) {
1282 // Okay: no conversion necessary
1283 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1284 !ParamType->isEnumeralType()) {
1285 // This is an integral promotion or conversion.
1286 ImpCastExprToType(Arg, ParamType);
1287 } else {
1288 // We can't perform this conversion.
1289 Diag(Arg->getSourceRange().getBegin(),
1290 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001291 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001292 Diag(Param->getLocation(), diag::note_template_param_here);
1293 return true;
1294 }
1295
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001296 QualType IntegerType = Context.getCanonicalType(ParamType);
1297 if (const EnumType *Enum = IntegerType->getAsEnumType())
1298 IntegerType = Enum->getDecl()->getIntegerType();
1299
1300 if (!Arg->isValueDependent()) {
1301 // Check that an unsigned parameter does not receive a negative
1302 // value.
1303 if (IntegerType->isUnsignedIntegerType()
1304 && (Value.isSigned() && Value.isNegative())) {
1305 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1306 << Value.toString(10) << Param->getType()
1307 << Arg->getSourceRange();
1308 Diag(Param->getLocation(), diag::note_template_param_here);
1309 return true;
1310 }
1311
1312 // Check that we don't overflow the template parameter type.
1313 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1314 if (Value.getActiveBits() > AllowedBits) {
1315 Diag(Arg->getSourceRange().getBegin(),
1316 diag::err_template_arg_too_large)
1317 << Value.toString(10) << Param->getType()
1318 << Arg->getSourceRange();
1319 Diag(Param->getLocation(), diag::note_template_param_here);
1320 return true;
1321 }
1322
1323 if (Value.getBitWidth() != AllowedBits)
1324 Value.extOrTrunc(AllowedBits);
1325 Value.setIsSigned(IntegerType->isSignedIntegerType());
1326 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001327
1328 if (Converted) {
1329 // Add the value of this argument to the list of converted
1330 // arguments. We use the bitwidth and signedness of the template
1331 // parameter.
Douglas Gregorba498172009-03-13 21:01:28 +00001332 if (Arg->isValueDependent()) {
1333 // The argument is value-dependent. Create a new
1334 // TemplateArgument with the converted expression.
1335 Converted->push_back(TemplateArgument(Arg));
1336 return false;
1337 }
1338
Douglas Gregor5b0f7522009-03-14 00:03:48 +00001339 Converted->push_back(TemplateArgument(StartLoc, Value,
Douglas Gregorc971f862009-03-12 22:20:26 +00001340 Context.getCanonicalType(IntegerType)));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001341 }
1342
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001343 return false;
1344 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001345
Douglas Gregorb86b0572009-02-11 01:18:59 +00001346 // Handle pointer-to-function, reference-to-function, and
1347 // pointer-to-member-function all in (roughly) the same way.
1348 if (// -- For a non-type template-parameter of type pointer to
1349 // function, only the function-to-pointer conversion (4.3) is
1350 // applied. If the template-argument represents a set of
1351 // overloaded functions (or a pointer to such), the matching
1352 // function is selected from the set (13.4).
1353 (ParamType->isPointerType() &&
1354 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1355 // -- For a non-type template-parameter of type reference to
1356 // function, no conversions apply. If the template-argument
1357 // represents a set of overloaded functions, the matching
1358 // function is selected from the set (13.4).
1359 (ParamType->isReferenceType() &&
1360 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1361 // -- For a non-type template-parameter of type pointer to
1362 // member function, no conversions apply. If the
1363 // template-argument represents a set of overloaded member
1364 // functions, the matching member function is selected from
1365 // the set (13.4).
1366 (ParamType->isMemberPointerType() &&
1367 ParamType->getAsMemberPointerType()->getPointeeType()
1368 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001369 if (Context.hasSameUnqualifiedType(ArgType,
1370 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001371 // We don't have to do anything: the types already match.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001372 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001373 ArgType = Context.getPointerType(ArgType);
1374 ImpCastExprToType(Arg, ArgType);
1375 } else if (FunctionDecl *Fn
1376 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001377 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1378 return true;
1379
Douglas Gregora35284b2009-02-11 00:19:33 +00001380 FixOverloadedFunctionReference(Arg, Fn);
1381 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001382 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001383 ArgType = Context.getPointerType(Arg->getType());
1384 ImpCastExprToType(Arg, ArgType);
1385 }
1386 }
1387
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001388 if (!Context.hasSameUnqualifiedType(ArgType,
1389 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001390 // We can't perform this conversion.
1391 Diag(Arg->getSourceRange().getBegin(),
1392 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001393 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001394 Diag(Param->getLocation(), diag::note_template_param_here);
1395 return true;
1396 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001397
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001398 if (ParamType->isMemberPointerType()) {
1399 NamedDecl *Member = 0;
1400 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1401 return true;
1402
1403 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001404 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001405
1406 return false;
1407 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001408
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001409 NamedDecl *Entity = 0;
1410 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1411 return true;
1412
1413 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001414 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001415 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001416 }
1417
Chris Lattnerfe90de72009-02-20 21:37:53 +00001418 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001419 // -- for a non-type template-parameter of type pointer to
1420 // object, qualification conversions (4.4) and the
1421 // array-to-pointer conversion (4.2) are applied.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001422 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001423 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001424
Douglas Gregorb86b0572009-02-11 01:18:59 +00001425 if (ArgType->isArrayType()) {
1426 ArgType = Context.getArrayDecayedType(ArgType);
1427 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001428 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001429
1430 if (IsQualificationConversion(ArgType, ParamType)) {
1431 ArgType = ParamType;
1432 ImpCastExprToType(Arg, ParamType);
1433 }
1434
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001435 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001436 // We can't perform this conversion.
1437 Diag(Arg->getSourceRange().getBegin(),
1438 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001439 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001440 Diag(Param->getLocation(), diag::note_template_param_here);
1441 return true;
1442 }
1443
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001444 NamedDecl *Entity = 0;
1445 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1446 return true;
1447
1448 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001449 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001450
1451 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001452 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001453
1454 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1455 // -- For a non-type template-parameter of type reference to
1456 // object, no conversions apply. The type referred to by the
1457 // reference may be more cv-qualified than the (otherwise
1458 // identical) type of the template-argument. The
1459 // template-parameter is bound directly to the
1460 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001461 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001462 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001463
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001464 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001465 Diag(Arg->getSourceRange().getBegin(),
1466 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001467 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001468 << Arg->getSourceRange();
1469 Diag(Param->getLocation(), diag::note_template_param_here);
1470 return true;
1471 }
1472
1473 unsigned ParamQuals
1474 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1475 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1476
1477 if ((ParamQuals | ArgQuals) != ParamQuals) {
1478 Diag(Arg->getSourceRange().getBegin(),
1479 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001480 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001481 << Arg->getSourceRange();
1482 Diag(Param->getLocation(), diag::note_template_param_here);
1483 return true;
1484 }
1485
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001486 NamedDecl *Entity = 0;
1487 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1488 return true;
1489
1490 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001491 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001492
1493 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001494 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001495
1496 // -- For a non-type template-parameter of type pointer to data
1497 // member, qualification conversions (4.4) are applied.
1498 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1499
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001500 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001501 // Types match exactly: nothing more to do here.
1502 } else if (IsQualificationConversion(ArgType, ParamType)) {
1503 ImpCastExprToType(Arg, ParamType);
1504 } else {
1505 // We can't perform this conversion.
1506 Diag(Arg->getSourceRange().getBegin(),
1507 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001508 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001509 Diag(Param->getLocation(), diag::note_template_param_here);
1510 return true;
1511 }
1512
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001513 NamedDecl *Member = 0;
1514 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1515 return true;
1516
1517 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001518 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001519
1520 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001521}
1522
1523/// \brief Check a template argument against its corresponding
1524/// template template parameter.
1525///
1526/// This routine implements the semantics of C++ [temp.arg.template].
1527/// It returns true if an error occurred, and false otherwise.
1528bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1529 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001530 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1531 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1532
1533 // C++ [temp.arg.template]p1:
1534 // A template-argument for a template template-parameter shall be
1535 // the name of a class template, expressed as id-expression. Only
1536 // primary class templates are considered when matching the
1537 // template template argument with the corresponding parameter;
1538 // partial specializations are not considered even if their
1539 // parameter lists match that of the template template parameter.
1540 if (!isa<ClassTemplateDecl>(Template)) {
1541 assert(isa<FunctionTemplateDecl>(Template) &&
1542 "Only function templates are possible here");
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001543 Diag(Arg->getSourceRange().getBegin(),
1544 diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001545 << Template;
1546 }
1547
1548 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1549 Param->getTemplateParameters(),
1550 true, true,
1551 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001552}
1553
Douglas Gregorddc29e12009-02-06 22:42:48 +00001554/// \brief Determine whether the given template parameter lists are
1555/// equivalent.
1556///
1557/// \param New The new template parameter list, typically written in the
1558/// source code as part of a new template declaration.
1559///
1560/// \param Old The old template parameter list, typically found via
1561/// name lookup of the template declared with this template parameter
1562/// list.
1563///
1564/// \param Complain If true, this routine will produce a diagnostic if
1565/// the template parameter lists are not equivalent.
1566///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001567/// \param IsTemplateTemplateParm If true, this routine is being
1568/// called to compare the template parameter lists of a template
1569/// template parameter.
1570///
1571/// \param TemplateArgLoc If this source location is valid, then we
1572/// are actually checking the template parameter list of a template
1573/// argument (New) against the template parameter list of its
1574/// corresponding template template parameter (Old). We produce
1575/// slightly different diagnostics in this scenario.
1576///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001577/// \returns True if the template parameter lists are equal, false
1578/// otherwise.
1579bool
1580Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1581 TemplateParameterList *Old,
1582 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001583 bool IsTemplateTemplateParm,
1584 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001585 if (Old->size() != New->size()) {
1586 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001587 unsigned NextDiag = diag::err_template_param_list_different_arity;
1588 if (TemplateArgLoc.isValid()) {
1589 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1590 NextDiag = diag::note_template_param_list_different_arity;
1591 }
1592 Diag(New->getTemplateLoc(), NextDiag)
1593 << (New->size() > Old->size())
1594 << IsTemplateTemplateParm
1595 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001596 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1597 << IsTemplateTemplateParm
1598 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1599 }
1600
1601 return false;
1602 }
1603
1604 for (TemplateParameterList::iterator OldParm = Old->begin(),
1605 OldParmEnd = Old->end(), NewParm = New->begin();
1606 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1607 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001608 unsigned NextDiag = diag::err_template_param_different_kind;
1609 if (TemplateArgLoc.isValid()) {
1610 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1611 NextDiag = diag::note_template_param_different_kind;
1612 }
1613 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001614 << IsTemplateTemplateParm;
1615 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1616 << IsTemplateTemplateParm;
1617 return false;
1618 }
1619
1620 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1621 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00001622 // know we're at the same index).
1623#if 0
1624 // FIXME: Enable this code in debug mode *after* we properly go
1625 // through and "instantiate" the template parameter lists of
1626 // template template parameters. It's only after this
1627 // instantiation that (1) any dependent types within the
1628 // template parameter list of the template template parameter
1629 // can be checked, and (2) the template type parameter depths
1630 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00001631 QualType OldParmType
1632 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1633 QualType NewParmType
1634 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1635 assert(Context.getCanonicalType(OldParmType) ==
1636 Context.getCanonicalType(NewParmType) &&
1637 "type parameter mismatch?");
1638#endif
1639 } else if (NonTypeTemplateParmDecl *OldNTTP
1640 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1641 // The types of non-type template parameters must agree.
1642 NonTypeTemplateParmDecl *NewNTTP
1643 = cast<NonTypeTemplateParmDecl>(*NewParm);
1644 if (Context.getCanonicalType(OldNTTP->getType()) !=
1645 Context.getCanonicalType(NewNTTP->getType())) {
1646 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001647 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1648 if (TemplateArgLoc.isValid()) {
1649 Diag(TemplateArgLoc,
1650 diag::err_template_arg_template_params_mismatch);
1651 NextDiag = diag::note_template_nontype_parm_different_type;
1652 }
1653 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001654 << NewNTTP->getType()
1655 << IsTemplateTemplateParm;
1656 Diag(OldNTTP->getLocation(),
1657 diag::note_template_nontype_parm_prev_declaration)
1658 << OldNTTP->getType();
1659 }
1660 return false;
1661 }
1662 } else {
1663 // The template parameter lists of template template
1664 // parameters must agree.
1665 // FIXME: Could we perform a faster "type" comparison here?
1666 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1667 "Only template template parameters handled here");
1668 TemplateTemplateParmDecl *OldTTP
1669 = cast<TemplateTemplateParmDecl>(*OldParm);
1670 TemplateTemplateParmDecl *NewTTP
1671 = cast<TemplateTemplateParmDecl>(*NewParm);
1672 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1673 OldTTP->getTemplateParameters(),
1674 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001675 /*IsTemplateTemplateParm=*/true,
1676 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00001677 return false;
1678 }
1679 }
1680
1681 return true;
1682}
1683
1684/// \brief Check whether a template can be declared within this scope.
1685///
1686/// If the template declaration is valid in this scope, returns
1687/// false. Otherwise, issues a diagnostic and returns true.
1688bool
1689Sema::CheckTemplateDeclScope(Scope *S,
1690 MultiTemplateParamsArg &TemplateParameterLists) {
1691 assert(TemplateParameterLists.size() > 0 && "Not a template");
1692
1693 // Find the nearest enclosing declaration scope.
1694 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1695 (S->getFlags() & Scope::TemplateParamScope) != 0)
1696 S = S->getParent();
1697
1698 TemplateParameterList *TemplateParams =
1699 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1700 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1701 SourceRange TemplateRange
1702 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1703
1704 // C++ [temp]p2:
1705 // A template-declaration can appear only as a namespace scope or
1706 // class scope declaration.
1707 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1708 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1709 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1710 return Diag(TemplateLoc, diag::err_template_linkage)
1711 << TemplateRange;
1712
1713 Ctx = Ctx->getParent();
1714 }
1715
1716 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1717 return false;
1718
1719 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1720 << TemplateRange;
1721}
Douglas Gregorcc636682009-02-17 23:15:12 +00001722
Douglas Gregor88b70942009-02-25 22:02:03 +00001723/// \brief Check whether a class template specialization in the
1724/// current context is well-formed.
1725///
1726/// This routine determines whether a class template specialization
1727/// can be declared in the current context (C++ [temp.expl.spec]p2)
1728/// and emits appropriate diagnostics if there was an error. It
1729/// returns true if there was an error that we cannot recover from,
1730/// and false otherwise.
1731bool
1732Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1733 ClassTemplateSpecializationDecl *PrevDecl,
1734 SourceLocation TemplateNameLoc,
1735 SourceRange ScopeSpecifierRange) {
1736 // C++ [temp.expl.spec]p2:
1737 // An explicit specialization shall be declared in the namespace
1738 // of which the template is a member, or, for member templates, in
1739 // the namespace of which the enclosing class or enclosing class
1740 // template is a member. An explicit specialization of a member
1741 // function, member class or static data member of a class
1742 // template shall be declared in the namespace of which the class
1743 // template is a member. Such a declaration may also be a
1744 // definition. If the declaration is not a definition, the
1745 // specialization may be defined later in the name- space in which
1746 // the explicit specialization was declared, or in a namespace
1747 // that encloses the one in which the explicit specialization was
1748 // declared.
1749 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1750 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1751 << ClassTemplate;
1752 return true;
1753 }
1754
1755 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1756 DeclContext *TemplateContext
1757 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1758 if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1759 // There is no prior declaration of this entity, so this
1760 // specialization must be in the same context as the template
1761 // itself.
1762 if (DC != TemplateContext) {
1763 if (isa<TranslationUnitDecl>(TemplateContext))
1764 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1765 << ClassTemplate << ScopeSpecifierRange;
1766 else if (isa<NamespaceDecl>(TemplateContext))
1767 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1768 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1769 << ScopeSpecifierRange;
1770
1771 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1772 }
1773
1774 return false;
1775 }
1776
1777 // We have a previous declaration of this entity. Make sure that
1778 // this redeclaration (or definition) occurs in an enclosing namespace.
1779 if (!CurContext->Encloses(TemplateContext)) {
1780 if (isa<TranslationUnitDecl>(TemplateContext))
1781 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1782 << ClassTemplate << ScopeSpecifierRange;
1783 else if (isa<NamespaceDecl>(TemplateContext))
1784 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1785 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1786 << ScopeSpecifierRange;
1787
1788 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1789 }
1790
1791 return false;
1792}
1793
Douglas Gregor212e81c2009-03-25 00:13:59 +00001794Sema::DeclResult
Douglas Gregorcc636682009-02-17 23:15:12 +00001795Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1796 SourceLocation KWLoc,
1797 const CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001798 DeclPtrTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00001799 SourceLocation TemplateNameLoc,
1800 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001801 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00001802 SourceLocation *TemplateArgLocs,
1803 SourceLocation RAngleLoc,
1804 AttributeList *Attr,
1805 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00001806 // Find the class template we're specializing
1807 ClassTemplateDecl *ClassTemplate
Chris Lattnerb28317a2009-03-28 19:18:32 +00001808 = dyn_cast_or_null<ClassTemplateDecl>(TemplateD.getAs<Decl>());
Douglas Gregorcc636682009-02-17 23:15:12 +00001809 if (!ClassTemplate)
Douglas Gregor212e81c2009-03-25 00:13:59 +00001810 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00001811
Douglas Gregor88b70942009-02-25 22:02:03 +00001812 // Check the validity of the template headers that introduce this
1813 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00001814 // FIXME: Once we have member templates, we'll need to check
1815 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
1816 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001817 if (TemplateParameterLists.size() == 0)
1818 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00001819 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001820 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00001821 TemplateParameterList *TemplateParams
1822 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattnerb28317a2009-03-28 19:18:32 +00001823 if (TemplateParameterLists.size() > 1) {
1824 Diag(TemplateParams->getTemplateLoc(),
1825 diag::err_template_spec_extra_headers);
1826 return true;
1827 }
Douglas Gregor88b70942009-02-25 22:02:03 +00001828
Chris Lattnerb28317a2009-03-28 19:18:32 +00001829 if (TemplateParams->size() > 0) {
Douglas Gregor88b70942009-02-25 22:02:03 +00001830 // FIXME: No support for class template partial specialization.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001831 Diag(TemplateParams->getTemplateLoc(), diag::unsup_template_partial_spec);
1832 return true;
1833 }
Douglas Gregor88b70942009-02-25 22:02:03 +00001834 }
1835
Douglas Gregorcc636682009-02-17 23:15:12 +00001836 // Check that the specialization uses the same tag kind as the
1837 // original template.
1838 TagDecl::TagKind Kind;
1839 switch (TagSpec) {
1840 default: assert(0 && "Unknown tag type!");
1841 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1842 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1843 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1844 }
1845 if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
1846 Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate;
1847 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1848 diag::note_previous_use);
1849 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1850 }
1851
Douglas Gregor40808ce2009-03-09 23:48:35 +00001852 // Translate the parser's template argument list in our AST format.
1853 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1854 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1855
Douglas Gregorcc636682009-02-17 23:15:12 +00001856 // Check that the template argument list is well-formed for this
1857 // template.
1858 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1859 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001860 &TemplateArgs[0], TemplateArgs.size(),
1861 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregor212e81c2009-03-25 00:13:59 +00001862 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00001863
1864 assert((ConvertedTemplateArgs.size() ==
1865 ClassTemplate->getTemplateParameters()->size()) &&
1866 "Converted template argument list is too short!");
1867
1868 // Find the class template specialization declaration that
1869 // corresponds to these arguments.
1870 llvm::FoldingSetNodeID ID;
1871 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
1872 ConvertedTemplateArgs.size());
1873 void *InsertPos = 0;
1874 ClassTemplateSpecializationDecl *PrevDecl
1875 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1876
1877 ClassTemplateSpecializationDecl *Specialization = 0;
1878
Douglas Gregor88b70942009-02-25 22:02:03 +00001879 // Check whether we can declare a class template specialization in
1880 // the current scope.
1881 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
1882 TemplateNameLoc,
1883 SS.getRange()))
Douglas Gregor212e81c2009-03-25 00:13:59 +00001884 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00001885
Douglas Gregorcc636682009-02-17 23:15:12 +00001886 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1887 // Since the only prior class template specialization with these
1888 // arguments was referenced but not declared, reuse that
1889 // declaration node as our own, updating its source location to
1890 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00001891 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00001892 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00001893 PrevDecl = 0;
1894 } else {
1895 // Create a new class template specialization declaration node for
1896 // this explicit specialization.
1897 Specialization
1898 = ClassTemplateSpecializationDecl::Create(Context,
1899 ClassTemplate->getDeclContext(),
1900 TemplateNameLoc,
1901 ClassTemplate,
1902 &ConvertedTemplateArgs[0],
1903 ConvertedTemplateArgs.size(),
1904 PrevDecl);
1905
1906 if (PrevDecl) {
1907 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
1908 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
1909 } else {
1910 ClassTemplate->getSpecializations().InsertNode(Specialization,
1911 InsertPos);
1912 }
1913 }
1914
1915 // Note that this is an explicit specialization.
1916 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
1917
1918 // Check that this isn't a redefinition of this specialization.
1919 if (TK == TK_Definition) {
1920 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
1921 // FIXME: Should also handle explicit specialization after
1922 // implicit instantiation with a special diagnostic.
1923 SourceRange Range(TemplateNameLoc, RAngleLoc);
1924 Diag(TemplateNameLoc, diag::err_redefinition)
1925 << Specialization << Range;
1926 Diag(Def->getLocation(), diag::note_previous_definition);
1927 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00001928 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00001929 }
1930 }
1931
Douglas Gregorfc705b82009-02-26 22:19:44 +00001932 // Build the fully-sugared type for this class template
1933 // specialization as the user wrote in the specialization
1934 // itself. This means that we'll pretty-print the type retrieved
1935 // from the specialization's declaration the way that the user
1936 // actually wrote the specialization, rather than formatting the
1937 // name based on the "canonical" representation used to store the
1938 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00001939 QualType WrittenTy
1940 = Context.getClassTemplateSpecializationType(ClassTemplate,
1941 &TemplateArgs[0],
1942 TemplateArgs.size(),
1943 Context.getTypeDeclType(Specialization));
1944 Specialization->setTypeAsWritten(getQualifiedNameType(SS, WrittenTy));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001945 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00001946
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00001947 // C++ [temp.expl.spec]p9:
1948 // A template explicit specialization is in the scope of the
1949 // namespace in which the template was defined.
1950 //
1951 // We actually implement this paragraph where we set the semantic
1952 // context (in the creation of the ClassTemplateSpecializationDecl),
1953 // but we also maintain the lexical context where the actual
1954 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00001955 Specialization->setLexicalDeclContext(CurContext);
1956
1957 // We may be starting the definition of this specialization.
1958 if (TK == TK_Definition)
1959 Specialization->startDefinition();
1960
1961 // Add the specialization into its lexical context, so that it can
1962 // be seen when iterating through the list of declarations in that
1963 // context. However, specializations are not found by name lookup.
1964 CurContext->addDecl(Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00001965 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00001966}
Douglas Gregord57959a2009-03-27 23:10:48 +00001967
1968Sema::TypeResult
1969Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
1970 const IdentifierInfo &II, SourceLocation IdLoc) {
1971 NestedNameSpecifier *NNS
1972 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1973 if (!NNS)
1974 return true;
1975
1976 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord57959a2009-03-27 23:10:48 +00001977 return T.getAsOpaquePtr();
1978}
1979
1980/// \brief Build the type that describes a C++ typename specifier,
1981/// e.g., "typename T::type".
1982QualType
1983Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
1984 SourceRange Range) {
1985 if (NNS->isDependent()) // FIXME: member of the current instantiation!
1986 return Context.getTypenameType(NNS, &II);
1987
1988 CXXScopeSpec SS;
1989 SS.setScopeRep(NNS);
1990 SS.setRange(Range);
1991 if (RequireCompleteDeclContext(SS))
1992 return QualType();
1993
1994 DeclContext *Ctx = computeDeclContext(SS);
1995 assert(Ctx && "No declaration context?");
1996
1997 DeclarationName Name(&II);
1998 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
1999 false);
2000 unsigned DiagID = 0;
2001 Decl *Referenced = 0;
2002 switch (Result.getKind()) {
2003 case LookupResult::NotFound:
2004 if (Ctx->isTranslationUnit())
2005 DiagID = diag::err_typename_nested_not_found_global;
2006 else
2007 DiagID = diag::err_typename_nested_not_found;
2008 break;
2009
2010 case LookupResult::Found:
2011 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2012 // We found a type. Build a QualifiedNameType, since the
2013 // typename-specifier was just sugar. FIXME: Tell
2014 // QualifiedNameType that it has a "typename" prefix.
2015 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2016 }
2017
2018 DiagID = diag::err_typename_nested_not_type;
2019 Referenced = Result.getAsDecl();
2020 break;
2021
2022 case LookupResult::FoundOverloaded:
2023 DiagID = diag::err_typename_nested_not_type;
2024 Referenced = *Result.begin();
2025 break;
2026
2027 case LookupResult::AmbiguousBaseSubobjectTypes:
2028 case LookupResult::AmbiguousBaseSubobjects:
2029 case LookupResult::AmbiguousReference:
2030 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2031 return QualType();
2032 }
2033
2034 // If we get here, it's because name lookup did not find a
2035 // type. Emit an appropriate diagnostic and return an error.
2036 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2037 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2038 else
2039 Diag(Range.getEnd(), DiagID) << Range << Name;
2040 if (Referenced)
2041 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2042 << Name;
2043 return QualType();
2044}