blob: d08e268b6378b2edaa3bec10847b76d2a1bd50a5 [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 Gregorc45c2322009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregor7532dc62009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
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
Douglas Gregor7532dc62009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregor7532dc62009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregorbefc20e2009-03-26 00:10:35 +000046 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47 // C++ [temp.local]p1:
48 // Like normal (non-template) classes, class templates have an
49 // injected-class-name (Clause 9). The injected-class-name
50 // can be used with or without a template-argument-list. When
51 // it is used without a template-argument-list, it is
52 // equivalent to the injected-class-name followed by the
53 // template-parameters of the class template enclosed in
54 // <>. When it is used with a template-argument-list, it
55 // refers to the specified class template specialization,
56 // which could be the current specialization or another
57 // specialization.
58 if (Record->isInjectedClassName()) {
59 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
Douglas Gregor7532dc62009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregorc45c2322009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregorbefc20e2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregorc45c2322009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregorbefc20e2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregor55f6b142009-02-09 18:46:07 +000068 }
Douglas Gregoraaba5e32009-02-04 19:02:06 +000069
Douglas Gregor55f6b142009-02-09 18:46:07 +000070 // FIXME: What follows is a gross hack.
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000072 if (FD->getType()->isDependentType()) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000073 TemplateResult = TemplateTy::make(FD);
Douglas Gregor55f6b142009-02-09 18:46:07 +000074 return TNK_Function_template;
75 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000076 } else if (OverloadedFunctionDecl *Ovl
77 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
78 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
79 FEnd = Ovl->function_end();
80 F != FEnd; ++F) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000081 if ((*F)->getType()->isDependentType()) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000082 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor55f6b142009-02-09 18:46:07 +000083 return TNK_Function_template;
84 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000085 }
86 }
Douglas Gregor7532dc62009-03-30 22:58:21 +000087
88 if (TNK != TNK_Non_template) {
89 if (SS && SS->isSet() && !SS->isInvalid()) {
90 NestedNameSpecifier *Qualifier
91 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
92 TemplateResult
93 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
94 false,
95 Template));
96 } else
97 TemplateResult = TemplateTy::make(TemplateName(Template));
98 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000099 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000100 return TNK;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000101}
102
Douglas Gregor72c3f312008-12-05 18:15:24 +0000103/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
104/// that the template parameter 'PrevDecl' is being shadowed by a new
105/// declaration at location Loc. Returns true to indicate that this is
106/// an error, and false otherwise.
107bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000108 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000109
110 // Microsoft Visual C++ permits template parameters to be shadowed.
111 if (getLangOptions().Microsoft)
112 return false;
113
114 // C++ [temp.local]p4:
115 // A template-parameter shall not be redeclared within its
116 // scope (including nested scopes).
117 Diag(Loc, diag::err_template_param_shadow)
118 << cast<NamedDecl>(PrevDecl)->getDeclName();
119 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
120 return true;
121}
122
Douglas Gregor2943aed2009-03-03 04:44:36 +0000123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000124/// the parameter D to reference the templated declaration and return a pointer
125/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000126TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
127 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
128 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000129 return Temp;
130 }
131 return 0;
132}
133
Douglas Gregor72c3f312008-12-05 18:15:24 +0000134/// ActOnTypeParameter - Called when a C++ template type parameter
135/// (e.g., "typename T") has been parsed. Typename specifies whether
136/// the keyword "typename" was used to declare the type parameter
137/// (otherwise, "class" was used), and KeyLoc is the location of the
138/// "class" or "typename" keyword. ParamName is the name of the
139/// parameter (NULL indicates an unnamed template parameter) and
140/// ParamName is the location of the parameter name (if any).
141/// If the type parameter has a default argument, it will be added
142/// later via ActOnTypeParameterDefault.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000143Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename,
144 SourceLocation KeyLoc,
145 IdentifierInfo *ParamName,
146 SourceLocation ParamNameLoc,
147 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000148 assert(S->isTemplateParamScope() &&
149 "Template type parameter not in template parameter scope!");
150 bool Invalid = false;
151
152 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000153 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000154 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000155 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
156 PrevDecl);
157 }
158
Douglas Gregorddc29e12009-02-06 22:42:48 +0000159 SourceLocation Loc = ParamNameLoc;
160 if (!ParamName)
161 Loc = KeyLoc;
162
Douglas Gregor72c3f312008-12-05 18:15:24 +0000163 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000164 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000165 Depth, Position, ParamName, Typename);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000166 if (Invalid)
167 Param->setInvalidDecl();
168
169 if (ParamName) {
170 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000171 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000172 IdResolver.AddDecl(Param);
173 }
174
Chris Lattnerb28317a2009-03-28 19:18:32 +0000175 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000176}
177
Douglas Gregord684b002009-02-10 19:49:53 +0000178/// ActOnTypeParameterDefault - Adds a default argument (the type
179/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000180void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000181 SourceLocation EqualLoc,
182 SourceLocation DefaultLoc,
183 TypeTy *DefaultT) {
184 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000185 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000186 QualType Default = QualType::getFromOpaquePtr(DefaultT);
187
188 // C++ [temp.param]p14:
189 // A template-parameter shall not be used in its own default argument.
190 // FIXME: Implement this check! Needs a recursive walk over the types.
191
192 // Check the template argument itself.
193 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
194 Parm->setInvalidDecl();
195 return;
196 }
197
198 Parm->setDefaultArgument(Default, DefaultLoc, false);
199}
200
Douglas Gregor2943aed2009-03-03 04:44:36 +0000201/// \brief Check that the type of a non-type template parameter is
202/// well-formed.
203///
204/// \returns the (possibly-promoted) parameter type if valid;
205/// otherwise, produces a diagnostic and returns a NULL type.
206QualType
207Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
208 // C++ [temp.param]p4:
209 //
210 // A non-type template-parameter shall have one of the following
211 // (optionally cv-qualified) types:
212 //
213 // -- integral or enumeration type,
214 if (T->isIntegralType() || T->isEnumeralType() ||
215 // -- pointer to object or pointer to function,
216 (T->isPointerType() &&
217 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
218 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
219 // -- reference to object or reference to function,
220 T->isReferenceType() ||
221 // -- pointer to member.
222 T->isMemberPointerType() ||
223 // If T is a dependent type, we can't do the check now, so we
224 // assume that it is well-formed.
225 T->isDependentType())
226 return T;
227 // C++ [temp.param]p8:
228 //
229 // A non-type template-parameter of type "array of T" or
230 // "function returning T" is adjusted to be of type "pointer to
231 // T" or "pointer to function returning T", respectively.
232 else if (T->isArrayType())
233 // FIXME: Keep the type prior to promotion?
234 return Context.getArrayDecayedType(T);
235 else if (T->isFunctionType())
236 // FIXME: Keep the type prior to promotion?
237 return Context.getPointerType(T);
238
239 Diag(Loc, diag::err_template_nontype_parm_bad_type)
240 << T;
241
242 return QualType();
243}
244
Douglas Gregor72c3f312008-12-05 18:15:24 +0000245/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
246/// template parameter (e.g., "int Size" in "template<int Size>
247/// class Array") has been parsed. S is the current scope and D is
248/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000249Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
250 unsigned Depth,
251 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000252 QualType T = GetTypeForDeclarator(D, S);
253
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000254 assert(S->isTemplateParamScope() &&
255 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000256 bool Invalid = false;
257
258 IdentifierInfo *ParamName = D.getIdentifier();
259 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000260 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000261 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000262 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000263 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000264 }
265
Douglas Gregor2943aed2009-03-03 04:44:36 +0000266 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000267 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000268 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000269 Invalid = true;
270 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000271
Douglas Gregor72c3f312008-12-05 18:15:24 +0000272 NonTypeTemplateParmDecl *Param
273 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000274 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000275 if (Invalid)
276 Param->setInvalidDecl();
277
278 if (D.getIdentifier()) {
279 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000280 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000281 IdResolver.AddDecl(Param);
282 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000283 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000284}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000285
Douglas Gregord684b002009-02-10 19:49:53 +0000286/// \brief Adds a default argument to the given non-type template
287/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000288void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000289 SourceLocation EqualLoc,
290 ExprArg DefaultE) {
291 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000292 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000293 Expr *Default = static_cast<Expr *>(DefaultE.get());
294
295 // C++ [temp.param]p14:
296 // A template-parameter shall not be used in its own default argument.
297 // FIXME: Implement this check! Needs a recursive walk over the types.
298
299 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000300 TemplateArgument Converted;
301 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
302 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000303 TemplateParm->setInvalidDecl();
304 return;
305 }
306
Anders Carlssone9146f22009-05-01 19:49:17 +0000307 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000308}
309
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000310
311/// ActOnTemplateTemplateParameter - Called when a C++ template template
312/// parameter (e.g. T in template <template <typename> class T> class array)
313/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000314Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
315 SourceLocation TmpLoc,
316 TemplateParamsTy *Params,
317 IdentifierInfo *Name,
318 SourceLocation NameLoc,
319 unsigned Depth,
320 unsigned Position)
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000321{
322 assert(S->isTemplateParamScope() &&
323 "Template template parameter not in template parameter scope!");
324
325 // Construct the parameter object.
326 TemplateTemplateParmDecl *Param =
327 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
328 Position, Name,
329 (TemplateParameterList*)Params);
330
331 // Make sure the parameter is valid.
332 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
333 // do anything yet. However, if the template parameter list or (eventual)
334 // default value is ever invalidated, that will propagate here.
335 bool Invalid = false;
336 if (Invalid) {
337 Param->setInvalidDecl();
338 }
339
340 // If the tt-param has a name, then link the identifier into the scope
341 // and lookup mechanisms.
342 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000343 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000344 IdResolver.AddDecl(Param);
345 }
346
Chris Lattnerb28317a2009-03-28 19:18:32 +0000347 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000348}
349
Douglas Gregord684b002009-02-10 19:49:53 +0000350/// \brief Adds a default argument to the given template template
351/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000352void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000353 SourceLocation EqualLoc,
354 ExprArg DefaultE) {
355 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000356 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000357
358 // Since a template-template parameter's default argument is an
359 // id-expression, it must be a DeclRefExpr.
360 DeclRefExpr *Default
361 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
362
363 // C++ [temp.param]p14:
364 // A template-parameter shall not be used in its own default argument.
365 // FIXME: Implement this check! Needs a recursive walk over the types.
366
367 // Check the well-formedness of the template argument.
368 if (!isa<TemplateDecl>(Default->getDecl())) {
369 Diag(Default->getSourceRange().getBegin(),
370 diag::err_template_arg_must_be_template)
371 << Default->getSourceRange();
372 TemplateParm->setInvalidDecl();
373 return;
374 }
375 if (CheckTemplateArgument(TemplateParm, Default)) {
376 TemplateParm->setInvalidDecl();
377 return;
378 }
379
380 DefaultE.release();
381 TemplateParm->setDefaultArgument(Default);
382}
383
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000384/// ActOnTemplateParameterList - Builds a TemplateParameterList that
385/// contains the template parameters in Params/NumParams.
386Sema::TemplateParamsTy *
387Sema::ActOnTemplateParameterList(unsigned Depth,
388 SourceLocation ExportLoc,
389 SourceLocation TemplateLoc,
390 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000391 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000392 SourceLocation RAngleLoc) {
393 if (ExportLoc.isValid())
394 Diag(ExportLoc, diag::note_template_export_unsupported);
395
Douglas Gregorddc29e12009-02-06 22:42:48 +0000396 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
397 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000398}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000399
Douglas Gregor212e81c2009-03-25 00:13:59 +0000400Sema::DeclResult
Douglas Gregorddc29e12009-02-06 22:42:48 +0000401Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
402 SourceLocation KWLoc, const CXXScopeSpec &SS,
403 IdentifierInfo *Name, SourceLocation NameLoc,
404 AttributeList *Attr,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000405 MultiTemplateParamsArg TemplateParameterLists,
406 AccessSpecifier AS) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000407 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
408 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000409 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000410
411 // Check that we can declare a template here.
412 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000413 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000414
415 TagDecl::TagKind Kind;
416 switch (TagSpec) {
417 default: assert(0 && "Unknown tag type!");
418 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
419 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
420 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
421 }
422
423 // There is no such thing as an unnamed class template.
424 if (!Name) {
425 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000426 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000427 }
428
429 // Find any previous declaration with this name.
430 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
431 true);
432 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
433 NamedDecl *PrevDecl = 0;
434 if (Previous.begin() != Previous.end())
435 PrevDecl = *Previous.begin();
436
437 DeclContext *SemanticContext = CurContext;
438 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000439 SemanticContext = computeDeclContext(SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000440
Mike Stump390b4cc2009-05-16 07:39:55 +0000441 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregorddc29e12009-02-06 22:42:48 +0000442 }
443
444 // FIXME: member templates!
445 TemplateParameterList *TemplateParams
446 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
447
448 // If there is a previous declaration with the same name, check
449 // whether this is a valid redeclaration.
450 ClassTemplateDecl *PrevClassTemplate
451 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
452 if (PrevClassTemplate) {
453 // Ensure that the template parameter lists are compatible.
454 if (!TemplateParameterListsAreEqual(TemplateParams,
455 PrevClassTemplate->getTemplateParameters(),
456 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000457 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000458
459 // C++ [temp.class]p4:
460 // In a redeclaration, partial specialization, explicit
461 // specialization or explicit instantiation of a class template,
462 // the class-key shall agree in kind with the original class
463 // template declaration (7.1.5.3).
464 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000465 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000466 Diag(KWLoc, diag::err_use_with_wrong_tag)
467 << Name
468 << CodeModificationHint::CreateReplacement(KWLoc,
469 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000470 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000471 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000472 }
473
Douglas Gregorddc29e12009-02-06 22:42:48 +0000474 // Check for redefinition of this class template.
475 if (TK == TK_Definition) {
476 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
477 Diag(NameLoc, diag::err_redefinition) << Name;
478 Diag(Def->getLocation(), diag::note_previous_definition);
479 // FIXME: Would it make sense to try to "forget" the previous
480 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000481 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000482 }
483 }
484 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
485 // Maybe we will complain about the shadowed template parameter.
486 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
487 // Just pretend that we didn't see the previous declaration.
488 PrevDecl = 0;
489 } else if (PrevDecl) {
490 // C++ [temp]p5:
491 // A class template shall not have the same name as any other
492 // template, class, function, object, enumeration, enumerator,
493 // namespace, or type in the same scope (3.3), except as specified
494 // in (14.5.4).
495 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
496 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000497 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000498 }
499
Douglas Gregord684b002009-02-10 19:49:53 +0000500 // Check the template parameter list of this declaration, possibly
501 // merging in the template parameter list from the previous class
502 // template declaration.
503 if (CheckTemplateParameterList(TemplateParams,
504 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
505 Invalid = true;
506
Douglas Gregor7da97d02009-05-10 22:57:19 +0000507 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000508 // declaration!
509
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000510 CXXRecordDecl *NewClass =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000511 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
512 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000513 PrevClassTemplate->getTemplatedDecl() : 0,
514 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000515
516 ClassTemplateDecl *NewTemplate
517 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
518 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000519 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000520 NewClass->setDescribedClassTemplate(NewTemplate);
521
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000522 // Build the type for the class template declaration now.
523 QualType T =
524 Context.getTypeDeclType(NewClass,
525 PrevClassTemplate?
526 PrevClassTemplate->getTemplatedDecl() : 0);
527 assert(T->isDependentType() && "Class template type is not dependent?");
528 (void)T;
529
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000530 // Set the access specifier.
531 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
532
Douglas Gregorddc29e12009-02-06 22:42:48 +0000533 // Set the lexical context of these templates
534 NewClass->setLexicalDeclContext(CurContext);
535 NewTemplate->setLexicalDeclContext(CurContext);
536
537 if (TK == TK_Definition)
538 NewClass->startDefinition();
539
540 if (Attr)
541 ProcessDeclAttributeList(NewClass, Attr);
542
543 PushOnScopeChains(NewTemplate, S);
544
Douglas Gregord684b002009-02-10 19:49:53 +0000545 if (Invalid) {
546 NewTemplate->setInvalidDecl();
547 NewClass->setInvalidDecl();
548 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000549 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000550}
551
Douglas Gregord684b002009-02-10 19:49:53 +0000552/// \brief Checks the validity of a template parameter list, possibly
553/// considering the template parameter list from a previous
554/// declaration.
555///
556/// If an "old" template parameter list is provided, it must be
557/// equivalent (per TemplateParameterListsAreEqual) to the "new"
558/// template parameter list.
559///
560/// \param NewParams Template parameter list for a new template
561/// declaration. This template parameter list will be updated with any
562/// default arguments that are carried through from the previous
563/// template parameter list.
564///
565/// \param OldParams If provided, template parameter list from a
566/// previous declaration of the same template. Default template
567/// arguments will be merged from the old template parameter list to
568/// the new template parameter list.
569///
570/// \returns true if an error occurred, false otherwise.
571bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
572 TemplateParameterList *OldParams) {
573 bool Invalid = false;
574
575 // C++ [temp.param]p10:
576 // The set of default template-arguments available for use with a
577 // template declaration or definition is obtained by merging the
578 // default arguments from the definition (if in scope) and all
579 // declarations in scope in the same way default function
580 // arguments are (8.3.6).
581 bool SawDefaultArgument = false;
582 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000583
Mike Stump1a35fde2009-02-11 23:03:27 +0000584 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000585 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000586 if (OldParams)
587 OldParam = OldParams->begin();
588
589 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
590 NewParamEnd = NewParams->end();
591 NewParam != NewParamEnd; ++NewParam) {
592 // Variables used to diagnose redundant default arguments
593 bool RedundantDefaultArg = false;
594 SourceLocation OldDefaultLoc;
595 SourceLocation NewDefaultLoc;
596
597 // Variables used to diagnose missing default arguments
598 bool MissingDefaultArg = false;
599
600 // Merge default arguments for template type parameters.
601 if (TemplateTypeParmDecl *NewTypeParm
602 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
603 TemplateTypeParmDecl *OldTypeParm
604 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
605
606 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
607 NewTypeParm->hasDefaultArgument()) {
608 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
609 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
610 SawDefaultArgument = true;
611 RedundantDefaultArg = true;
612 PreviousDefaultArgLoc = NewDefaultLoc;
613 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
614 // Merge the default argument from the old declaration to the
615 // new declaration.
616 SawDefaultArgument = true;
617 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
618 OldTypeParm->getDefaultArgumentLoc(),
619 true);
620 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
621 } else if (NewTypeParm->hasDefaultArgument()) {
622 SawDefaultArgument = true;
623 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
624 } else if (SawDefaultArgument)
625 MissingDefaultArg = true;
626 }
627 // Merge default arguments for non-type template parameters
628 else if (NonTypeTemplateParmDecl *NewNonTypeParm
629 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
630 NonTypeTemplateParmDecl *OldNonTypeParm
631 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
632 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
633 NewNonTypeParm->hasDefaultArgument()) {
634 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
635 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
636 SawDefaultArgument = true;
637 RedundantDefaultArg = true;
638 PreviousDefaultArgLoc = NewDefaultLoc;
639 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
640 // Merge the default argument from the old declaration to the
641 // new declaration.
642 SawDefaultArgument = true;
643 // FIXME: We need to create a new kind of "default argument"
644 // expression that points to a previous template template
645 // parameter.
646 NewNonTypeParm->setDefaultArgument(
647 OldNonTypeParm->getDefaultArgument());
648 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
649 } else if (NewNonTypeParm->hasDefaultArgument()) {
650 SawDefaultArgument = true;
651 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
652 } else if (SawDefaultArgument)
653 MissingDefaultArg = true;
654 }
655 // Merge default arguments for template template parameters
656 else {
657 TemplateTemplateParmDecl *NewTemplateParm
658 = cast<TemplateTemplateParmDecl>(*NewParam);
659 TemplateTemplateParmDecl *OldTemplateParm
660 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
661 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
662 NewTemplateParm->hasDefaultArgument()) {
663 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
664 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
665 SawDefaultArgument = true;
666 RedundantDefaultArg = true;
667 PreviousDefaultArgLoc = NewDefaultLoc;
668 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
669 // Merge the default argument from the old declaration to the
670 // new declaration.
671 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000672 // FIXME: We need to create a new kind of "default argument" expression
673 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000674 NewTemplateParm->setDefaultArgument(
675 OldTemplateParm->getDefaultArgument());
676 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
677 } else if (NewTemplateParm->hasDefaultArgument()) {
678 SawDefaultArgument = true;
679 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
680 } else if (SawDefaultArgument)
681 MissingDefaultArg = true;
682 }
683
684 if (RedundantDefaultArg) {
685 // C++ [temp.param]p12:
686 // A template-parameter shall not be given default arguments
687 // by two different declarations in the same scope.
688 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
689 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
690 Invalid = true;
691 } else if (MissingDefaultArg) {
692 // C++ [temp.param]p11:
693 // If a template-parameter has a default template-argument,
694 // all subsequent template-parameters shall have a default
695 // template-argument supplied.
696 Diag((*NewParam)->getLocation(),
697 diag::err_template_param_default_arg_missing);
698 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
699 Invalid = true;
700 }
701
702 // If we have an old template parameter list that we're merging
703 // in, move on to the next parameter.
704 if (OldParams)
705 ++OldParam;
706 }
707
708 return Invalid;
709}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000710
Douglas Gregor40808ce2009-03-09 23:48:35 +0000711/// \brief Translates template arguments as provided by the parser
712/// into template arguments used by semantic analysis.
713static void
714translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
715 SourceLocation *TemplateArgLocs,
716 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
717 TemplateArgs.reserve(TemplateArgsIn.size());
718
719 void **Args = TemplateArgsIn.getArgs();
720 bool *ArgIsType = TemplateArgsIn.getArgIsType();
721 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
722 TemplateArgs.push_back(
723 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
724 QualType::getFromOpaquePtr(Args[Arg]))
725 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
726 }
727}
728
Douglas Gregorc45c2322009-03-31 00:43:58 +0000729/// \brief Build a canonical version of a template argument list.
730///
731/// This function builds a canonical version of the given template
732/// argument list, where each of the template arguments has been
733/// converted into its canonical form. This routine is typically used
734/// to canonicalize a template argument list when the template name
735/// itself is dependent. When the template name refers to an actual
736/// template declaration, Sema::CheckTemplateArgumentList should be
737/// used to check and canonicalize the template arguments.
738///
739/// \param TemplateArgs The incoming template arguments.
740///
741/// \param NumTemplateArgs The number of template arguments in \p
742/// TemplateArgs.
743///
744/// \param Canonical A vector to be filled with the canonical versions
745/// of the template arguments.
746///
747/// \param Context The ASTContext in which the template arguments live.
748static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
749 unsigned NumTemplateArgs,
750 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
751 ASTContext &Context) {
752 Canonical.reserve(NumTemplateArgs);
753 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
754 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000755 case TemplateArgument::Null:
756 assert(false && "Should never see a NULL template argument here");
757 break;
758
Douglas Gregorc45c2322009-03-31 00:43:58 +0000759 case TemplateArgument::Expression:
760 // FIXME: Build canonical expression (!)
761 Canonical.push_back(TemplateArgs[Idx]);
762 break;
763
764 case TemplateArgument::Declaration:
Douglas Gregor7da97d02009-05-10 22:57:19 +0000765 Canonical.push_back(
766 TemplateArgument(SourceLocation(),
767 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregorc45c2322009-03-31 00:43:58 +0000768 break;
769
770 case TemplateArgument::Integral:
771 Canonical.push_back(TemplateArgument(SourceLocation(),
772 *TemplateArgs[Idx].getAsIntegral(),
773 TemplateArgs[Idx].getIntegralType()));
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000774 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000775
776 case TemplateArgument::Type: {
777 QualType CanonType
778 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
779 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000780 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000781 }
782 }
783 }
784}
785
Douglas Gregor7532dc62009-03-30 22:58:21 +0000786QualType Sema::CheckTemplateIdType(TemplateName Name,
787 SourceLocation TemplateLoc,
788 SourceLocation LAngleLoc,
789 const TemplateArgument *TemplateArgs,
790 unsigned NumTemplateArgs,
791 SourceLocation RAngleLoc) {
792 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +0000793 if (!Template) {
794 // The template name does not resolve to a template, so we just
795 // build a dependent template-id type.
796
797 // Canonicalize the template arguments to build the canonical
798 // template-id type.
799 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
800 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
801 CanonicalTemplateArgs, Context);
802
Douglas Gregor45fbaf02009-05-07 06:49:52 +0000803 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000804 QualType CanonType
Douglas Gregor45fbaf02009-05-07 06:49:52 +0000805 = Context.getTemplateSpecializationType(CanonName,
806 &CanonicalTemplateArgs[0],
Douglas Gregorc45c2322009-03-31 00:43:58 +0000807 CanonicalTemplateArgs.size());
808
809 // Build the dependent template-id type.
810 return Context.getTemplateSpecializationType(Name, TemplateArgs,
811 NumTemplateArgs, CanonType);
812 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000813
Douglas Gregor40808ce2009-03-09 23:48:35 +0000814 // Check that the template argument list is well-formed for this
815 // template.
Anders Carlsson9ba41642009-06-05 05:31:27 +0000816 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000817 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000818 TemplateArgs, NumTemplateArgs, RAngleLoc,
819 ConvertedTemplateArgs))
820 return QualType();
821
822 assert((ConvertedTemplateArgs.size() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000823 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000824 "Converted template argument list is too short!");
825
826 QualType CanonType;
827
Douglas Gregor7532dc62009-03-30 22:58:21 +0000828 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000829 TemplateArgs,
830 NumTemplateArgs)) {
831 // This class template specialization is a dependent
832 // type. Therefore, its canonical type is another class template
833 // specialization type that contains all of the converted
834 // arguments in canonical form. This ensures that, e.g., A<T> and
835 // A<T, T> have identical types when A is declared as:
836 //
837 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +0000838 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
839 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000840 ConvertedTemplateArgs.getFlatArgumentList(),
841 ConvertedTemplateArgs.flatSize());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000842 } else if (ClassTemplateDecl *ClassTemplate
843 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000844 // Find the class template specialization declaration that
845 // corresponds to these arguments.
846 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000847 ClassTemplateSpecializationDecl::Profile(ID,
848 ConvertedTemplateArgs.getFlatArgumentList(),
849 ConvertedTemplateArgs.flatSize());
Douglas Gregor40808ce2009-03-09 23:48:35 +0000850 void *InsertPos = 0;
851 ClassTemplateSpecializationDecl *Decl
852 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
853 if (!Decl) {
854 // This is the first time we have referenced this class template
855 // specialization. Create the canonical declaration and add it to
856 // the set of specializations.
857 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000858 ClassTemplate->getDeclContext(),
859 TemplateLoc,
860 ClassTemplate,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +0000861 ConvertedTemplateArgs, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000862 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
863 Decl->setLexicalDeclContext(CurContext);
864 }
865
866 CanonType = Context.getTypeDeclType(Decl);
867 }
868
869 // Build the fully-sugared type for this class template
870 // specialization, which refers back to the class template
871 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +0000872 return Context.getTemplateSpecializationType(Name, TemplateArgs,
873 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000874}
875
Douglas Gregorcc636682009-02-17 23:15:12 +0000876Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +0000877Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
878 SourceLocation LAngleLoc,
879 ASTTemplateArgsPtr TemplateArgsIn,
880 SourceLocation *TemplateArgLocs,
881 SourceLocation RAngleLoc) {
882 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000883
Douglas Gregor40808ce2009-03-09 23:48:35 +0000884 // Translate the parser's template argument list in our AST format.
885 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
886 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000887
Douglas Gregor7532dc62009-03-30 22:58:21 +0000888 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000889 TemplateArgs.data(),
890 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +0000891 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000892 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000893
894 if (Result.isNull())
895 return true;
896
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000897 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000898}
899
Douglas Gregorc45c2322009-03-31 00:43:58 +0000900/// \brief Form a dependent template name.
901///
902/// This action forms a dependent template name given the template
903/// name and its (presumably dependent) scope specifier. For
904/// example, given "MetaFun::template apply", the scope specifier \p
905/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
906/// of the "template" keyword, and "apply" is the \p Name.
907Sema::TemplateTy
908Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
909 const IdentifierInfo &Name,
910 SourceLocation NameLoc,
911 const CXXScopeSpec &SS) {
912 if (!SS.isSet() || SS.isInvalid())
913 return TemplateTy();
914
915 NestedNameSpecifier *Qualifier
916 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
917
918 // FIXME: member of the current instantiation
919
920 if (!Qualifier->isDependent()) {
921 // C++0x [temp.names]p5:
922 // If a name prefixed by the keyword template is not the name of
923 // a template, the program is ill-formed. [Note: the keyword
924 // template may not be applied to non-template members of class
925 // templates. -end note ] [ Note: as is the case with the
926 // typename prefix, the template prefix is allowed in cases
927 // where it is not strictly necessary; i.e., when the
928 // nested-name-specifier or the expression on the left of the ->
929 // or . is not dependent on a template-parameter, or the use
930 // does not appear in the scope of a template. -end note]
931 //
932 // Note: C++03 was more strict here, because it banned the use of
933 // the "template" keyword prior to a template-name that was not a
934 // dependent name. C++ DR468 relaxed this requirement (the
935 // "template" keyword is now permitted). We follow the C++0x
936 // rules, even in C++03 mode, retroactively applying the DR.
937 TemplateTy Template;
938 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
939 if (TNK == TNK_Non_template) {
940 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
941 << &Name;
942 return TemplateTy();
943 }
944
945 return Template;
946 }
947
948 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
949}
950
Douglas Gregorc15cb382009-02-09 23:23:08 +0000951/// \brief Check that the given template argument list is well-formed
952/// for specializing the given template.
953bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
954 SourceLocation TemplateLoc,
955 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000956 const TemplateArgument *TemplateArgs,
957 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000958 SourceLocation RAngleLoc,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000959 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000960 TemplateParameterList *Params = Template->getTemplateParameters();
961 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +0000962 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000963 bool Invalid = false;
964
965 if (NumArgs > NumParams ||
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000966 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000967 // FIXME: point at either the first arg beyond what we can handle,
968 // or the '>', depending on whether we have too many or too few
969 // arguments.
970 SourceRange Range;
971 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +0000972 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000973 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
974 << (NumArgs > NumParams)
975 << (isa<ClassTemplateDecl>(Template)? 0 :
976 isa<FunctionTemplateDecl>(Template)? 1 :
977 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
978 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000979 Diag(Template->getLocation(), diag::note_template_decl_here)
980 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +0000981 Invalid = true;
982 }
983
984 // C++ [temp.arg]p1:
985 // [...] The type and form of each template-argument specified in
986 // a template-id shall match the type and form specified for the
987 // corresponding parameter declared by the template in its
988 // template-parameter-list.
989 unsigned ArgIdx = 0;
990 for (TemplateParameterList::iterator Param = Params->begin(),
991 ParamEnd = Params->end();
992 Param != ParamEnd; ++Param, ++ArgIdx) {
993 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +0000994 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000995 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000996 // Retrieve the default template argument from the template
997 // parameter.
998 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
999 if (!TTP->hasDefaultArgument())
1000 break;
1001
Douglas Gregor40808ce2009-03-09 23:48:35 +00001002 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001003
1004 // If the argument type is dependent, instantiate it now based
1005 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001006 if (ArgType->isDependentType()) {
1007 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001008 Template, Converted.getFlatArgumentList(),
1009 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001010 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001011
Anders Carlssone9c904b2009-06-05 04:47:51 +00001012 TemplateArgumentList TemplateArgs(Context, Converted,
1013 /*CopyArgs=*/false,
1014 /*FlattenArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001015 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor99ebf652009-02-27 19:31:52 +00001016 TTP->getDefaultArgumentLoc(),
1017 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001018 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001019
1020 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001021 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001022
Douglas Gregor40808ce2009-03-09 23:48:35 +00001023 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001024 } else if (NonTypeTemplateParmDecl *NTTP
1025 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1026 if (!NTTP->hasDefaultArgument())
1027 break;
1028
Anders Carlsson3b56c002009-06-11 16:06:49 +00001029 InstantiatingTemplate Inst(*this, TemplateLoc,
1030 Template, Converted.getFlatArgumentList(),
1031 Converted.flatSize(),
1032 SourceRange(TemplateLoc, RAngleLoc));
1033
1034 TemplateArgumentList TemplateArgs(Context, Converted,
1035 /*CopyArgs=*/false,
1036 /*FlattenArgs=*/false);
1037
1038 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1039 TemplateArgs);
1040 if (E.isInvalid())
1041 return true;
1042
1043 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001044 } else {
1045 TemplateTemplateParmDecl *TempParm
1046 = cast<TemplateTemplateParmDecl>(*Param);
1047
1048 if (!TempParm->hasDefaultArgument())
1049 break;
1050
Douglas Gregor2943aed2009-03-03 04:44:36 +00001051 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001052 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001053 }
1054 } else {
1055 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001056 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001057 }
1058
Douglas Gregorc15cb382009-02-09 23:23:08 +00001059
1060 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1061 // Check template type parameters.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001062 if (Arg.getKind() == TemplateArgument::Type) {
1063 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001064 Invalid = true;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001065
1066 // Add the converted template type argument.
1067 Converted.push_back(
Douglas Gregor40808ce2009-03-09 23:48:35 +00001068 TemplateArgument(Arg.getLocation(),
1069 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregorc15cb382009-02-09 23:23:08 +00001070 continue;
1071 }
1072
1073 // C++ [temp.arg.type]p1:
1074 // A template-argument for a template-parameter which is a
1075 // type shall be a type-id.
1076
1077 // We have a template type parameter but the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001078 // is not a type.
1079 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor8b642592009-02-10 00:53:15 +00001080 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001081 Invalid = true;
1082 } else if (NonTypeTemplateParmDecl *NTTP
1083 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1084 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001085
1086 // Instantiate the type of the non-type template parameter with
1087 // the template arguments we've seen thus far.
1088 QualType NTTPType = NTTP->getType();
1089 if (NTTPType->isDependentType()) {
1090 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001091 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001092 Template, Converted.getFlatArgumentList(),
1093 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001094 SourceRange(TemplateLoc, RAngleLoc));
1095
Anders Carlssone9c904b2009-06-05 04:47:51 +00001096 TemplateArgumentList TemplateArgs(Context, Converted,
1097 /*CopyArgs=*/false,
1098 /*FlattenArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001099 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001100 NTTP->getLocation(),
1101 NTTP->getDeclName());
1102 // If that worked, check the non-type template parameter type
1103 // for validity.
1104 if (!NTTPType.isNull())
1105 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1106 NTTP->getLocation());
1107
1108 if (NTTPType.isNull()) {
1109 Invalid = true;
1110 break;
1111 }
1112 }
1113
Douglas Gregor40808ce2009-03-09 23:48:35 +00001114 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001115 case TemplateArgument::Null:
1116 assert(false && "Should never see a NULL template argument here");
1117 break;
1118
Douglas Gregor40808ce2009-03-09 23:48:35 +00001119 case TemplateArgument::Expression: {
1120 Expr *E = Arg.getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001121 TemplateArgument Result;
1122 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001123 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001124 else
1125 Converted.push_back(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001126 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001127 }
1128
Douglas Gregor40808ce2009-03-09 23:48:35 +00001129 case TemplateArgument::Declaration:
1130 case TemplateArgument::Integral:
1131 // We've already checked this template argument, so just copy
1132 // it to the list of converted arguments.
1133 Converted.push_back(Arg);
1134 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001135
Douglas Gregor40808ce2009-03-09 23:48:35 +00001136 case TemplateArgument::Type:
1137 // We have a non-type template parameter but the template
1138 // argument is a type.
1139
1140 // C++ [temp.arg]p2:
1141 // In a template-argument, an ambiguity between a type-id and
1142 // an expression is resolved to a type-id, regardless of the
1143 // form of the corresponding template-parameter.
1144 //
1145 // We warn specifically about this case, since it can be rather
1146 // confusing for users.
1147 if (Arg.getAsType()->isFunctionType())
1148 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1149 << Arg.getAsType();
1150 else
1151 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1152 Diag((*Param)->getLocation(), diag::note_template_param_here);
1153 Invalid = true;
1154 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001155 } else {
1156 // Check template template parameters.
1157 TemplateTemplateParmDecl *TempParm
1158 = cast<TemplateTemplateParmDecl>(*Param);
1159
Douglas Gregor40808ce2009-03-09 23:48:35 +00001160 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001161 case TemplateArgument::Null:
1162 assert(false && "Should never see a NULL template argument here");
1163 break;
1164
Douglas Gregor40808ce2009-03-09 23:48:35 +00001165 case TemplateArgument::Expression: {
1166 Expr *ArgExpr = Arg.getAsExpr();
1167 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1168 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1169 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1170 Invalid = true;
1171
1172 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001173 Decl *D
1174 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1175 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001176 continue;
1177 }
1178 }
1179 // fall through
1180
1181 case TemplateArgument::Type: {
1182 // We have a template template parameter but the template
1183 // argument does not refer to a template.
1184 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1185 Invalid = true;
1186 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001187 }
1188
Douglas Gregor40808ce2009-03-09 23:48:35 +00001189 case TemplateArgument::Declaration:
1190 // We've already checked this template argument, so just copy
1191 // it to the list of converted arguments.
1192 Converted.push_back(Arg);
1193 break;
1194
1195 case TemplateArgument::Integral:
1196 assert(false && "Integral argument with template template parameter");
1197 break;
1198 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001199 }
1200 }
1201
1202 return Invalid;
1203}
1204
1205/// \brief Check a template argument against its corresponding
1206/// template type parameter.
1207///
1208/// This routine implements the semantics of C++ [temp.arg.type]. It
1209/// returns true if an error occurred, and false otherwise.
1210bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1211 QualType Arg, SourceLocation ArgLoc) {
1212 // C++ [temp.arg.type]p2:
1213 // A local type, a type with no linkage, an unnamed type or a type
1214 // compounded from any of these types shall not be used as a
1215 // template-argument for a template type-parameter.
1216 //
1217 // FIXME: Perform the recursive and no-linkage type checks.
1218 const TagType *Tag = 0;
1219 if (const EnumType *EnumT = Arg->getAsEnumType())
1220 Tag = EnumT;
1221 else if (const RecordType *RecordT = Arg->getAsRecordType())
1222 Tag = RecordT;
1223 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1224 return Diag(ArgLoc, diag::err_template_arg_local_type)
1225 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001226 else if (Tag && !Tag->getDecl()->getDeclName() &&
1227 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001228 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1229 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1230 return true;
1231 }
1232
1233 return false;
1234}
1235
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001236/// \brief Checks whether the given template argument is the address
1237/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001238bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1239 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001240 bool Invalid = false;
1241
1242 // See through any implicit casts we added to fix the type.
1243 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1244 Arg = Cast->getSubExpr();
1245
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001246 // C++0x allows nullptr, and there's no further checking to be done for that.
1247 if (Arg->getType()->isNullPtrType())
1248 return false;
1249
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001250 // C++ [temp.arg.nontype]p1:
1251 //
1252 // A template-argument for a non-type, non-template
1253 // template-parameter shall be one of: [...]
1254 //
1255 // -- the address of an object or function with external
1256 // linkage, including function templates and function
1257 // template-ids but excluding non-static class members,
1258 // expressed as & id-expression where the & is optional if
1259 // the name refers to a function or array, or if the
1260 // corresponding template-parameter is a reference; or
1261 DeclRefExpr *DRE = 0;
1262
1263 // Ignore (and complain about) any excess parentheses.
1264 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1265 if (!Invalid) {
1266 Diag(Arg->getSourceRange().getBegin(),
1267 diag::err_template_arg_extra_parens)
1268 << Arg->getSourceRange();
1269 Invalid = true;
1270 }
1271
1272 Arg = Parens->getSubExpr();
1273 }
1274
1275 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1276 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1277 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1278 } else
1279 DRE = dyn_cast<DeclRefExpr>(Arg);
1280
1281 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1282 return Diag(Arg->getSourceRange().getBegin(),
1283 diag::err_template_arg_not_object_or_func_form)
1284 << Arg->getSourceRange();
1285
1286 // Cannot refer to non-static data members
1287 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1288 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1289 << Field << Arg->getSourceRange();
1290
1291 // Cannot refer to non-static member functions
1292 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1293 if (!Method->isStatic())
1294 return Diag(Arg->getSourceRange().getBegin(),
1295 diag::err_template_arg_method)
1296 << Method << Arg->getSourceRange();
1297
1298 // Functions must have external linkage.
1299 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1300 if (Func->getStorageClass() == FunctionDecl::Static) {
1301 Diag(Arg->getSourceRange().getBegin(),
1302 diag::err_template_arg_function_not_extern)
1303 << Func << Arg->getSourceRange();
1304 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1305 << true;
1306 return true;
1307 }
1308
1309 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001310 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001311 return Invalid;
1312 }
1313
1314 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1315 if (!Var->hasGlobalStorage()) {
1316 Diag(Arg->getSourceRange().getBegin(),
1317 diag::err_template_arg_object_not_extern)
1318 << Var << Arg->getSourceRange();
1319 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1320 << true;
1321 return true;
1322 }
1323
1324 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001325 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001326 return Invalid;
1327 }
1328
1329 // We found something else, but we don't know specifically what it is.
1330 Diag(Arg->getSourceRange().getBegin(),
1331 diag::err_template_arg_not_object_or_func)
1332 << Arg->getSourceRange();
1333 Diag(DRE->getDecl()->getLocation(),
1334 diag::note_template_arg_refers_here);
1335 return true;
1336}
1337
1338/// \brief Checks whether the given template argument is a pointer to
1339/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001340bool
1341Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001342 bool Invalid = false;
1343
1344 // See through any implicit casts we added to fix the type.
1345 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1346 Arg = Cast->getSubExpr();
1347
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001348 // C++0x allows nullptr, and there's no further checking to be done for that.
1349 if (Arg->getType()->isNullPtrType())
1350 return false;
1351
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001352 // C++ [temp.arg.nontype]p1:
1353 //
1354 // A template-argument for a non-type, non-template
1355 // template-parameter shall be one of: [...]
1356 //
1357 // -- a pointer to member expressed as described in 5.3.1.
1358 QualifiedDeclRefExpr *DRE = 0;
1359
1360 // Ignore (and complain about) any excess parentheses.
1361 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1362 if (!Invalid) {
1363 Diag(Arg->getSourceRange().getBegin(),
1364 diag::err_template_arg_extra_parens)
1365 << Arg->getSourceRange();
1366 Invalid = true;
1367 }
1368
1369 Arg = Parens->getSubExpr();
1370 }
1371
1372 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1373 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1374 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1375
1376 if (!DRE)
1377 return Diag(Arg->getSourceRange().getBegin(),
1378 diag::err_template_arg_not_pointer_to_member_form)
1379 << Arg->getSourceRange();
1380
1381 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1382 assert((isa<FieldDecl>(DRE->getDecl()) ||
1383 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1384 "Only non-static member pointers can make it here");
1385
1386 // Okay: this is the address of a non-static member, and therefore
1387 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001388 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001389 return Invalid;
1390 }
1391
1392 // We found something else, but we don't know specifically what it is.
1393 Diag(Arg->getSourceRange().getBegin(),
1394 diag::err_template_arg_not_pointer_to_member_form)
1395 << Arg->getSourceRange();
1396 Diag(DRE->getDecl()->getLocation(),
1397 diag::note_template_arg_refers_here);
1398 return true;
1399}
1400
Douglas Gregorc15cb382009-02-09 23:23:08 +00001401/// \brief Check a template argument against its corresponding
1402/// non-type template parameter.
1403///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001404/// This routine implements the semantics of C++ [temp.arg.nontype].
1405/// It returns true if an error occurred, and false otherwise. \p
1406/// InstantiatedParamType is the type of the non-type template
1407/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001408///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001409/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001410bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001411 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001412 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001413 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1414
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001415 // If either the parameter has a dependent type or the argument is
1416 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001417 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001418 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1419 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001420 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001421 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001422 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001423
1424 // C++ [temp.arg.nontype]p5:
1425 // The following conversions are performed on each expression used
1426 // as a non-type template-argument. If a non-type
1427 // template-argument cannot be converted to the type of the
1428 // corresponding template-parameter then the program is
1429 // ill-formed.
1430 //
1431 // -- for a non-type template-parameter of integral or
1432 // enumeration type, integral promotions (4.5) and integral
1433 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001434 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001435 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001436 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001437 // C++ [temp.arg.nontype]p1:
1438 // A template-argument for a non-type, non-template
1439 // template-parameter shall be one of:
1440 //
1441 // -- an integral constant-expression of integral or enumeration
1442 // type; or
1443 // -- the name of a non-type template-parameter; or
1444 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001445 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001446 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1447 Diag(Arg->getSourceRange().getBegin(),
1448 diag::err_template_arg_not_integral_or_enumeral)
1449 << ArgType << Arg->getSourceRange();
1450 Diag(Param->getLocation(), diag::note_template_param_here);
1451 return true;
1452 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001453 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001454 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1455 << ArgType << Arg->getSourceRange();
1456 return true;
1457 }
1458
1459 // FIXME: We need some way to more easily get the unqualified form
1460 // of the types without going all the way to the
1461 // canonical type.
1462 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1463 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1464 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1465 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1466
1467 // Try to convert the argument to the parameter's type.
1468 if (ParamType == ArgType) {
1469 // Okay: no conversion necessary
1470 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1471 !ParamType->isEnumeralType()) {
1472 // This is an integral promotion or conversion.
1473 ImpCastExprToType(Arg, ParamType);
1474 } else {
1475 // We can't perform this conversion.
1476 Diag(Arg->getSourceRange().getBegin(),
1477 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001478 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001479 Diag(Param->getLocation(), diag::note_template_param_here);
1480 return true;
1481 }
1482
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001483 QualType IntegerType = Context.getCanonicalType(ParamType);
1484 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001485 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001486
1487 if (!Arg->isValueDependent()) {
1488 // Check that an unsigned parameter does not receive a negative
1489 // value.
1490 if (IntegerType->isUnsignedIntegerType()
1491 && (Value.isSigned() && Value.isNegative())) {
1492 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1493 << Value.toString(10) << Param->getType()
1494 << Arg->getSourceRange();
1495 Diag(Param->getLocation(), diag::note_template_param_here);
1496 return true;
1497 }
1498
1499 // Check that we don't overflow the template parameter type.
1500 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1501 if (Value.getActiveBits() > AllowedBits) {
1502 Diag(Arg->getSourceRange().getBegin(),
1503 diag::err_template_arg_too_large)
1504 << Value.toString(10) << Param->getType()
1505 << Arg->getSourceRange();
1506 Diag(Param->getLocation(), diag::note_template_param_here);
1507 return true;
1508 }
1509
1510 if (Value.getBitWidth() != AllowedBits)
1511 Value.extOrTrunc(AllowedBits);
1512 Value.setIsSigned(IntegerType->isSignedIntegerType());
1513 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001514
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001515 // Add the value of this argument to the list of converted
1516 // arguments. We use the bitwidth and signedness of the template
1517 // parameter.
1518 if (Arg->isValueDependent()) {
1519 // The argument is value-dependent. Create a new
1520 // TemplateArgument with the converted expression.
1521 Converted = TemplateArgument(Arg);
1522 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001523 }
1524
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001525 Converted = TemplateArgument(StartLoc, Value,
1526 ParamType->isEnumeralType() ? ParamType
1527 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001528 return false;
1529 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001530
Douglas Gregorb86b0572009-02-11 01:18:59 +00001531 // Handle pointer-to-function, reference-to-function, and
1532 // pointer-to-member-function all in (roughly) the same way.
1533 if (// -- For a non-type template-parameter of type pointer to
1534 // function, only the function-to-pointer conversion (4.3) is
1535 // applied. If the template-argument represents a set of
1536 // overloaded functions (or a pointer to such), the matching
1537 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001538 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001539 (ParamType->isPointerType() &&
1540 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1541 // -- For a non-type template-parameter of type reference to
1542 // function, no conversions apply. If the template-argument
1543 // represents a set of overloaded functions, the matching
1544 // function is selected from the set (13.4).
1545 (ParamType->isReferenceType() &&
1546 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1547 // -- For a non-type template-parameter of type pointer to
1548 // member function, no conversions apply. If the
1549 // template-argument represents a set of overloaded member
1550 // functions, the matching member function is selected from
1551 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001552 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001553 (ParamType->isMemberPointerType() &&
1554 ParamType->getAsMemberPointerType()->getPointeeType()
1555 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001556 if (Context.hasSameUnqualifiedType(ArgType,
1557 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001558 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001559 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1560 ParamType->isMemberPointerType())) {
1561 ArgType = ParamType;
1562 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001563 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001564 ArgType = Context.getPointerType(ArgType);
1565 ImpCastExprToType(Arg, ArgType);
1566 } else if (FunctionDecl *Fn
1567 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001568 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1569 return true;
1570
Douglas Gregora35284b2009-02-11 00:19:33 +00001571 FixOverloadedFunctionReference(Arg, Fn);
1572 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001573 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001574 ArgType = Context.getPointerType(Arg->getType());
1575 ImpCastExprToType(Arg, ArgType);
1576 }
1577 }
1578
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001579 if (!Context.hasSameUnqualifiedType(ArgType,
1580 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001581 // We can't perform this conversion.
1582 Diag(Arg->getSourceRange().getBegin(),
1583 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001584 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001585 Diag(Param->getLocation(), diag::note_template_param_here);
1586 return true;
1587 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001588
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001589 if (ParamType->isMemberPointerType()) {
1590 NamedDecl *Member = 0;
1591 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1592 return true;
1593
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001594 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1595 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001596 return false;
1597 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001598
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001599 NamedDecl *Entity = 0;
1600 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1601 return true;
1602
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001603 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1604 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001605 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001606 }
1607
Chris Lattnerfe90de72009-02-20 21:37:53 +00001608 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001609 // -- for a non-type template-parameter of type pointer to
1610 // object, qualification conversions (4.4) and the
1611 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001612 // C++0x also allows a value of std::nullptr_t.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001613 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001614 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001615
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001616 if (ArgType->isNullPtrType()) {
1617 ArgType = ParamType;
1618 ImpCastExprToType(Arg, ParamType);
1619 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001620 ArgType = Context.getArrayDecayedType(ArgType);
1621 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001622 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001623
Douglas Gregorb86b0572009-02-11 01:18:59 +00001624 if (IsQualificationConversion(ArgType, ParamType)) {
1625 ArgType = ParamType;
1626 ImpCastExprToType(Arg, ParamType);
1627 }
1628
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001629 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001630 // We can't perform this conversion.
1631 Diag(Arg->getSourceRange().getBegin(),
1632 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001633 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001634 Diag(Param->getLocation(), diag::note_template_param_here);
1635 return true;
1636 }
1637
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001638 NamedDecl *Entity = 0;
1639 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1640 return true;
1641
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001642 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1643 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001644 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001645 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001646
1647 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1648 // -- For a non-type template-parameter of type reference to
1649 // object, no conversions apply. The type referred to by the
1650 // reference may be more cv-qualified than the (otherwise
1651 // identical) type of the template-argument. The
1652 // template-parameter is bound directly to the
1653 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001654 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001655 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001656
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001657 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001658 Diag(Arg->getSourceRange().getBegin(),
1659 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001660 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001661 << Arg->getSourceRange();
1662 Diag(Param->getLocation(), diag::note_template_param_here);
1663 return true;
1664 }
1665
1666 unsigned ParamQuals
1667 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1668 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1669
1670 if ((ParamQuals | ArgQuals) != ParamQuals) {
1671 Diag(Arg->getSourceRange().getBegin(),
1672 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001673 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001674 << Arg->getSourceRange();
1675 Diag(Param->getLocation(), diag::note_template_param_here);
1676 return true;
1677 }
1678
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001679 NamedDecl *Entity = 0;
1680 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1681 return true;
1682
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001683 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1684 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001685 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001686 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001687
1688 // -- For a non-type template-parameter of type pointer to data
1689 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001690 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00001691 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1692
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001693 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001694 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001695 } else if (ArgType->isNullPtrType()) {
1696 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00001697 } else if (IsQualificationConversion(ArgType, ParamType)) {
1698 ImpCastExprToType(Arg, ParamType);
1699 } else {
1700 // We can't perform this conversion.
1701 Diag(Arg->getSourceRange().getBegin(),
1702 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001703 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001704 Diag(Param->getLocation(), diag::note_template_param_here);
1705 return true;
1706 }
1707
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001708 NamedDecl *Member = 0;
1709 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1710 return true;
1711
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001712 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1713 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001714 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001715}
1716
1717/// \brief Check a template argument against its corresponding
1718/// template template parameter.
1719///
1720/// This routine implements the semantics of C++ [temp.arg.template].
1721/// It returns true if an error occurred, and false otherwise.
1722bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1723 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001724 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1725 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1726
1727 // C++ [temp.arg.template]p1:
1728 // A template-argument for a template template-parameter shall be
1729 // the name of a class template, expressed as id-expression. Only
1730 // primary class templates are considered when matching the
1731 // template template argument with the corresponding parameter;
1732 // partial specializations are not considered even if their
1733 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00001734 //
1735 // Note that we also allow template template parameters here, which
1736 // will happen when we are dealing with, e.g., class template
1737 // partial specializations.
1738 if (!isa<ClassTemplateDecl>(Template) &&
1739 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001740 assert(isa<FunctionTemplateDecl>(Template) &&
1741 "Only function templates are possible here");
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001742 Diag(Arg->getSourceRange().getBegin(),
1743 diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001744 << Template;
1745 }
1746
1747 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1748 Param->getTemplateParameters(),
1749 true, true,
1750 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001751}
1752
Douglas Gregorddc29e12009-02-06 22:42:48 +00001753/// \brief Determine whether the given template parameter lists are
1754/// equivalent.
1755///
1756/// \param New The new template parameter list, typically written in the
1757/// source code as part of a new template declaration.
1758///
1759/// \param Old The old template parameter list, typically found via
1760/// name lookup of the template declared with this template parameter
1761/// list.
1762///
1763/// \param Complain If true, this routine will produce a diagnostic if
1764/// the template parameter lists are not equivalent.
1765///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001766/// \param IsTemplateTemplateParm If true, this routine is being
1767/// called to compare the template parameter lists of a template
1768/// template parameter.
1769///
1770/// \param TemplateArgLoc If this source location is valid, then we
1771/// are actually checking the template parameter list of a template
1772/// argument (New) against the template parameter list of its
1773/// corresponding template template parameter (Old). We produce
1774/// slightly different diagnostics in this scenario.
1775///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001776/// \returns True if the template parameter lists are equal, false
1777/// otherwise.
1778bool
1779Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1780 TemplateParameterList *Old,
1781 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001782 bool IsTemplateTemplateParm,
1783 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001784 if (Old->size() != New->size()) {
1785 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001786 unsigned NextDiag = diag::err_template_param_list_different_arity;
1787 if (TemplateArgLoc.isValid()) {
1788 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1789 NextDiag = diag::note_template_param_list_different_arity;
1790 }
1791 Diag(New->getTemplateLoc(), NextDiag)
1792 << (New->size() > Old->size())
1793 << IsTemplateTemplateParm
1794 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001795 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1796 << IsTemplateTemplateParm
1797 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1798 }
1799
1800 return false;
1801 }
1802
1803 for (TemplateParameterList::iterator OldParm = Old->begin(),
1804 OldParmEnd = Old->end(), NewParm = New->begin();
1805 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1806 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001807 unsigned NextDiag = diag::err_template_param_different_kind;
1808 if (TemplateArgLoc.isValid()) {
1809 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1810 NextDiag = diag::note_template_param_different_kind;
1811 }
1812 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001813 << IsTemplateTemplateParm;
1814 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1815 << IsTemplateTemplateParm;
1816 return false;
1817 }
1818
1819 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1820 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00001821 // know we're at the same index).
1822#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00001823 // FIXME: Enable this code in debug mode *after* we properly go through
1824 // and "instantiate" the template parameter lists of template template
1825 // parameters. It's only after this instantiation that (1) any dependent
1826 // types within the template parameter list of the template template
1827 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00001828 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00001829 QualType OldParmType
1830 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1831 QualType NewParmType
1832 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1833 assert(Context.getCanonicalType(OldParmType) ==
1834 Context.getCanonicalType(NewParmType) &&
1835 "type parameter mismatch?");
1836#endif
1837 } else if (NonTypeTemplateParmDecl *OldNTTP
1838 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1839 // The types of non-type template parameters must agree.
1840 NonTypeTemplateParmDecl *NewNTTP
1841 = cast<NonTypeTemplateParmDecl>(*NewParm);
1842 if (Context.getCanonicalType(OldNTTP->getType()) !=
1843 Context.getCanonicalType(NewNTTP->getType())) {
1844 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001845 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1846 if (TemplateArgLoc.isValid()) {
1847 Diag(TemplateArgLoc,
1848 diag::err_template_arg_template_params_mismatch);
1849 NextDiag = diag::note_template_nontype_parm_different_type;
1850 }
1851 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001852 << NewNTTP->getType()
1853 << IsTemplateTemplateParm;
1854 Diag(OldNTTP->getLocation(),
1855 diag::note_template_nontype_parm_prev_declaration)
1856 << OldNTTP->getType();
1857 }
1858 return false;
1859 }
1860 } else {
1861 // The template parameter lists of template template
1862 // parameters must agree.
1863 // FIXME: Could we perform a faster "type" comparison here?
1864 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1865 "Only template template parameters handled here");
1866 TemplateTemplateParmDecl *OldTTP
1867 = cast<TemplateTemplateParmDecl>(*OldParm);
1868 TemplateTemplateParmDecl *NewTTP
1869 = cast<TemplateTemplateParmDecl>(*NewParm);
1870 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1871 OldTTP->getTemplateParameters(),
1872 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001873 /*IsTemplateTemplateParm=*/true,
1874 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00001875 return false;
1876 }
1877 }
1878
1879 return true;
1880}
1881
1882/// \brief Check whether a template can be declared within this scope.
1883///
1884/// If the template declaration is valid in this scope, returns
1885/// false. Otherwise, issues a diagnostic and returns true.
1886bool
1887Sema::CheckTemplateDeclScope(Scope *S,
1888 MultiTemplateParamsArg &TemplateParameterLists) {
1889 assert(TemplateParameterLists.size() > 0 && "Not a template");
1890
1891 // Find the nearest enclosing declaration scope.
1892 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1893 (S->getFlags() & Scope::TemplateParamScope) != 0)
1894 S = S->getParent();
1895
1896 TemplateParameterList *TemplateParams =
1897 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1898 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1899 SourceRange TemplateRange
1900 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1901
1902 // C++ [temp]p2:
1903 // A template-declaration can appear only as a namespace scope or
1904 // class scope declaration.
1905 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1906 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1907 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1908 return Diag(TemplateLoc, diag::err_template_linkage)
1909 << TemplateRange;
1910
1911 Ctx = Ctx->getParent();
1912 }
1913
1914 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1915 return false;
1916
1917 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1918 << TemplateRange;
1919}
Douglas Gregorcc636682009-02-17 23:15:12 +00001920
Douglas Gregorff668032009-05-13 18:28:20 +00001921/// \brief Check whether a class template specialization or explicit
1922/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00001923///
Douglas Gregorff668032009-05-13 18:28:20 +00001924/// This routine determines whether a class template specialization or
1925/// explicit instantiation can be declared in the current context
1926/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1927/// appropriate diagnostics if there was an error. It returns true if
1928// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00001929bool
1930Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1931 ClassTemplateSpecializationDecl *PrevDecl,
1932 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00001933 SourceRange ScopeSpecifierRange,
1934 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00001935 // C++ [temp.expl.spec]p2:
1936 // An explicit specialization shall be declared in the namespace
1937 // of which the template is a member, or, for member templates, in
1938 // the namespace of which the enclosing class or enclosing class
1939 // template is a member. An explicit specialization of a member
1940 // function, member class or static data member of a class
1941 // template shall be declared in the namespace of which the class
1942 // template is a member. Such a declaration may also be a
1943 // definition. If the declaration is not a definition, the
1944 // specialization may be defined later in the name- space in which
1945 // the explicit specialization was declared, or in a namespace
1946 // that encloses the one in which the explicit specialization was
1947 // declared.
1948 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1949 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregorff668032009-05-13 18:28:20 +00001950 << ExplicitInstantiation << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00001951 return true;
1952 }
1953
1954 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1955 DeclContext *TemplateContext
1956 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00001957 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
1958 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00001959 // There is no prior declaration of this entity, so this
1960 // specialization must be in the same context as the template
1961 // itself.
1962 if (DC != TemplateContext) {
1963 if (isa<TranslationUnitDecl>(TemplateContext))
1964 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1965 << ClassTemplate << ScopeSpecifierRange;
1966 else if (isa<NamespaceDecl>(TemplateContext))
1967 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1968 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1969 << ScopeSpecifierRange;
1970
1971 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1972 }
1973
1974 return false;
1975 }
1976
1977 // We have a previous declaration of this entity. Make sure that
1978 // this redeclaration (or definition) occurs in an enclosing namespace.
1979 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001980 // FIXME: In C++98, we would like to turn these errors into warnings,
1981 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00001982 bool SuppressedDiag = false;
1983 if (isa<TranslationUnitDecl>(TemplateContext)) {
1984 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1985 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1986 << ExplicitInstantiation << ClassTemplate << ScopeSpecifierRange;
1987 else
1988 SuppressedDiag = true;
1989 } else if (isa<NamespaceDecl>(TemplateContext)) {
1990 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1991 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1992 << ExplicitInstantiation << ClassTemplate
1993 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
1994 else
1995 SuppressedDiag = true;
1996 }
Douglas Gregor88b70942009-02-25 22:02:03 +00001997
Douglas Gregorff668032009-05-13 18:28:20 +00001998 if (!SuppressedDiag)
1999 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00002000 }
2001
2002 return false;
2003}
2004
Douglas Gregor212e81c2009-03-25 00:13:59 +00002005Sema::DeclResult
Douglas Gregorcc636682009-02-17 23:15:12 +00002006Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2007 SourceLocation KWLoc,
2008 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002009 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002010 SourceLocation TemplateNameLoc,
2011 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002012 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002013 SourceLocation *TemplateArgLocs,
2014 SourceLocation RAngleLoc,
2015 AttributeList *Attr,
2016 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002017 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002018 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002019 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002020 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002021
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002022 bool isPartialSpecialization = false;
2023
Douglas Gregor88b70942009-02-25 22:02:03 +00002024 // Check the validity of the template headers that introduce this
2025 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002026 // FIXME: Once we have member templates, we'll need to check
2027 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2028 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002029 if (TemplateParameterLists.size() == 0)
2030 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00002031 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002032 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00002033 TemplateParameterList *TemplateParams
2034 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattnerb28317a2009-03-28 19:18:32 +00002035 if (TemplateParameterLists.size() > 1) {
2036 Diag(TemplateParams->getTemplateLoc(),
2037 diag::err_template_spec_extra_headers);
2038 return true;
2039 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002040
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002041 if (TemplateParams->size() > 0) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002042 isPartialSpecialization = true;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002043
2044 // C++ [temp.class.spec]p10:
2045 // The template parameter list of a specialization shall not
2046 // contain default template argument values.
2047 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2048 Decl *Param = TemplateParams->getParam(I);
2049 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2050 if (TTP->hasDefaultArgument()) {
2051 Diag(TTP->getDefaultArgumentLoc(),
2052 diag::err_default_arg_in_partial_spec);
2053 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2054 }
2055 } else if (NonTypeTemplateParmDecl *NTTP
2056 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2057 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2058 Diag(NTTP->getDefaultArgumentLoc(),
2059 diag::err_default_arg_in_partial_spec)
2060 << DefArg->getSourceRange();
2061 NTTP->setDefaultArgument(0);
2062 DefArg->Destroy(Context);
2063 }
2064 } else {
2065 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2066 if (Expr *DefArg = TTP->getDefaultArgument()) {
2067 Diag(TTP->getDefaultArgumentLoc(),
2068 diag::err_default_arg_in_partial_spec)
2069 << DefArg->getSourceRange();
2070 TTP->setDefaultArgument(0);
2071 DefArg->Destroy(Context);
2072 }
2073 }
2074 }
2075 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002076 }
2077
Douglas Gregorcc636682009-02-17 23:15:12 +00002078 // Check that the specialization uses the same tag kind as the
2079 // original template.
2080 TagDecl::TagKind Kind;
2081 switch (TagSpec) {
2082 default: assert(0 && "Unknown tag type!");
2083 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2084 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2085 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2086 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002087 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2088 Kind, KWLoc,
2089 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002090 Diag(KWLoc, diag::err_use_with_wrong_tag)
2091 << ClassTemplate
2092 << CodeModificationHint::CreateReplacement(KWLoc,
2093 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002094 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2095 diag::note_previous_use);
2096 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2097 }
2098
Douglas Gregor40808ce2009-03-09 23:48:35 +00002099 // Translate the parser's template argument list in our AST format.
2100 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2101 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2102
Douglas Gregorcc636682009-02-17 23:15:12 +00002103 // Check that the template argument list is well-formed for this
2104 // template.
Anders Carlsson9ba41642009-06-05 05:31:27 +00002105 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00002106 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002107 &TemplateArgs[0], TemplateArgs.size(),
2108 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002109 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002110
2111 assert((ConvertedTemplateArgs.size() ==
2112 ClassTemplate->getTemplateParameters()->size()) &&
2113 "Converted template argument list is too short!");
2114
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002115 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002116 // corresponds to these arguments.
2117 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002118 if (isPartialSpecialization) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002119 // FIXME: Template parameter list matters, too
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002120 ClassTemplatePartialSpecializationDecl::Profile(ID,
2121 ConvertedTemplateArgs.getFlatArgumentList(),
2122 ConvertedTemplateArgs.flatSize());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002123 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002124 else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002125 ClassTemplateSpecializationDecl::Profile(ID,
2126 ConvertedTemplateArgs.getFlatArgumentList(),
2127 ConvertedTemplateArgs.flatSize());
Douglas Gregorcc636682009-02-17 23:15:12 +00002128 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002129 ClassTemplateSpecializationDecl *PrevDecl = 0;
2130
2131 if (isPartialSpecialization)
2132 PrevDecl
2133 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2134 InsertPos);
2135 else
2136 PrevDecl
2137 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002138
2139 ClassTemplateSpecializationDecl *Specialization = 0;
2140
Douglas Gregor88b70942009-02-25 22:02:03 +00002141 // Check whether we can declare a class template specialization in
2142 // the current scope.
2143 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2144 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002145 SS.getRange(),
2146 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002147 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002148
Douglas Gregorcc636682009-02-17 23:15:12 +00002149 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2150 // Since the only prior class template specialization with these
2151 // arguments was referenced but not declared, reuse that
2152 // declaration node as our own, updating its source location to
2153 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002154 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002155 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002156 PrevDecl = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002157 } else if (isPartialSpecialization) {
2158 // FIXME: extra checking for partial specializations
2159
2160 // Create a new class template partial specialization declaration node.
2161 TemplateParameterList *TemplateParams
2162 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2163 ClassTemplatePartialSpecializationDecl *PrevPartial
2164 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2165 ClassTemplatePartialSpecializationDecl *Partial
2166 = ClassTemplatePartialSpecializationDecl::Create(Context,
2167 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002168 TemplateNameLoc,
2169 TemplateParams,
2170 ClassTemplate,
2171 ConvertedTemplateArgs,
2172 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002173
2174 if (PrevPartial) {
2175 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2176 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2177 } else {
2178 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2179 }
2180 Specialization = Partial;
Douglas Gregorcc636682009-02-17 23:15:12 +00002181 } else {
2182 // Create a new class template specialization declaration node for
2183 // this explicit specialization.
2184 Specialization
2185 = ClassTemplateSpecializationDecl::Create(Context,
2186 ClassTemplate->getDeclContext(),
2187 TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002188 ClassTemplate,
2189 ConvertedTemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +00002190 PrevDecl);
2191
2192 if (PrevDecl) {
2193 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2194 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2195 } else {
2196 ClassTemplate->getSpecializations().InsertNode(Specialization,
2197 InsertPos);
2198 }
2199 }
2200
2201 // Note that this is an explicit specialization.
2202 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2203
2204 // Check that this isn't a redefinition of this specialization.
2205 if (TK == TK_Definition) {
2206 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002207 // FIXME: Should also handle explicit specialization after implicit
2208 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002209 SourceRange Range(TemplateNameLoc, RAngleLoc);
2210 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002211 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002212 Diag(Def->getLocation(), diag::note_previous_definition);
2213 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002214 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002215 }
2216 }
2217
Douglas Gregorfc705b82009-02-26 22:19:44 +00002218 // Build the fully-sugared type for this class template
2219 // specialization as the user wrote in the specialization
2220 // itself. This means that we'll pretty-print the type retrieved
2221 // from the specialization's declaration the way that the user
2222 // actually wrote the specialization, rather than formatting the
2223 // name based on the "canonical" representation used to store the
2224 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002225 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002226 = Context.getTemplateSpecializationType(Name,
2227 &TemplateArgs[0],
2228 TemplateArgs.size(),
Douglas Gregore6258932009-03-19 00:39:20 +00002229 Context.getTypeDeclType(Specialization));
Douglas Gregor7532dc62009-03-30 22:58:21 +00002230 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002231 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002232
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002233 // C++ [temp.expl.spec]p9:
2234 // A template explicit specialization is in the scope of the
2235 // namespace in which the template was defined.
2236 //
2237 // We actually implement this paragraph where we set the semantic
2238 // context (in the creation of the ClassTemplateSpecializationDecl),
2239 // but we also maintain the lexical context where the actual
2240 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002241 Specialization->setLexicalDeclContext(CurContext);
2242
2243 // We may be starting the definition of this specialization.
2244 if (TK == TK_Definition)
2245 Specialization->startDefinition();
2246
2247 // Add the specialization into its lexical context, so that it can
2248 // be seen when iterating through the list of declarations in that
2249 // context. However, specializations are not found by name lookup.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002250 CurContext->addDecl(Context, Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002251 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002252}
Douglas Gregord57959a2009-03-27 23:10:48 +00002253
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002254// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002255Sema::DeclResult
2256Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2257 unsigned TagSpec,
2258 SourceLocation KWLoc,
2259 const CXXScopeSpec &SS,
2260 TemplateTy TemplateD,
2261 SourceLocation TemplateNameLoc,
2262 SourceLocation LAngleLoc,
2263 ASTTemplateArgsPtr TemplateArgsIn,
2264 SourceLocation *TemplateArgLocs,
2265 SourceLocation RAngleLoc,
2266 AttributeList *Attr) {
2267 // Find the class template we're specializing
2268 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2269 ClassTemplateDecl *ClassTemplate
2270 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2271
2272 // Check that the specialization uses the same tag kind as the
2273 // original template.
2274 TagDecl::TagKind Kind;
2275 switch (TagSpec) {
2276 default: assert(0 && "Unknown tag type!");
2277 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2278 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2279 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2280 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002281 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2282 Kind, KWLoc,
2283 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002284 Diag(KWLoc, diag::err_use_with_wrong_tag)
2285 << ClassTemplate
2286 << CodeModificationHint::CreateReplacement(KWLoc,
2287 ClassTemplate->getTemplatedDecl()->getKindName());
2288 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2289 diag::note_previous_use);
2290 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2291 }
2292
Douglas Gregorff668032009-05-13 18:28:20 +00002293 // C++0x [temp.explicit]p2:
2294 // [...] An explicit instantiation shall appear in an enclosing
2295 // namespace of its template. [...]
2296 //
2297 // This is C++ DR 275.
2298 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2299 TemplateNameLoc,
2300 SS.getRange(),
2301 /*ExplicitInstantiation=*/true))
2302 return true;
2303
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002304 // Translate the parser's template argument list in our AST format.
2305 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2306 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2307
2308 // Check that the template argument list is well-formed for this
2309 // template.
Anders Carlsson9ba41642009-06-05 05:31:27 +00002310 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002311 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00002312 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002313 RAngleLoc, ConvertedTemplateArgs))
2314 return true;
2315
2316 assert((ConvertedTemplateArgs.size() ==
2317 ClassTemplate->getTemplateParameters()->size()) &&
2318 "Converted template argument list is too short!");
2319
2320 // Find the class template specialization declaration that
2321 // corresponds to these arguments.
2322 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002323 ClassTemplateSpecializationDecl::Profile(ID,
2324 ConvertedTemplateArgs.getFlatArgumentList(),
2325 ConvertedTemplateArgs.flatSize());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002326 void *InsertPos = 0;
2327 ClassTemplateSpecializationDecl *PrevDecl
2328 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2329
2330 ClassTemplateSpecializationDecl *Specialization = 0;
2331
Douglas Gregorff668032009-05-13 18:28:20 +00002332 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002333 if (PrevDecl) {
Douglas Gregorff668032009-05-13 18:28:20 +00002334 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002335 // This particular specialization has already been declared or
2336 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002337 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2338 << Context.getTypeDeclType(PrevDecl);
2339 Diag(PrevDecl->getLocation(),
2340 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002341 return DeclPtrTy::make(PrevDecl);
2342 }
2343
Douglas Gregorff668032009-05-13 18:28:20 +00002344 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002345 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002346 // For a given set of template parameters, if an explicit
2347 // instantiation of a template appears after a declaration of
2348 // an explicit specialization for that template, the explicit
2349 // instantiation has no effect.
2350 if (!getLangOptions().CPlusPlus0x) {
2351 Diag(TemplateNameLoc,
2352 diag::ext_explicit_instantiation_after_specialization)
2353 << Context.getTypeDeclType(PrevDecl);
2354 Diag(PrevDecl->getLocation(),
2355 diag::note_previous_template_specialization);
2356 }
2357
2358 // Create a new class template specialization declaration node
2359 // for this explicit specialization. This node is only used to
2360 // record the existence of this explicit instantiation for
2361 // accurate reproduction of the source code; we don't actually
2362 // use it for anything, since it is semantically irrelevant.
2363 Specialization
2364 = ClassTemplateSpecializationDecl::Create(Context,
2365 ClassTemplate->getDeclContext(),
2366 TemplateNameLoc,
2367 ClassTemplate,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002368 ConvertedTemplateArgs, 0);
Douglas Gregorff668032009-05-13 18:28:20 +00002369 Specialization->setLexicalDeclContext(CurContext);
2370 CurContext->addDecl(Context, Specialization);
2371 return DeclPtrTy::make(Specialization);
2372 }
2373
2374 // If we have already (implicitly) instantiated this
2375 // specialization, there is less work to do.
2376 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2377 SpecializationRequiresInstantiation = false;
2378
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002379 // Since the only prior class template specialization with these
2380 // arguments was referenced but not declared, reuse that
2381 // declaration node as our own, updating its source location to
2382 // reflect our new declaration.
2383 Specialization = PrevDecl;
2384 Specialization->setLocation(TemplateNameLoc);
2385 PrevDecl = 0;
2386 } else {
2387 // Create a new class template specialization declaration node for
2388 // this explicit specialization.
2389 Specialization
2390 = ClassTemplateSpecializationDecl::Create(Context,
2391 ClassTemplate->getDeclContext(),
2392 TemplateNameLoc,
2393 ClassTemplate,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002394 ConvertedTemplateArgs, 0);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002395
2396 ClassTemplate->getSpecializations().InsertNode(Specialization,
2397 InsertPos);
2398 }
2399
2400 // Build the fully-sugared type for this explicit instantiation as
2401 // the user wrote in the explicit instantiation itself. This means
2402 // that we'll pretty-print the type retrieved from the
2403 // specialization's declaration the way that the user actually wrote
2404 // the explicit instantiation, rather than formatting the name based
2405 // on the "canonical" representation used to store the template
2406 // arguments in the specialization.
2407 QualType WrittenTy
2408 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00002409 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002410 TemplateArgs.size(),
2411 Context.getTypeDeclType(Specialization));
2412 Specialization->setTypeAsWritten(WrittenTy);
2413 TemplateArgsIn.release();
2414
2415 // Add the explicit instantiation into its lexical context. However,
2416 // since explicit instantiations are never found by name lookup, we
2417 // just put it into the declaration context directly.
2418 Specialization->setLexicalDeclContext(CurContext);
2419 CurContext->addDecl(Context, Specialization);
2420
2421 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002422 // A definition of a class template or class member template
2423 // shall be in scope at the point of the explicit instantiation of
2424 // the class template or class member template.
2425 //
2426 // This check comes when we actually try to perform the
2427 // instantiation.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002428 if (SpecializationRequiresInstantiation)
2429 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002430 else // Instantiate the members of this class template specialization.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002431 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002432
2433 return DeclPtrTy::make(Specialization);
2434}
2435
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002436// Explicit instantiation of a member class of a class template.
2437Sema::DeclResult
2438Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2439 unsigned TagSpec,
2440 SourceLocation KWLoc,
2441 const CXXScopeSpec &SS,
2442 IdentifierInfo *Name,
2443 SourceLocation NameLoc,
2444 AttributeList *Attr) {
2445
Douglas Gregor402abb52009-05-28 23:31:59 +00002446 bool Owned = false;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002447 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor402abb52009-05-28 23:31:59 +00002448 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002449 if (!TagD)
2450 return true;
2451
2452 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2453 if (Tag->isEnum()) {
2454 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2455 << Context.getTypeDeclType(Tag);
2456 return true;
2457 }
2458
Douglas Gregord0c87372009-05-27 17:30:49 +00002459 if (Tag->isInvalidDecl())
2460 return true;
2461
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002462 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2463 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2464 if (!Pattern) {
2465 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2466 << Context.getTypeDeclType(Record);
2467 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2468 return true;
2469 }
2470
2471 // C++0x [temp.explicit]p2:
2472 // [...] An explicit instantiation shall appear in an enclosing
2473 // namespace of its template. [...]
2474 //
2475 // This is C++ DR 275.
2476 if (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002477 // FIXME: In C++98, we would like to turn these errors into warnings,
2478 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002479 DeclContext *PatternContext
2480 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2481 if (!CurContext->Encloses(PatternContext)) {
2482 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2483 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2484 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2485 }
2486 }
2487
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002488 if (!Record->getDefinition(Context)) {
2489 // If the class has a definition, instantiate it (and all of its
2490 // members, recursively).
2491 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2492 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002493 getTemplateInstantiationArgs(Record),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002494 /*ExplicitInstantiation=*/true))
2495 return true;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002496 } else // Instantiate all of the members of class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002497 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002498 getTemplateInstantiationArgs(Record));
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002499
Mike Stump390b4cc2009-05-16 07:39:55 +00002500 // FIXME: We don't have any representation for explicit instantiations of
2501 // member classes. Such a representation is not needed for compilation, but it
2502 // should be available for clients that want to see all of the declarations in
2503 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002504 return TagD;
2505}
2506
Douglas Gregord57959a2009-03-27 23:10:48 +00002507Sema::TypeResult
2508Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2509 const IdentifierInfo &II, SourceLocation IdLoc) {
2510 NestedNameSpecifier *NNS
2511 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2512 if (!NNS)
2513 return true;
2514
2515 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002516 if (T.isNull())
2517 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002518 return T.getAsOpaquePtr();
2519}
2520
Douglas Gregor17343172009-04-01 00:28:59 +00002521Sema::TypeResult
2522Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2523 SourceLocation TemplateLoc, TypeTy *Ty) {
2524 QualType T = QualType::getFromOpaquePtr(Ty);
2525 NestedNameSpecifier *NNS
2526 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2527 const TemplateSpecializationType *TemplateId
2528 = T->getAsTemplateSpecializationType();
2529 assert(TemplateId && "Expected a template specialization type");
2530
2531 if (NNS->isDependent())
2532 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2533
2534 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2535}
2536
Douglas Gregord57959a2009-03-27 23:10:48 +00002537/// \brief Build the type that describes a C++ typename specifier,
2538/// e.g., "typename T::type".
2539QualType
2540Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2541 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00002542 CXXRecordDecl *CurrentInstantiation = 0;
2543 if (NNS->isDependent()) {
2544 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00002545
Douglas Gregor42af25f2009-05-11 19:58:34 +00002546 // If the nested-name-specifier does not refer to the current
2547 // instantiation, then build a typename type.
2548 if (!CurrentInstantiation)
2549 return Context.getTypenameType(NNS, &II);
2550 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002551
Douglas Gregor42af25f2009-05-11 19:58:34 +00002552 DeclContext *Ctx = 0;
2553
2554 if (CurrentInstantiation)
2555 Ctx = CurrentInstantiation;
2556 else {
2557 CXXScopeSpec SS;
2558 SS.setScopeRep(NNS);
2559 SS.setRange(Range);
2560 if (RequireCompleteDeclContext(SS))
2561 return QualType();
2562
2563 Ctx = computeDeclContext(SS);
2564 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002565 assert(Ctx && "No declaration context?");
2566
2567 DeclarationName Name(&II);
2568 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2569 false);
2570 unsigned DiagID = 0;
2571 Decl *Referenced = 0;
2572 switch (Result.getKind()) {
2573 case LookupResult::NotFound:
2574 if (Ctx->isTranslationUnit())
2575 DiagID = diag::err_typename_nested_not_found_global;
2576 else
2577 DiagID = diag::err_typename_nested_not_found;
2578 break;
2579
2580 case LookupResult::Found:
2581 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2582 // We found a type. Build a QualifiedNameType, since the
2583 // typename-specifier was just sugar. FIXME: Tell
2584 // QualifiedNameType that it has a "typename" prefix.
2585 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2586 }
2587
2588 DiagID = diag::err_typename_nested_not_type;
2589 Referenced = Result.getAsDecl();
2590 break;
2591
2592 case LookupResult::FoundOverloaded:
2593 DiagID = diag::err_typename_nested_not_type;
2594 Referenced = *Result.begin();
2595 break;
2596
2597 case LookupResult::AmbiguousBaseSubobjectTypes:
2598 case LookupResult::AmbiguousBaseSubobjects:
2599 case LookupResult::AmbiguousReference:
2600 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2601 return QualType();
2602 }
2603
2604 // If we get here, it's because name lookup did not find a
2605 // type. Emit an appropriate diagnostic and return an error.
2606 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2607 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2608 else
2609 Diag(Range.getEnd(), DiagID) << Range << Name;
2610 if (Referenced)
2611 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2612 << Name;
2613 return QualType();
2614}