blob: 9ee4f3fcabd1dae1b8c7b9997d992959365fb5ca [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 Gregorc5c903a2009-06-24 00:23:40 +000070 // FIXME: What follows is a slightly less gross hack than what used to
71 // follow.
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000072 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregorc5c903a2009-06-24 00:23:40 +000073 if (FD->getDescribedFunctionTemplate()) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000074 TemplateResult = TemplateTy::make(FD);
Douglas Gregor55f6b142009-02-09 18:46:07 +000075 return TNK_Function_template;
76 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000077 } else if (OverloadedFunctionDecl *Ovl
78 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
79 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
80 FEnd = Ovl->function_end();
81 F != FEnd; ++F) {
Douglas Gregore53060f2009-06-25 22:08:12 +000082 if (isa<FunctionTemplateDecl>(*F)) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000083 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor55f6b142009-02-09 18:46:07 +000084 return TNK_Function_template;
85 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000086 }
87 }
Douglas Gregor7532dc62009-03-30 22:58:21 +000088
89 if (TNK != TNK_Non_template) {
90 if (SS && SS->isSet() && !SS->isInvalid()) {
91 NestedNameSpecifier *Qualifier
92 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
93 TemplateResult
94 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
95 false,
96 Template));
97 } else
98 TemplateResult = TemplateTy::make(TemplateName(Template));
99 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000100 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000101 return TNK;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000102}
103
Douglas Gregor72c3f312008-12-05 18:15:24 +0000104/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
105/// that the template parameter 'PrevDecl' is being shadowed by a new
106/// declaration at location Loc. Returns true to indicate that this is
107/// an error, and false otherwise.
108bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000109 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000110
111 // Microsoft Visual C++ permits template parameters to be shadowed.
112 if (getLangOptions().Microsoft)
113 return false;
114
115 // C++ [temp.local]p4:
116 // A template-parameter shall not be redeclared within its
117 // scope (including nested scopes).
118 Diag(Loc, diag::err_template_param_shadow)
119 << cast<NamedDecl>(PrevDecl)->getDeclName();
120 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
121 return true;
122}
123
Douglas Gregor2943aed2009-03-03 04:44:36 +0000124/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000125/// the parameter D to reference the templated declaration and return a pointer
126/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000127TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
128 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
129 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000130 return Temp;
131 }
132 return 0;
133}
134
Douglas Gregor72c3f312008-12-05 18:15:24 +0000135/// ActOnTypeParameter - Called when a C++ template type parameter
136/// (e.g., "typename T") has been parsed. Typename specifies whether
137/// the keyword "typename" was used to declare the type parameter
138/// (otherwise, "class" was used), and KeyLoc is the location of the
139/// "class" or "typename" keyword. ParamName is the name of the
140/// parameter (NULL indicates an unnamed template parameter) and
141/// ParamName is the location of the parameter name (if any).
142/// If the type parameter has a default argument, it will be added
143/// later via ActOnTypeParameterDefault.
Anders Carlsson941df7d2009-06-12 19:58:00 +0000144Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
145 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000146 SourceLocation KeyLoc,
147 IdentifierInfo *ParamName,
148 SourceLocation ParamNameLoc,
149 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000150 assert(S->isTemplateParamScope() &&
151 "Template type parameter not in template parameter scope!");
152 bool Invalid = false;
153
154 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000155 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000156 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000157 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
158 PrevDecl);
159 }
160
Douglas Gregorddc29e12009-02-06 22:42:48 +0000161 SourceLocation Loc = ParamNameLoc;
162 if (!ParamName)
163 Loc = KeyLoc;
164
Douglas Gregor72c3f312008-12-05 18:15:24 +0000165 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000166 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000167 Depth, Position, ParamName, Typename,
168 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000169 if (Invalid)
170 Param->setInvalidDecl();
171
172 if (ParamName) {
173 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000174 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000175 IdResolver.AddDecl(Param);
176 }
177
Chris Lattnerb28317a2009-03-28 19:18:32 +0000178 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000179}
180
Douglas Gregord684b002009-02-10 19:49:53 +0000181/// ActOnTypeParameterDefault - Adds a default argument (the type
182/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000183void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000184 SourceLocation EqualLoc,
185 SourceLocation DefaultLoc,
186 TypeTy *DefaultT) {
187 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000188 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000189 QualType Default = QualType::getFromOpaquePtr(DefaultT);
190
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000191 // C++0x [temp.param]p9:
192 // A default template-argument may be specified for any kind of
193 // template-parameter that is not a template parameter pack.
194 if (Parm->isParameterPack()) {
195 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000196 return;
197 }
198
Douglas Gregord684b002009-02-10 19:49:53 +0000199 // C++ [temp.param]p14:
200 // A template-parameter shall not be used in its own default argument.
201 // FIXME: Implement this check! Needs a recursive walk over the types.
202
203 // Check the template argument itself.
204 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
205 Parm->setInvalidDecl();
206 return;
207 }
208
209 Parm->setDefaultArgument(Default, DefaultLoc, false);
210}
211
Douglas Gregor2943aed2009-03-03 04:44:36 +0000212/// \brief Check that the type of a non-type template parameter is
213/// well-formed.
214///
215/// \returns the (possibly-promoted) parameter type if valid;
216/// otherwise, produces a diagnostic and returns a NULL type.
217QualType
218Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
219 // C++ [temp.param]p4:
220 //
221 // A non-type template-parameter shall have one of the following
222 // (optionally cv-qualified) types:
223 //
224 // -- integral or enumeration type,
225 if (T->isIntegralType() || T->isEnumeralType() ||
226 // -- pointer to object or pointer to function,
227 (T->isPointerType() &&
Ted Kremenek1a1a6e22009-07-16 19:58:26 +0000228 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
229 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Douglas Gregor2943aed2009-03-03 04:44:36 +0000230 // -- reference to object or reference to function,
231 T->isReferenceType() ||
232 // -- pointer to member.
233 T->isMemberPointerType() ||
234 // If T is a dependent type, we can't do the check now, so we
235 // assume that it is well-formed.
236 T->isDependentType())
237 return T;
238 // C++ [temp.param]p8:
239 //
240 // A non-type template-parameter of type "array of T" or
241 // "function returning T" is adjusted to be of type "pointer to
242 // T" or "pointer to function returning T", respectively.
243 else if (T->isArrayType())
244 // FIXME: Keep the type prior to promotion?
245 return Context.getArrayDecayedType(T);
246 else if (T->isFunctionType())
247 // FIXME: Keep the type prior to promotion?
248 return Context.getPointerType(T);
249
250 Diag(Loc, diag::err_template_nontype_parm_bad_type)
251 << T;
252
253 return QualType();
254}
255
Douglas Gregor72c3f312008-12-05 18:15:24 +0000256/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
257/// template parameter (e.g., "int Size" in "template<int Size>
258/// class Array") has been parsed. S is the current scope and D is
259/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000260Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
261 unsigned Depth,
262 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000263 QualType T = GetTypeForDeclarator(D, S);
264
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000265 assert(S->isTemplateParamScope() &&
266 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000267 bool Invalid = false;
268
269 IdentifierInfo *ParamName = D.getIdentifier();
270 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000271 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000272 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000273 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000274 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000275 }
276
Douglas Gregor2943aed2009-03-03 04:44:36 +0000277 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000278 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000279 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000280 Invalid = true;
281 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000282
Douglas Gregor72c3f312008-12-05 18:15:24 +0000283 NonTypeTemplateParmDecl *Param
284 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000285 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000286 if (Invalid)
287 Param->setInvalidDecl();
288
289 if (D.getIdentifier()) {
290 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000291 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000292 IdResolver.AddDecl(Param);
293 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000294 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000295}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000296
Douglas Gregord684b002009-02-10 19:49:53 +0000297/// \brief Adds a default argument to the given non-type template
298/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000299void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000300 SourceLocation EqualLoc,
301 ExprArg DefaultE) {
302 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000303 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000304 Expr *Default = static_cast<Expr *>(DefaultE.get());
305
306 // C++ [temp.param]p14:
307 // A template-parameter shall not be used in its own default argument.
308 // FIXME: Implement this check! Needs a recursive walk over the types.
309
310 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000311 TemplateArgument Converted;
312 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
313 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000314 TemplateParm->setInvalidDecl();
315 return;
316 }
317
Anders Carlssone9146f22009-05-01 19:49:17 +0000318 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000319}
320
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000321
322/// ActOnTemplateTemplateParameter - Called when a C++ template template
323/// parameter (e.g. T in template <template <typename> class T> class array)
324/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000325Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
326 SourceLocation TmpLoc,
327 TemplateParamsTy *Params,
328 IdentifierInfo *Name,
329 SourceLocation NameLoc,
330 unsigned Depth,
331 unsigned Position)
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000332{
333 assert(S->isTemplateParamScope() &&
334 "Template template parameter not in template parameter scope!");
335
336 // Construct the parameter object.
337 TemplateTemplateParmDecl *Param =
338 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
339 Position, Name,
340 (TemplateParameterList*)Params);
341
342 // Make sure the parameter is valid.
343 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
344 // do anything yet. However, if the template parameter list or (eventual)
345 // default value is ever invalidated, that will propagate here.
346 bool Invalid = false;
347 if (Invalid) {
348 Param->setInvalidDecl();
349 }
350
351 // If the tt-param has a name, then link the identifier into the scope
352 // and lookup mechanisms.
353 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000354 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000355 IdResolver.AddDecl(Param);
356 }
357
Chris Lattnerb28317a2009-03-28 19:18:32 +0000358 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000359}
360
Douglas Gregord684b002009-02-10 19:49:53 +0000361/// \brief Adds a default argument to the given template template
362/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000363void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000364 SourceLocation EqualLoc,
365 ExprArg DefaultE) {
366 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000367 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000368
369 // Since a template-template parameter's default argument is an
370 // id-expression, it must be a DeclRefExpr.
371 DeclRefExpr *Default
372 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
373
374 // C++ [temp.param]p14:
375 // A template-parameter shall not be used in its own default argument.
376 // FIXME: Implement this check! Needs a recursive walk over the types.
377
378 // Check the well-formedness of the template argument.
379 if (!isa<TemplateDecl>(Default->getDecl())) {
380 Diag(Default->getSourceRange().getBegin(),
381 diag::err_template_arg_must_be_template)
382 << Default->getSourceRange();
383 TemplateParm->setInvalidDecl();
384 return;
385 }
386 if (CheckTemplateArgument(TemplateParm, Default)) {
387 TemplateParm->setInvalidDecl();
388 return;
389 }
390
391 DefaultE.release();
392 TemplateParm->setDefaultArgument(Default);
393}
394
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000395/// ActOnTemplateParameterList - Builds a TemplateParameterList that
396/// contains the template parameters in Params/NumParams.
397Sema::TemplateParamsTy *
398Sema::ActOnTemplateParameterList(unsigned Depth,
399 SourceLocation ExportLoc,
400 SourceLocation TemplateLoc,
401 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000402 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000403 SourceLocation RAngleLoc) {
404 if (ExportLoc.isValid())
405 Diag(ExportLoc, diag::note_template_export_unsupported);
406
Douglas Gregorddc29e12009-02-06 22:42:48 +0000407 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
408 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000409}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000410
Douglas Gregor212e81c2009-03-25 00:13:59 +0000411Sema::DeclResult
Douglas Gregorddc29e12009-02-06 22:42:48 +0000412Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
413 SourceLocation KWLoc, const CXXScopeSpec &SS,
414 IdentifierInfo *Name, SourceLocation NameLoc,
415 AttributeList *Attr,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000416 MultiTemplateParamsArg TemplateParameterLists,
417 AccessSpecifier AS) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000418 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
419 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000420 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000421
422 // Check that we can declare a template here.
423 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000424 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000425
426 TagDecl::TagKind Kind;
427 switch (TagSpec) {
428 default: assert(0 && "Unknown tag type!");
429 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
430 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
431 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
432 }
433
434 // There is no such thing as an unnamed class template.
435 if (!Name) {
436 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000437 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000438 }
439
440 // Find any previous declaration with this name.
441 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
442 true);
443 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
444 NamedDecl *PrevDecl = 0;
445 if (Previous.begin() != Previous.end())
446 PrevDecl = *Previous.begin();
447
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000448 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
449 PrevDecl = 0;
450
Douglas Gregorddc29e12009-02-06 22:42:48 +0000451 DeclContext *SemanticContext = CurContext;
452 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000453 SemanticContext = computeDeclContext(SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000454
Mike Stump390b4cc2009-05-16 07:39:55 +0000455 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregorddc29e12009-02-06 22:42:48 +0000456 }
457
458 // FIXME: member templates!
459 TemplateParameterList *TemplateParams
460 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
461
462 // If there is a previous declaration with the same name, check
463 // whether this is a valid redeclaration.
464 ClassTemplateDecl *PrevClassTemplate
465 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
466 if (PrevClassTemplate) {
467 // Ensure that the template parameter lists are compatible.
468 if (!TemplateParameterListsAreEqual(TemplateParams,
469 PrevClassTemplate->getTemplateParameters(),
470 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000471 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000472
473 // C++ [temp.class]p4:
474 // In a redeclaration, partial specialization, explicit
475 // specialization or explicit instantiation of a class template,
476 // the class-key shall agree in kind with the original class
477 // template declaration (7.1.5.3).
478 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000479 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000480 Diag(KWLoc, diag::err_use_with_wrong_tag)
481 << Name
482 << CodeModificationHint::CreateReplacement(KWLoc,
483 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000484 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000485 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000486 }
487
Douglas Gregorddc29e12009-02-06 22:42:48 +0000488 // Check for redefinition of this class template.
489 if (TK == TK_Definition) {
490 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
491 Diag(NameLoc, diag::err_redefinition) << Name;
492 Diag(Def->getLocation(), diag::note_previous_definition);
493 // FIXME: Would it make sense to try to "forget" the previous
494 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000495 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000496 }
497 }
498 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
499 // Maybe we will complain about the shadowed template parameter.
500 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
501 // Just pretend that we didn't see the previous declaration.
502 PrevDecl = 0;
503 } else if (PrevDecl) {
504 // C++ [temp]p5:
505 // A class template shall not have the same name as any other
506 // template, class, function, object, enumeration, enumerator,
507 // namespace, or type in the same scope (3.3), except as specified
508 // in (14.5.4).
509 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
510 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000511 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000512 }
513
Douglas Gregord684b002009-02-10 19:49:53 +0000514 // Check the template parameter list of this declaration, possibly
515 // merging in the template parameter list from the previous class
516 // template declaration.
517 if (CheckTemplateParameterList(TemplateParams,
518 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
519 Invalid = true;
520
Douglas Gregor7da97d02009-05-10 22:57:19 +0000521 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000522 // declaration!
523
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000524 CXXRecordDecl *NewClass =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000525 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
526 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000527 PrevClassTemplate->getTemplatedDecl() : 0,
528 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000529
530 ClassTemplateDecl *NewTemplate
531 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
532 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000533 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000534 NewClass->setDescribedClassTemplate(NewTemplate);
535
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000536 // Build the type for the class template declaration now.
537 QualType T =
538 Context.getTypeDeclType(NewClass,
539 PrevClassTemplate?
540 PrevClassTemplate->getTemplatedDecl() : 0);
541 assert(T->isDependentType() && "Class template type is not dependent?");
542 (void)T;
543
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000544 // Set the access specifier.
545 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
546
Douglas Gregorddc29e12009-02-06 22:42:48 +0000547 // Set the lexical context of these templates
548 NewClass->setLexicalDeclContext(CurContext);
549 NewTemplate->setLexicalDeclContext(CurContext);
550
551 if (TK == TK_Definition)
552 NewClass->startDefinition();
553
554 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000555 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000556
557 PushOnScopeChains(NewTemplate, S);
558
Douglas Gregord684b002009-02-10 19:49:53 +0000559 if (Invalid) {
560 NewTemplate->setInvalidDecl();
561 NewClass->setInvalidDecl();
562 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000563 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000564}
565
Douglas Gregord684b002009-02-10 19:49:53 +0000566/// \brief Checks the validity of a template parameter list, possibly
567/// considering the template parameter list from a previous
568/// declaration.
569///
570/// If an "old" template parameter list is provided, it must be
571/// equivalent (per TemplateParameterListsAreEqual) to the "new"
572/// template parameter list.
573///
574/// \param NewParams Template parameter list for a new template
575/// declaration. This template parameter list will be updated with any
576/// default arguments that are carried through from the previous
577/// template parameter list.
578///
579/// \param OldParams If provided, template parameter list from a
580/// previous declaration of the same template. Default template
581/// arguments will be merged from the old template parameter list to
582/// the new template parameter list.
583///
584/// \returns true if an error occurred, false otherwise.
585bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
586 TemplateParameterList *OldParams) {
587 bool Invalid = false;
588
589 // C++ [temp.param]p10:
590 // The set of default template-arguments available for use with a
591 // template declaration or definition is obtained by merging the
592 // default arguments from the definition (if in scope) and all
593 // declarations in scope in the same way default function
594 // arguments are (8.3.6).
595 bool SawDefaultArgument = false;
596 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000597
Anders Carlsson49d25572009-06-12 23:20:15 +0000598 bool SawParameterPack = false;
599 SourceLocation ParameterPackLoc;
600
Mike Stump1a35fde2009-02-11 23:03:27 +0000601 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000602 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000603 if (OldParams)
604 OldParam = OldParams->begin();
605
606 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
607 NewParamEnd = NewParams->end();
608 NewParam != NewParamEnd; ++NewParam) {
609 // Variables used to diagnose redundant default arguments
610 bool RedundantDefaultArg = false;
611 SourceLocation OldDefaultLoc;
612 SourceLocation NewDefaultLoc;
613
614 // Variables used to diagnose missing default arguments
615 bool MissingDefaultArg = false;
616
Anders Carlsson49d25572009-06-12 23:20:15 +0000617 // C++0x [temp.param]p11:
618 // If a template parameter of a class template is a template parameter pack,
619 // it must be the last template parameter.
620 if (SawParameterPack) {
621 Diag(ParameterPackLoc,
622 diag::err_template_param_pack_must_be_last_template_parameter);
623 Invalid = true;
624 }
625
Douglas Gregord684b002009-02-10 19:49:53 +0000626 // Merge default arguments for template type parameters.
627 if (TemplateTypeParmDecl *NewTypeParm
628 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
629 TemplateTypeParmDecl *OldTypeParm
630 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
631
Anders Carlsson49d25572009-06-12 23:20:15 +0000632 if (NewTypeParm->isParameterPack()) {
633 assert(!NewTypeParm->hasDefaultArgument() &&
634 "Parameter packs can't have a default argument!");
635 SawParameterPack = true;
636 ParameterPackLoc = NewTypeParm->getLocation();
637 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000638 NewTypeParm->hasDefaultArgument()) {
639 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
640 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
641 SawDefaultArgument = true;
642 RedundantDefaultArg = true;
643 PreviousDefaultArgLoc = NewDefaultLoc;
644 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
645 // Merge the default argument from the old declaration to the
646 // new declaration.
647 SawDefaultArgument = true;
648 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
649 OldTypeParm->getDefaultArgumentLoc(),
650 true);
651 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
652 } else if (NewTypeParm->hasDefaultArgument()) {
653 SawDefaultArgument = true;
654 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
655 } else if (SawDefaultArgument)
656 MissingDefaultArg = true;
657 }
658 // Merge default arguments for non-type template parameters
659 else if (NonTypeTemplateParmDecl *NewNonTypeParm
660 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
661 NonTypeTemplateParmDecl *OldNonTypeParm
662 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
663 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
664 NewNonTypeParm->hasDefaultArgument()) {
665 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
666 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
667 SawDefaultArgument = true;
668 RedundantDefaultArg = true;
669 PreviousDefaultArgLoc = NewDefaultLoc;
670 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
671 // Merge the default argument from the old declaration to the
672 // new declaration.
673 SawDefaultArgument = true;
674 // FIXME: We need to create a new kind of "default argument"
675 // expression that points to a previous template template
676 // parameter.
677 NewNonTypeParm->setDefaultArgument(
678 OldNonTypeParm->getDefaultArgument());
679 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
680 } else if (NewNonTypeParm->hasDefaultArgument()) {
681 SawDefaultArgument = true;
682 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
683 } else if (SawDefaultArgument)
684 MissingDefaultArg = true;
685 }
686 // Merge default arguments for template template parameters
687 else {
688 TemplateTemplateParmDecl *NewTemplateParm
689 = cast<TemplateTemplateParmDecl>(*NewParam);
690 TemplateTemplateParmDecl *OldTemplateParm
691 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
692 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
693 NewTemplateParm->hasDefaultArgument()) {
694 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
695 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
696 SawDefaultArgument = true;
697 RedundantDefaultArg = true;
698 PreviousDefaultArgLoc = NewDefaultLoc;
699 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
700 // Merge the default argument from the old declaration to the
701 // new declaration.
702 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000703 // FIXME: We need to create a new kind of "default argument" expression
704 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000705 NewTemplateParm->setDefaultArgument(
706 OldTemplateParm->getDefaultArgument());
707 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
708 } else if (NewTemplateParm->hasDefaultArgument()) {
709 SawDefaultArgument = true;
710 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
711 } else if (SawDefaultArgument)
712 MissingDefaultArg = true;
713 }
714
715 if (RedundantDefaultArg) {
716 // C++ [temp.param]p12:
717 // A template-parameter shall not be given default arguments
718 // by two different declarations in the same scope.
719 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
720 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
721 Invalid = true;
722 } else if (MissingDefaultArg) {
723 // C++ [temp.param]p11:
724 // If a template-parameter has a default template-argument,
725 // all subsequent template-parameters shall have a default
726 // template-argument supplied.
727 Diag((*NewParam)->getLocation(),
728 diag::err_template_param_default_arg_missing);
729 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
730 Invalid = true;
731 }
732
733 // If we have an old template parameter list that we're merging
734 // in, move on to the next parameter.
735 if (OldParams)
736 ++OldParam;
737 }
738
739 return Invalid;
740}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000741
Douglas Gregor40808ce2009-03-09 23:48:35 +0000742/// \brief Translates template arguments as provided by the parser
743/// into template arguments used by semantic analysis.
744static void
745translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
746 SourceLocation *TemplateArgLocs,
747 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
748 TemplateArgs.reserve(TemplateArgsIn.size());
749
750 void **Args = TemplateArgsIn.getArgs();
751 bool *ArgIsType = TemplateArgsIn.getArgIsType();
752 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
753 TemplateArgs.push_back(
754 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
755 QualType::getFromOpaquePtr(Args[Arg]))
756 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
757 }
758}
759
Douglas Gregorc45c2322009-03-31 00:43:58 +0000760/// \brief Build a canonical version of a template argument list.
761///
762/// This function builds a canonical version of the given template
763/// argument list, where each of the template arguments has been
764/// converted into its canonical form. This routine is typically used
765/// to canonicalize a template argument list when the template name
766/// itself is dependent. When the template name refers to an actual
767/// template declaration, Sema::CheckTemplateArgumentList should be
768/// used to check and canonicalize the template arguments.
769///
770/// \param TemplateArgs The incoming template arguments.
771///
772/// \param NumTemplateArgs The number of template arguments in \p
773/// TemplateArgs.
774///
775/// \param Canonical A vector to be filled with the canonical versions
776/// of the template arguments.
777///
778/// \param Context The ASTContext in which the template arguments live.
779static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
780 unsigned NumTemplateArgs,
781 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
782 ASTContext &Context) {
783 Canonical.reserve(NumTemplateArgs);
784 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
785 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000786 case TemplateArgument::Null:
787 assert(false && "Should never see a NULL template argument here");
788 break;
789
Douglas Gregorc45c2322009-03-31 00:43:58 +0000790 case TemplateArgument::Expression:
791 // FIXME: Build canonical expression (!)
792 Canonical.push_back(TemplateArgs[Idx]);
793 break;
794
795 case TemplateArgument::Declaration:
Douglas Gregor7da97d02009-05-10 22:57:19 +0000796 Canonical.push_back(
797 TemplateArgument(SourceLocation(),
798 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregorc45c2322009-03-31 00:43:58 +0000799 break;
800
801 case TemplateArgument::Integral:
802 Canonical.push_back(TemplateArgument(SourceLocation(),
803 *TemplateArgs[Idx].getAsIntegral(),
804 TemplateArgs[Idx].getIntegralType()));
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000805 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000806
807 case TemplateArgument::Type: {
808 QualType CanonType
809 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
810 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000811 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000812 }
Anders Carlssond01b1da2009-06-15 17:04:53 +0000813
814 case TemplateArgument::Pack:
815 assert(0 && "FIXME: Implement!");
816 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000817 }
818 }
819}
820
Douglas Gregor7532dc62009-03-30 22:58:21 +0000821QualType Sema::CheckTemplateIdType(TemplateName Name,
822 SourceLocation TemplateLoc,
823 SourceLocation LAngleLoc,
824 const TemplateArgument *TemplateArgs,
825 unsigned NumTemplateArgs,
826 SourceLocation RAngleLoc) {
827 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +0000828 if (!Template) {
829 // The template name does not resolve to a template, so we just
830 // build a dependent template-id type.
831
832 // Canonicalize the template arguments to build the canonical
833 // template-id type.
834 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
835 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
836 CanonicalTemplateArgs, Context);
837
Douglas Gregor45fbaf02009-05-07 06:49:52 +0000838 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000839 QualType CanonType
Douglas Gregor45fbaf02009-05-07 06:49:52 +0000840 = Context.getTemplateSpecializationType(CanonName,
841 &CanonicalTemplateArgs[0],
Douglas Gregorc45c2322009-03-31 00:43:58 +0000842 CanonicalTemplateArgs.size());
843
844 // Build the dependent template-id type.
845 return Context.getTemplateSpecializationType(Name, TemplateArgs,
846 NumTemplateArgs, CanonType);
847 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000848
Douglas Gregor40808ce2009-03-09 23:48:35 +0000849 // Check that the template argument list is well-formed for this
850 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +0000851 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
852 NumTemplateArgs);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000853 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000854 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +0000855 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +0000856 return QualType();
857
Anders Carlssonfb250522009-06-23 01:26:57 +0000858 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000859 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000860 "Converted template argument list is too short!");
861
862 QualType CanonType;
863
Douglas Gregor7532dc62009-03-30 22:58:21 +0000864 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000865 TemplateArgs,
866 NumTemplateArgs)) {
867 // This class template specialization is a dependent
868 // type. Therefore, its canonical type is another class template
869 // specialization type that contains all of the converted
870 // arguments in canonical form. This ensures that, e.g., A<T> and
871 // A<T, T> have identical types when A is declared as:
872 //
873 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +0000874 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
875 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +0000876 Converted.getFlatArguments(),
877 Converted.flatSize());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000878 } else if (ClassTemplateDecl *ClassTemplate
879 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000880 // Find the class template specialization declaration that
881 // corresponds to these arguments.
882 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000883 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +0000884 Converted.getFlatArguments(),
885 Converted.flatSize());
Douglas Gregor40808ce2009-03-09 23:48:35 +0000886 void *InsertPos = 0;
887 ClassTemplateSpecializationDecl *Decl
888 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
889 if (!Decl) {
890 // This is the first time we have referenced this class template
891 // specialization. Create the canonical declaration and add it to
892 // the set of specializations.
893 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000894 ClassTemplate->getDeclContext(),
895 TemplateLoc,
896 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +0000897 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000898 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
899 Decl->setLexicalDeclContext(CurContext);
900 }
901
902 CanonType = Context.getTypeDeclType(Decl);
903 }
904
905 // Build the fully-sugared type for this class template
906 // specialization, which refers back to the class template
907 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +0000908 return Context.getTemplateSpecializationType(Name, TemplateArgs,
909 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000910}
911
Douglas Gregorcc636682009-02-17 23:15:12 +0000912Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +0000913Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
914 SourceLocation LAngleLoc,
915 ASTTemplateArgsPtr TemplateArgsIn,
916 SourceLocation *TemplateArgLocs,
917 SourceLocation RAngleLoc) {
918 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000919
Douglas Gregor40808ce2009-03-09 23:48:35 +0000920 // Translate the parser's template argument list in our AST format.
921 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
922 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000923
Douglas Gregor7532dc62009-03-30 22:58:21 +0000924 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000925 TemplateArgs.data(),
926 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +0000927 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000928 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000929
930 if (Result.isNull())
931 return true;
932
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000933 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000934}
935
Douglas Gregoredce4dd2009-06-30 22:34:41 +0000936Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
937 SourceLocation TemplateNameLoc,
938 SourceLocation LAngleLoc,
939 const TemplateArgument *TemplateArgs,
940 unsigned NumTemplateArgs,
941 SourceLocation RAngleLoc) {
942 // FIXME: Can we do any checking at this point? I guess we could check the
943 // template arguments that we have against the template name, if the template
944 // name refers to a single template. That's not a terribly common case,
945 // though.
946 return Owned(TemplateIdRefExpr::Create(Context,
947 /*FIXME: New type?*/Context.OverloadTy,
948 /*FIXME: Necessary?*/0,
949 /*FIXME: Necessary?*/SourceRange(),
950 Template, TemplateNameLoc, LAngleLoc,
951 TemplateArgs,
952 NumTemplateArgs, RAngleLoc));
953}
954
955Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
956 SourceLocation TemplateNameLoc,
957 SourceLocation LAngleLoc,
958 ASTTemplateArgsPtr TemplateArgsIn,
959 SourceLocation *TemplateArgLocs,
960 SourceLocation RAngleLoc) {
961 TemplateName Template = TemplateD.getAsVal<TemplateName>();
962
963 // Translate the parser's template argument list in our AST format.
964 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
965 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
966
967 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
968 TemplateArgs.data(), TemplateArgs.size(),
969 RAngleLoc);
970}
971
Douglas Gregorc45c2322009-03-31 00:43:58 +0000972/// \brief Form a dependent template name.
973///
974/// This action forms a dependent template name given the template
975/// name and its (presumably dependent) scope specifier. For
976/// example, given "MetaFun::template apply", the scope specifier \p
977/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
978/// of the "template" keyword, and "apply" is the \p Name.
979Sema::TemplateTy
980Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
981 const IdentifierInfo &Name,
982 SourceLocation NameLoc,
983 const CXXScopeSpec &SS) {
984 if (!SS.isSet() || SS.isInvalid())
985 return TemplateTy();
986
987 NestedNameSpecifier *Qualifier
988 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
989
990 // FIXME: member of the current instantiation
991
992 if (!Qualifier->isDependent()) {
993 // C++0x [temp.names]p5:
994 // If a name prefixed by the keyword template is not the name of
995 // a template, the program is ill-formed. [Note: the keyword
996 // template may not be applied to non-template members of class
997 // templates. -end note ] [ Note: as is the case with the
998 // typename prefix, the template prefix is allowed in cases
999 // where it is not strictly necessary; i.e., when the
1000 // nested-name-specifier or the expression on the left of the ->
1001 // or . is not dependent on a template-parameter, or the use
1002 // does not appear in the scope of a template. -end note]
1003 //
1004 // Note: C++03 was more strict here, because it banned the use of
1005 // the "template" keyword prior to a template-name that was not a
1006 // dependent name. C++ DR468 relaxed this requirement (the
1007 // "template" keyword is now permitted). We follow the C++0x
1008 // rules, even in C++03 mode, retroactively applying the DR.
1009 TemplateTy Template;
1010 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
1011 if (TNK == TNK_Non_template) {
1012 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1013 << &Name;
1014 return TemplateTy();
1015 }
1016
1017 return Template;
1018 }
1019
1020 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1021}
1022
Anders Carlsson436b1562009-06-13 00:33:33 +00001023bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1024 const TemplateArgument &Arg,
1025 TemplateArgumentListBuilder &Converted) {
1026 // Check template type parameter.
1027 if (Arg.getKind() != TemplateArgument::Type) {
1028 // C++ [temp.arg.type]p1:
1029 // A template-argument for a template-parameter which is a
1030 // type shall be a type-id.
1031
1032 // We have a template type parameter but the template argument
1033 // is not a type.
1034 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1035 Diag(Param->getLocation(), diag::note_template_param_here);
1036
1037 return true;
1038 }
1039
1040 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1041 return true;
1042
1043 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001044 Converted.Append(
Anders Carlsson436b1562009-06-13 00:33:33 +00001045 TemplateArgument(Arg.getLocation(),
1046 Context.getCanonicalType(Arg.getAsType())));
1047 return false;
1048}
1049
Douglas Gregorc15cb382009-02-09 23:23:08 +00001050/// \brief Check that the given template argument list is well-formed
1051/// for specializing the given template.
1052bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1053 SourceLocation TemplateLoc,
1054 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001055 const TemplateArgument *TemplateArgs,
1056 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001057 SourceLocation RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001058 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001059 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001060 TemplateParameterList *Params = Template->getTemplateParameters();
1061 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001062 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001063 bool Invalid = false;
1064
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001065 bool HasParameterPack =
1066 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1067
1068 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00001069 (NumArgs < Params->getMinRequiredArguments() &&
1070 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001071 // FIXME: point at either the first arg beyond what we can handle,
1072 // or the '>', depending on whether we have too many or too few
1073 // arguments.
1074 SourceRange Range;
1075 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001076 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001077 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1078 << (NumArgs > NumParams)
1079 << (isa<ClassTemplateDecl>(Template)? 0 :
1080 isa<FunctionTemplateDecl>(Template)? 1 :
1081 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1082 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001083 Diag(Template->getLocation(), diag::note_template_decl_here)
1084 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001085 Invalid = true;
1086 }
1087
1088 // C++ [temp.arg]p1:
1089 // [...] The type and form of each template-argument specified in
1090 // a template-id shall match the type and form specified for the
1091 // corresponding parameter declared by the template in its
1092 // template-parameter-list.
1093 unsigned ArgIdx = 0;
1094 for (TemplateParameterList::iterator Param = Params->begin(),
1095 ParamEnd = Params->end();
1096 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00001097 if (ArgIdx > NumArgs && PartialTemplateArgs)
1098 break;
1099
Douglas Gregorc15cb382009-02-09 23:23:08 +00001100 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001101 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001102 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001103 // Retrieve the default template argument from the template
1104 // parameter.
1105 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001106 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001107 // We have an empty argument pack.
1108 Converted.BeginPack();
1109 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001110 break;
1111 }
1112
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001113 if (!TTP->hasDefaultArgument())
1114 break;
1115
Douglas Gregor40808ce2009-03-09 23:48:35 +00001116 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001117
1118 // If the argument type is dependent, instantiate it now based
1119 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001120 if (ArgType->isDependentType()) {
1121 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001122 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001123 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001124 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001125
Anders Carlssone9c904b2009-06-05 04:47:51 +00001126 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001127 /*TakeArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001128 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor99ebf652009-02-27 19:31:52 +00001129 TTP->getDefaultArgumentLoc(),
1130 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001131 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001132
1133 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001134 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001135
Douglas Gregor40808ce2009-03-09 23:48:35 +00001136 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001137 } else if (NonTypeTemplateParmDecl *NTTP
1138 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1139 if (!NTTP->hasDefaultArgument())
1140 break;
1141
Anders Carlsson3b56c002009-06-11 16:06:49 +00001142 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001143 Template, Converted.getFlatArguments(),
Anders Carlsson3b56c002009-06-11 16:06:49 +00001144 Converted.flatSize(),
1145 SourceRange(TemplateLoc, RAngleLoc));
1146
1147 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001148 /*TakeArgs=*/false);
Anders Carlsson3b56c002009-06-11 16:06:49 +00001149
1150 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1151 TemplateArgs);
1152 if (E.isInvalid())
1153 return true;
1154
1155 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001156 } else {
1157 TemplateTemplateParmDecl *TempParm
1158 = cast<TemplateTemplateParmDecl>(*Param);
1159
1160 if (!TempParm->hasDefaultArgument())
1161 break;
1162
Douglas Gregor2943aed2009-03-03 04:44:36 +00001163 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001164 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001165 }
1166 } else {
1167 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001168 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001169 }
1170
Douglas Gregorc15cb382009-02-09 23:23:08 +00001171
1172 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001173 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001174 Converted.BeginPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001175 // Check all the remaining arguments (if any).
1176 for (; ArgIdx < NumArgs; ++ArgIdx) {
1177 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1178 Invalid = true;
1179 }
1180
Anders Carlssonfb250522009-06-23 01:26:57 +00001181 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001182 } else {
1183 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1184 Invalid = true;
1185 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001186 } else if (NonTypeTemplateParmDecl *NTTP
1187 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1188 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001189
1190 // Instantiate the type of the non-type template parameter with
1191 // the template arguments we've seen thus far.
1192 QualType NTTPType = NTTP->getType();
1193 if (NTTPType->isDependentType()) {
1194 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001195 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001196 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001197 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001198 SourceRange(TemplateLoc, RAngleLoc));
1199
Anders Carlssone9c904b2009-06-05 04:47:51 +00001200 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001201 /*TakeArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001202 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001203 NTTP->getLocation(),
1204 NTTP->getDeclName());
1205 // If that worked, check the non-type template parameter type
1206 // for validity.
1207 if (!NTTPType.isNull())
1208 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1209 NTTP->getLocation());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001210 if (NTTPType.isNull()) {
1211 Invalid = true;
1212 break;
1213 }
1214 }
1215
Douglas Gregor40808ce2009-03-09 23:48:35 +00001216 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001217 case TemplateArgument::Null:
1218 assert(false && "Should never see a NULL template argument here");
1219 break;
1220
Douglas Gregor40808ce2009-03-09 23:48:35 +00001221 case TemplateArgument::Expression: {
1222 Expr *E = Arg.getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001223 TemplateArgument Result;
1224 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001225 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001226 else
Anders Carlssonfb250522009-06-23 01:26:57 +00001227 Converted.Append(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001228 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001229 }
1230
Douglas Gregor40808ce2009-03-09 23:48:35 +00001231 case TemplateArgument::Declaration:
1232 case TemplateArgument::Integral:
1233 // We've already checked this template argument, so just copy
1234 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001235 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001236 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001237
Douglas Gregor40808ce2009-03-09 23:48:35 +00001238 case TemplateArgument::Type:
1239 // We have a non-type template parameter but the template
1240 // argument is a type.
1241
1242 // C++ [temp.arg]p2:
1243 // In a template-argument, an ambiguity between a type-id and
1244 // an expression is resolved to a type-id, regardless of the
1245 // form of the corresponding template-parameter.
1246 //
1247 // We warn specifically about this case, since it can be rather
1248 // confusing for users.
1249 if (Arg.getAsType()->isFunctionType())
1250 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1251 << Arg.getAsType();
1252 else
1253 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1254 Diag((*Param)->getLocation(), diag::note_template_param_here);
1255 Invalid = true;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001256 break;
1257
1258 case TemplateArgument::Pack:
1259 assert(0 && "FIXME: Implement!");
1260 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001261 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001262 } else {
1263 // Check template template parameters.
1264 TemplateTemplateParmDecl *TempParm
1265 = cast<TemplateTemplateParmDecl>(*Param);
1266
Douglas Gregor40808ce2009-03-09 23:48:35 +00001267 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001268 case TemplateArgument::Null:
1269 assert(false && "Should never see a NULL template argument here");
1270 break;
1271
Douglas Gregor40808ce2009-03-09 23:48:35 +00001272 case TemplateArgument::Expression: {
1273 Expr *ArgExpr = Arg.getAsExpr();
1274 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1275 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1276 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1277 Invalid = true;
1278
1279 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001280 Decl *D
1281 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
Anders Carlssonfb250522009-06-23 01:26:57 +00001282 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001283 continue;
1284 }
1285 }
1286 // fall through
1287
1288 case TemplateArgument::Type: {
1289 // We have a template template parameter but the template
1290 // argument does not refer to a template.
1291 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1292 Invalid = true;
1293 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001294 }
1295
Douglas Gregor40808ce2009-03-09 23:48:35 +00001296 case TemplateArgument::Declaration:
1297 // We've already checked this template argument, so just copy
1298 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001299 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001300 break;
1301
1302 case TemplateArgument::Integral:
1303 assert(false && "Integral argument with template template parameter");
1304 break;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001305
1306 case TemplateArgument::Pack:
1307 assert(0 && "FIXME: Implement!");
1308 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001309 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001310 }
1311 }
1312
1313 return Invalid;
1314}
1315
1316/// \brief Check a template argument against its corresponding
1317/// template type parameter.
1318///
1319/// This routine implements the semantics of C++ [temp.arg.type]. It
1320/// returns true if an error occurred, and false otherwise.
1321bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1322 QualType Arg, SourceLocation ArgLoc) {
1323 // C++ [temp.arg.type]p2:
1324 // A local type, a type with no linkage, an unnamed type or a type
1325 // compounded from any of these types shall not be used as a
1326 // template-argument for a template type-parameter.
1327 //
1328 // FIXME: Perform the recursive and no-linkage type checks.
1329 const TagType *Tag = 0;
1330 if (const EnumType *EnumT = Arg->getAsEnumType())
1331 Tag = EnumT;
Ted Kremenek5cad1f72009-07-17 01:20:38 +00001332 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001333 Tag = RecordT;
1334 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1335 return Diag(ArgLoc, diag::err_template_arg_local_type)
1336 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001337 else if (Tag && !Tag->getDecl()->getDeclName() &&
1338 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001339 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1340 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1341 return true;
1342 }
1343
1344 return false;
1345}
1346
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001347/// \brief Checks whether the given template argument is the address
1348/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001349bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1350 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001351 bool Invalid = false;
1352
1353 // See through any implicit casts we added to fix the type.
1354 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1355 Arg = Cast->getSubExpr();
1356
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001357 // C++0x allows nullptr, and there's no further checking to be done for that.
1358 if (Arg->getType()->isNullPtrType())
1359 return false;
1360
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001361 // C++ [temp.arg.nontype]p1:
1362 //
1363 // A template-argument for a non-type, non-template
1364 // template-parameter shall be one of: [...]
1365 //
1366 // -- the address of an object or function with external
1367 // linkage, including function templates and function
1368 // template-ids but excluding non-static class members,
1369 // expressed as & id-expression where the & is optional if
1370 // the name refers to a function or array, or if the
1371 // corresponding template-parameter is a reference; or
1372 DeclRefExpr *DRE = 0;
1373
1374 // Ignore (and complain about) any excess parentheses.
1375 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1376 if (!Invalid) {
1377 Diag(Arg->getSourceRange().getBegin(),
1378 diag::err_template_arg_extra_parens)
1379 << Arg->getSourceRange();
1380 Invalid = true;
1381 }
1382
1383 Arg = Parens->getSubExpr();
1384 }
1385
1386 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1387 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1388 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1389 } else
1390 DRE = dyn_cast<DeclRefExpr>(Arg);
1391
1392 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1393 return Diag(Arg->getSourceRange().getBegin(),
1394 diag::err_template_arg_not_object_or_func_form)
1395 << Arg->getSourceRange();
1396
1397 // Cannot refer to non-static data members
1398 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1399 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1400 << Field << Arg->getSourceRange();
1401
1402 // Cannot refer to non-static member functions
1403 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1404 if (!Method->isStatic())
1405 return Diag(Arg->getSourceRange().getBegin(),
1406 diag::err_template_arg_method)
1407 << Method << Arg->getSourceRange();
1408
1409 // Functions must have external linkage.
1410 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1411 if (Func->getStorageClass() == FunctionDecl::Static) {
1412 Diag(Arg->getSourceRange().getBegin(),
1413 diag::err_template_arg_function_not_extern)
1414 << Func << Arg->getSourceRange();
1415 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1416 << true;
1417 return true;
1418 }
1419
1420 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001421 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001422 return Invalid;
1423 }
1424
1425 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1426 if (!Var->hasGlobalStorage()) {
1427 Diag(Arg->getSourceRange().getBegin(),
1428 diag::err_template_arg_object_not_extern)
1429 << Var << Arg->getSourceRange();
1430 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1431 << true;
1432 return true;
1433 }
1434
1435 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001436 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001437 return Invalid;
1438 }
1439
1440 // We found something else, but we don't know specifically what it is.
1441 Diag(Arg->getSourceRange().getBegin(),
1442 diag::err_template_arg_not_object_or_func)
1443 << Arg->getSourceRange();
1444 Diag(DRE->getDecl()->getLocation(),
1445 diag::note_template_arg_refers_here);
1446 return true;
1447}
1448
1449/// \brief Checks whether the given template argument is a pointer to
1450/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001451bool
1452Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001453 bool Invalid = false;
1454
1455 // See through any implicit casts we added to fix the type.
1456 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1457 Arg = Cast->getSubExpr();
1458
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001459 // C++0x allows nullptr, and there's no further checking to be done for that.
1460 if (Arg->getType()->isNullPtrType())
1461 return false;
1462
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001463 // C++ [temp.arg.nontype]p1:
1464 //
1465 // A template-argument for a non-type, non-template
1466 // template-parameter shall be one of: [...]
1467 //
1468 // -- a pointer to member expressed as described in 5.3.1.
1469 QualifiedDeclRefExpr *DRE = 0;
1470
1471 // Ignore (and complain about) any excess parentheses.
1472 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1473 if (!Invalid) {
1474 Diag(Arg->getSourceRange().getBegin(),
1475 diag::err_template_arg_extra_parens)
1476 << Arg->getSourceRange();
1477 Invalid = true;
1478 }
1479
1480 Arg = Parens->getSubExpr();
1481 }
1482
1483 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1484 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1485 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1486
1487 if (!DRE)
1488 return Diag(Arg->getSourceRange().getBegin(),
1489 diag::err_template_arg_not_pointer_to_member_form)
1490 << Arg->getSourceRange();
1491
1492 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1493 assert((isa<FieldDecl>(DRE->getDecl()) ||
1494 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1495 "Only non-static member pointers can make it here");
1496
1497 // Okay: this is the address of a non-static member, and therefore
1498 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001499 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001500 return Invalid;
1501 }
1502
1503 // We found something else, but we don't know specifically what it is.
1504 Diag(Arg->getSourceRange().getBegin(),
1505 diag::err_template_arg_not_pointer_to_member_form)
1506 << Arg->getSourceRange();
1507 Diag(DRE->getDecl()->getLocation(),
1508 diag::note_template_arg_refers_here);
1509 return true;
1510}
1511
Douglas Gregorc15cb382009-02-09 23:23:08 +00001512/// \brief Check a template argument against its corresponding
1513/// non-type template parameter.
1514///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001515/// This routine implements the semantics of C++ [temp.arg.nontype].
1516/// It returns true if an error occurred, and false otherwise. \p
1517/// InstantiatedParamType is the type of the non-type template
1518/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001519///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001520/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001521bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001522 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001523 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001524 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1525
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001526 // If either the parameter has a dependent type or the argument is
1527 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001528 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001529 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1530 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001531 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001532 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001533 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001534
1535 // C++ [temp.arg.nontype]p5:
1536 // The following conversions are performed on each expression used
1537 // as a non-type template-argument. If a non-type
1538 // template-argument cannot be converted to the type of the
1539 // corresponding template-parameter then the program is
1540 // ill-formed.
1541 //
1542 // -- for a non-type template-parameter of integral or
1543 // enumeration type, integral promotions (4.5) and integral
1544 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001545 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001546 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001547 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001548 // C++ [temp.arg.nontype]p1:
1549 // A template-argument for a non-type, non-template
1550 // template-parameter shall be one of:
1551 //
1552 // -- an integral constant-expression of integral or enumeration
1553 // type; or
1554 // -- the name of a non-type template-parameter; or
1555 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001556 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001557 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1558 Diag(Arg->getSourceRange().getBegin(),
1559 diag::err_template_arg_not_integral_or_enumeral)
1560 << ArgType << Arg->getSourceRange();
1561 Diag(Param->getLocation(), diag::note_template_param_here);
1562 return true;
1563 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001564 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001565 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1566 << ArgType << Arg->getSourceRange();
1567 return true;
1568 }
1569
1570 // FIXME: We need some way to more easily get the unqualified form
1571 // of the types without going all the way to the
1572 // canonical type.
1573 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1574 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1575 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1576 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1577
1578 // Try to convert the argument to the parameter's type.
1579 if (ParamType == ArgType) {
1580 // Okay: no conversion necessary
1581 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1582 !ParamType->isEnumeralType()) {
1583 // This is an integral promotion or conversion.
1584 ImpCastExprToType(Arg, ParamType);
1585 } else {
1586 // We can't perform this conversion.
1587 Diag(Arg->getSourceRange().getBegin(),
1588 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001589 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001590 Diag(Param->getLocation(), diag::note_template_param_here);
1591 return true;
1592 }
1593
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001594 QualType IntegerType = Context.getCanonicalType(ParamType);
1595 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001596 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001597
1598 if (!Arg->isValueDependent()) {
1599 // Check that an unsigned parameter does not receive a negative
1600 // value.
1601 if (IntegerType->isUnsignedIntegerType()
1602 && (Value.isSigned() && Value.isNegative())) {
1603 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1604 << Value.toString(10) << Param->getType()
1605 << Arg->getSourceRange();
1606 Diag(Param->getLocation(), diag::note_template_param_here);
1607 return true;
1608 }
1609
1610 // Check that we don't overflow the template parameter type.
1611 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1612 if (Value.getActiveBits() > AllowedBits) {
1613 Diag(Arg->getSourceRange().getBegin(),
1614 diag::err_template_arg_too_large)
1615 << Value.toString(10) << Param->getType()
1616 << Arg->getSourceRange();
1617 Diag(Param->getLocation(), diag::note_template_param_here);
1618 return true;
1619 }
1620
1621 if (Value.getBitWidth() != AllowedBits)
1622 Value.extOrTrunc(AllowedBits);
1623 Value.setIsSigned(IntegerType->isSignedIntegerType());
1624 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001625
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001626 // Add the value of this argument to the list of converted
1627 // arguments. We use the bitwidth and signedness of the template
1628 // parameter.
1629 if (Arg->isValueDependent()) {
1630 // The argument is value-dependent. Create a new
1631 // TemplateArgument with the converted expression.
1632 Converted = TemplateArgument(Arg);
1633 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001634 }
1635
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001636 Converted = TemplateArgument(StartLoc, Value,
1637 ParamType->isEnumeralType() ? ParamType
1638 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001639 return false;
1640 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001641
Douglas Gregorb86b0572009-02-11 01:18:59 +00001642 // Handle pointer-to-function, reference-to-function, and
1643 // pointer-to-member-function all in (roughly) the same way.
1644 if (// -- For a non-type template-parameter of type pointer to
1645 // function, only the function-to-pointer conversion (4.3) is
1646 // applied. If the template-argument represents a set of
1647 // overloaded functions (or a pointer to such), the matching
1648 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001649 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001650 (ParamType->isPointerType() &&
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00001651 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001652 // -- For a non-type template-parameter of type reference to
1653 // function, no conversions apply. If the template-argument
1654 // represents a set of overloaded functions, the matching
1655 // function is selected from the set (13.4).
1656 (ParamType->isReferenceType() &&
Ted Kremenek808825c2009-07-17 01:01:15 +00001657 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001658 // -- For a non-type template-parameter of type pointer to
1659 // member function, no conversions apply. If the
1660 // template-argument represents a set of overloaded member
1661 // functions, the matching member function is selected from
1662 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001663 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001664 (ParamType->isMemberPointerType() &&
Ted Kremenek5cad1f72009-07-17 01:20:38 +00001665 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001666 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001667 if (Context.hasSameUnqualifiedType(ArgType,
1668 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001669 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001670 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1671 ParamType->isMemberPointerType())) {
1672 ArgType = ParamType;
1673 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001674 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001675 ArgType = Context.getPointerType(ArgType);
1676 ImpCastExprToType(Arg, ArgType);
1677 } else if (FunctionDecl *Fn
1678 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001679 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1680 return true;
1681
Douglas Gregora35284b2009-02-11 00:19:33 +00001682 FixOverloadedFunctionReference(Arg, Fn);
1683 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001684 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001685 ArgType = Context.getPointerType(Arg->getType());
1686 ImpCastExprToType(Arg, ArgType);
1687 }
1688 }
1689
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001690 if (!Context.hasSameUnqualifiedType(ArgType,
1691 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001692 // We can't perform this conversion.
1693 Diag(Arg->getSourceRange().getBegin(),
1694 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001695 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001696 Diag(Param->getLocation(), diag::note_template_param_here);
1697 return true;
1698 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001699
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001700 if (ParamType->isMemberPointerType()) {
1701 NamedDecl *Member = 0;
1702 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1703 return true;
1704
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001705 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1706 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001707 return false;
1708 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001709
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001710 NamedDecl *Entity = 0;
1711 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1712 return true;
1713
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001714 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1715 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001716 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001717 }
1718
Chris Lattnerfe90de72009-02-20 21:37:53 +00001719 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001720 // -- for a non-type template-parameter of type pointer to
1721 // object, qualification conversions (4.4) and the
1722 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001723 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00001724 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001725 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001726
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001727 if (ArgType->isNullPtrType()) {
1728 ArgType = ParamType;
1729 ImpCastExprToType(Arg, ParamType);
1730 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001731 ArgType = Context.getArrayDecayedType(ArgType);
1732 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001733 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001734
Douglas Gregorb86b0572009-02-11 01:18:59 +00001735 if (IsQualificationConversion(ArgType, ParamType)) {
1736 ArgType = ParamType;
1737 ImpCastExprToType(Arg, ParamType);
1738 }
1739
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001740 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001741 // We can't perform this conversion.
1742 Diag(Arg->getSourceRange().getBegin(),
1743 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001744 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001745 Diag(Param->getLocation(), diag::note_template_param_here);
1746 return true;
1747 }
1748
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001749 NamedDecl *Entity = 0;
1750 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1751 return true;
1752
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001753 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1754 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001755 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001756 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001757
Ted Kremenek808825c2009-07-17 01:01:15 +00001758 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001759 // -- For a non-type template-parameter of type reference to
1760 // object, no conversions apply. The type referred to by the
1761 // reference may be more cv-qualified than the (otherwise
1762 // identical) type of the template-argument. The
1763 // template-parameter is bound directly to the
1764 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001765 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001766 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001767
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001768 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001769 Diag(Arg->getSourceRange().getBegin(),
1770 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001771 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001772 << Arg->getSourceRange();
1773 Diag(Param->getLocation(), diag::note_template_param_here);
1774 return true;
1775 }
1776
1777 unsigned ParamQuals
1778 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1779 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1780
1781 if ((ParamQuals | ArgQuals) != ParamQuals) {
1782 Diag(Arg->getSourceRange().getBegin(),
1783 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001784 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001785 << Arg->getSourceRange();
1786 Diag(Param->getLocation(), diag::note_template_param_here);
1787 return true;
1788 }
1789
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001790 NamedDecl *Entity = 0;
1791 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1792 return true;
1793
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001794 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1795 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001796 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001797 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001798
1799 // -- For a non-type template-parameter of type pointer to data
1800 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001801 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00001802 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1803
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001804 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001805 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001806 } else if (ArgType->isNullPtrType()) {
1807 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00001808 } else if (IsQualificationConversion(ArgType, ParamType)) {
1809 ImpCastExprToType(Arg, ParamType);
1810 } else {
1811 // We can't perform this conversion.
1812 Diag(Arg->getSourceRange().getBegin(),
1813 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001814 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001815 Diag(Param->getLocation(), diag::note_template_param_here);
1816 return true;
1817 }
1818
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001819 NamedDecl *Member = 0;
1820 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1821 return true;
1822
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001823 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1824 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001825 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001826}
1827
1828/// \brief Check a template argument against its corresponding
1829/// template template parameter.
1830///
1831/// This routine implements the semantics of C++ [temp.arg.template].
1832/// It returns true if an error occurred, and false otherwise.
1833bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1834 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001835 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1836 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1837
1838 // C++ [temp.arg.template]p1:
1839 // A template-argument for a template template-parameter shall be
1840 // the name of a class template, expressed as id-expression. Only
1841 // primary class templates are considered when matching the
1842 // template template argument with the corresponding parameter;
1843 // partial specializations are not considered even if their
1844 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00001845 //
1846 // Note that we also allow template template parameters here, which
1847 // will happen when we are dealing with, e.g., class template
1848 // partial specializations.
1849 if (!isa<ClassTemplateDecl>(Template) &&
1850 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001851 assert(isa<FunctionTemplateDecl>(Template) &&
1852 "Only function templates are possible here");
Douglas Gregore53060f2009-06-25 22:08:12 +00001853 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1854 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001855 << Template;
1856 }
1857
1858 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1859 Param->getTemplateParameters(),
1860 true, true,
1861 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001862}
1863
Douglas Gregorddc29e12009-02-06 22:42:48 +00001864/// \brief Determine whether the given template parameter lists are
1865/// equivalent.
1866///
1867/// \param New The new template parameter list, typically written in the
1868/// source code as part of a new template declaration.
1869///
1870/// \param Old The old template parameter list, typically found via
1871/// name lookup of the template declared with this template parameter
1872/// list.
1873///
1874/// \param Complain If true, this routine will produce a diagnostic if
1875/// the template parameter lists are not equivalent.
1876///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001877/// \param IsTemplateTemplateParm If true, this routine is being
1878/// called to compare the template parameter lists of a template
1879/// template parameter.
1880///
1881/// \param TemplateArgLoc If this source location is valid, then we
1882/// are actually checking the template parameter list of a template
1883/// argument (New) against the template parameter list of its
1884/// corresponding template template parameter (Old). We produce
1885/// slightly different diagnostics in this scenario.
1886///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001887/// \returns True if the template parameter lists are equal, false
1888/// otherwise.
1889bool
1890Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1891 TemplateParameterList *Old,
1892 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001893 bool IsTemplateTemplateParm,
1894 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001895 if (Old->size() != New->size()) {
1896 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001897 unsigned NextDiag = diag::err_template_param_list_different_arity;
1898 if (TemplateArgLoc.isValid()) {
1899 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1900 NextDiag = diag::note_template_param_list_different_arity;
1901 }
1902 Diag(New->getTemplateLoc(), NextDiag)
1903 << (New->size() > Old->size())
1904 << IsTemplateTemplateParm
1905 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001906 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1907 << IsTemplateTemplateParm
1908 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1909 }
1910
1911 return false;
1912 }
1913
1914 for (TemplateParameterList::iterator OldParm = Old->begin(),
1915 OldParmEnd = Old->end(), NewParm = New->begin();
1916 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1917 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00001918 if (Complain) {
1919 unsigned NextDiag = diag::err_template_param_different_kind;
1920 if (TemplateArgLoc.isValid()) {
1921 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1922 NextDiag = diag::note_template_param_different_kind;
1923 }
1924 Diag((*NewParm)->getLocation(), NextDiag)
1925 << IsTemplateTemplateParm;
1926 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1927 << IsTemplateTemplateParm;
Douglas Gregordd0574e2009-02-10 00:24:35 +00001928 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00001929 return false;
1930 }
1931
1932 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1933 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00001934 // know we're at the same index).
1935#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00001936 // FIXME: Enable this code in debug mode *after* we properly go through
1937 // and "instantiate" the template parameter lists of template template
1938 // parameters. It's only after this instantiation that (1) any dependent
1939 // types within the template parameter list of the template template
1940 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00001941 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00001942 QualType OldParmType
1943 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1944 QualType NewParmType
1945 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1946 assert(Context.getCanonicalType(OldParmType) ==
1947 Context.getCanonicalType(NewParmType) &&
1948 "type parameter mismatch?");
1949#endif
1950 } else if (NonTypeTemplateParmDecl *OldNTTP
1951 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1952 // The types of non-type template parameters must agree.
1953 NonTypeTemplateParmDecl *NewNTTP
1954 = cast<NonTypeTemplateParmDecl>(*NewParm);
1955 if (Context.getCanonicalType(OldNTTP->getType()) !=
1956 Context.getCanonicalType(NewNTTP->getType())) {
1957 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001958 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1959 if (TemplateArgLoc.isValid()) {
1960 Diag(TemplateArgLoc,
1961 diag::err_template_arg_template_params_mismatch);
1962 NextDiag = diag::note_template_nontype_parm_different_type;
1963 }
1964 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001965 << NewNTTP->getType()
1966 << IsTemplateTemplateParm;
1967 Diag(OldNTTP->getLocation(),
1968 diag::note_template_nontype_parm_prev_declaration)
1969 << OldNTTP->getType();
1970 }
1971 return false;
1972 }
1973 } else {
1974 // The template parameter lists of template template
1975 // parameters must agree.
1976 // FIXME: Could we perform a faster "type" comparison here?
1977 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1978 "Only template template parameters handled here");
1979 TemplateTemplateParmDecl *OldTTP
1980 = cast<TemplateTemplateParmDecl>(*OldParm);
1981 TemplateTemplateParmDecl *NewTTP
1982 = cast<TemplateTemplateParmDecl>(*NewParm);
1983 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1984 OldTTP->getTemplateParameters(),
1985 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001986 /*IsTemplateTemplateParm=*/true,
1987 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00001988 return false;
1989 }
1990 }
1991
1992 return true;
1993}
1994
1995/// \brief Check whether a template can be declared within this scope.
1996///
1997/// If the template declaration is valid in this scope, returns
1998/// false. Otherwise, issues a diagnostic and returns true.
1999bool
2000Sema::CheckTemplateDeclScope(Scope *S,
2001 MultiTemplateParamsArg &TemplateParameterLists) {
2002 assert(TemplateParameterLists.size() > 0 && "Not a template");
2003
2004 // Find the nearest enclosing declaration scope.
2005 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2006 (S->getFlags() & Scope::TemplateParamScope) != 0)
2007 S = S->getParent();
2008
2009 TemplateParameterList *TemplateParams =
2010 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2011 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
2012 SourceRange TemplateRange
2013 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
2014
2015 // C++ [temp]p2:
2016 // A template-declaration can appear only as a namespace scope or
2017 // class scope declaration.
2018 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2019 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
2020 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2021 return Diag(TemplateLoc, diag::err_template_linkage)
2022 << TemplateRange;
2023
2024 Ctx = Ctx->getParent();
2025 }
2026
2027 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2028 return false;
2029
2030 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
2031 << TemplateRange;
2032}
Douglas Gregorcc636682009-02-17 23:15:12 +00002033
Douglas Gregorff668032009-05-13 18:28:20 +00002034/// \brief Check whether a class template specialization or explicit
2035/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00002036///
Douglas Gregorff668032009-05-13 18:28:20 +00002037/// This routine determines whether a class template specialization or
2038/// explicit instantiation can be declared in the current context
2039/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2040/// appropriate diagnostics if there was an error. It returns true if
2041// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00002042bool
2043Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2044 ClassTemplateSpecializationDecl *PrevDecl,
2045 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002046 SourceRange ScopeSpecifierRange,
Douglas Gregor16df8502009-06-12 22:21:45 +00002047 bool PartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002048 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002049 // C++ [temp.expl.spec]p2:
2050 // An explicit specialization shall be declared in the namespace
2051 // of which the template is a member, or, for member templates, in
2052 // the namespace of which the enclosing class or enclosing class
2053 // template is a member. An explicit specialization of a member
2054 // function, member class or static data member of a class
2055 // template shall be declared in the namespace of which the class
2056 // template is a member. Such a declaration may also be a
2057 // definition. If the declaration is not a definition, the
2058 // specialization may be defined later in the name- space in which
2059 // the explicit specialization was declared, or in a namespace
2060 // that encloses the one in which the explicit specialization was
2061 // declared.
2062 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor16df8502009-06-12 22:21:45 +00002063 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor88b70942009-02-25 22:02:03 +00002064 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002065 << Kind << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00002066 return true;
2067 }
2068
2069 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2070 DeclContext *TemplateContext
2071 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00002072 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2073 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002074 // There is no prior declaration of this entity, so this
2075 // specialization must be in the same context as the template
2076 // itself.
2077 if (DC != TemplateContext) {
2078 if (isa<TranslationUnitDecl>(TemplateContext))
2079 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor16df8502009-06-12 22:21:45 +00002080 << PartialSpecialization
Douglas Gregor88b70942009-02-25 22:02:03 +00002081 << ClassTemplate << ScopeSpecifierRange;
2082 else if (isa<NamespaceDecl>(TemplateContext))
2083 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002084 << PartialSpecialization << ClassTemplate
2085 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor88b70942009-02-25 22:02:03 +00002086
2087 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2088 }
2089
2090 return false;
2091 }
2092
2093 // We have a previous declaration of this entity. Make sure that
2094 // this redeclaration (or definition) occurs in an enclosing namespace.
2095 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002096 // FIXME: In C++98, we would like to turn these errors into warnings,
2097 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00002098 bool SuppressedDiag = false;
Douglas Gregor16df8502009-06-12 22:21:45 +00002099 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorff668032009-05-13 18:28:20 +00002100 if (isa<TranslationUnitDecl>(TemplateContext)) {
2101 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2102 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002103 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorff668032009-05-13 18:28:20 +00002104 else
2105 SuppressedDiag = true;
2106 } else if (isa<NamespaceDecl>(TemplateContext)) {
2107 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2108 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002109 << Kind << ClassTemplate
Douglas Gregorff668032009-05-13 18:28:20 +00002110 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2111 else
2112 SuppressedDiag = true;
2113 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002114
Douglas Gregorff668032009-05-13 18:28:20 +00002115 if (!SuppressedDiag)
2116 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00002117 }
2118
2119 return false;
2120}
2121
Douglas Gregore94866f2009-06-12 21:21:02 +00002122/// \brief Check the non-type template arguments of a class template
2123/// partial specialization according to C++ [temp.class.spec]p9.
2124///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002125/// \param TemplateParams the template parameters of the primary class
2126/// template.
2127///
2128/// \param TemplateArg the template arguments of the class template
2129/// partial specialization.
2130///
2131/// \param MirrorsPrimaryTemplate will be set true if the class
2132/// template partial specialization arguments are identical to the
2133/// implicit template arguments of the primary template. This is not
2134/// necessarily an error (C++0x), and it is left to the caller to diagnose
2135/// this condition when it is an error.
2136///
Douglas Gregore94866f2009-06-12 21:21:02 +00002137/// \returns true if there was an error, false otherwise.
2138bool Sema::CheckClassTemplatePartialSpecializationArgs(
2139 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002140 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002141 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002142 // FIXME: the interface to this function will have to change to
2143 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002144 MirrorsPrimaryTemplate = true;
Anders Carlsson6360be72009-06-13 18:20:51 +00002145
Anders Carlssonfb250522009-06-23 01:26:57 +00002146 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson6360be72009-06-13 18:20:51 +00002147
Douglas Gregore94866f2009-06-12 21:21:02 +00002148 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002149 // Determine whether the template argument list of the partial
2150 // specialization is identical to the implicit argument list of
2151 // the primary template. The caller may need to diagnostic this as
2152 // an error per C++ [temp.class.spec]p9b3.
2153 if (MirrorsPrimaryTemplate) {
2154 if (TemplateTypeParmDecl *TTP
2155 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2156 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002157 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002158 MirrorsPrimaryTemplate = false;
2159 } else if (TemplateTemplateParmDecl *TTP
2160 = dyn_cast<TemplateTemplateParmDecl>(
2161 TemplateParams->getParam(I))) {
2162 // FIXME: We should settle on either Declaration storage or
2163 // Expression storage for template template parameters.
2164 TemplateTemplateParmDecl *ArgDecl
2165 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson6360be72009-06-13 18:20:51 +00002166 ArgList[I].getAsDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002167 if (!ArgDecl)
2168 if (DeclRefExpr *DRE
Anders Carlsson6360be72009-06-13 18:20:51 +00002169 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002170 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2171
2172 if (!ArgDecl ||
2173 ArgDecl->getIndex() != TTP->getIndex() ||
2174 ArgDecl->getDepth() != TTP->getDepth())
2175 MirrorsPrimaryTemplate = false;
2176 }
2177 }
2178
Douglas Gregore94866f2009-06-12 21:21:02 +00002179 NonTypeTemplateParmDecl *Param
2180 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002181 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002182 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002183 }
2184
Anders Carlsson6360be72009-06-13 18:20:51 +00002185 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002186 if (!ArgExpr) {
2187 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002188 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002189 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002190
2191 // C++ [temp.class.spec]p8:
2192 // A non-type argument is non-specialized if it is the name of a
2193 // non-type parameter. All other non-type arguments are
2194 // specialized.
2195 //
2196 // Below, we check the two conditions that only apply to
2197 // specialized non-type arguments, so skip any non-specialized
2198 // arguments.
2199 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002200 if (NonTypeTemplateParmDecl *NTTP
2201 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2202 if (MirrorsPrimaryTemplate &&
2203 (Param->getIndex() != NTTP->getIndex() ||
2204 Param->getDepth() != NTTP->getDepth()))
2205 MirrorsPrimaryTemplate = false;
2206
Douglas Gregore94866f2009-06-12 21:21:02 +00002207 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002208 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002209
2210 // C++ [temp.class.spec]p9:
2211 // Within the argument list of a class template partial
2212 // specialization, the following restrictions apply:
2213 // -- A partially specialized non-type argument expression
2214 // shall not involve a template parameter of the partial
2215 // specialization except when the argument expression is a
2216 // simple identifier.
2217 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2218 Diag(ArgExpr->getLocStart(),
2219 diag::err_dependent_non_type_arg_in_partial_spec)
2220 << ArgExpr->getSourceRange();
2221 return true;
2222 }
2223
2224 // -- The type of a template parameter corresponding to a
2225 // specialized non-type argument shall not be dependent on a
2226 // parameter of the specialization.
2227 if (Param->getType()->isDependentType()) {
2228 Diag(ArgExpr->getLocStart(),
2229 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2230 << Param->getType()
2231 << ArgExpr->getSourceRange();
2232 Diag(Param->getLocation(), diag::note_template_param_here);
2233 return true;
2234 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002235
2236 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002237 }
2238
2239 return false;
2240}
2241
Douglas Gregor212e81c2009-03-25 00:13:59 +00002242Sema::DeclResult
Douglas Gregorcc636682009-02-17 23:15:12 +00002243Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2244 SourceLocation KWLoc,
2245 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002246 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002247 SourceLocation TemplateNameLoc,
2248 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002249 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002250 SourceLocation *TemplateArgLocs,
2251 SourceLocation RAngleLoc,
2252 AttributeList *Attr,
2253 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002254 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002255 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002256 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002257 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002258
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002259 bool isPartialSpecialization = false;
2260
Douglas Gregor88b70942009-02-25 22:02:03 +00002261 // Check the validity of the template headers that introduce this
2262 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002263 // FIXME: Once we have member templates, we'll need to check
2264 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2265 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002266 if (TemplateParameterLists.size() == 0)
2267 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00002268 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002269 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00002270 TemplateParameterList *TemplateParams
2271 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattnerb28317a2009-03-28 19:18:32 +00002272 if (TemplateParameterLists.size() > 1) {
2273 Diag(TemplateParams->getTemplateLoc(),
2274 diag::err_template_spec_extra_headers);
2275 return true;
2276 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002277
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002278 if (TemplateParams->size() > 0) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002279 isPartialSpecialization = true;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002280
2281 // C++ [temp.class.spec]p10:
2282 // The template parameter list of a specialization shall not
2283 // contain default template argument values.
2284 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2285 Decl *Param = TemplateParams->getParam(I);
2286 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2287 if (TTP->hasDefaultArgument()) {
2288 Diag(TTP->getDefaultArgumentLoc(),
2289 diag::err_default_arg_in_partial_spec);
2290 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2291 }
2292 } else if (NonTypeTemplateParmDecl *NTTP
2293 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2294 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2295 Diag(NTTP->getDefaultArgumentLoc(),
2296 diag::err_default_arg_in_partial_spec)
2297 << DefArg->getSourceRange();
2298 NTTP->setDefaultArgument(0);
2299 DefArg->Destroy(Context);
2300 }
2301 } else {
2302 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2303 if (Expr *DefArg = TTP->getDefaultArgument()) {
2304 Diag(TTP->getDefaultArgumentLoc(),
2305 diag::err_default_arg_in_partial_spec)
2306 << DefArg->getSourceRange();
2307 TTP->setDefaultArgument(0);
2308 DefArg->Destroy(Context);
2309 }
2310 }
2311 }
2312 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002313 }
2314
Douglas Gregorcc636682009-02-17 23:15:12 +00002315 // Check that the specialization uses the same tag kind as the
2316 // original template.
2317 TagDecl::TagKind Kind;
2318 switch (TagSpec) {
2319 default: assert(0 && "Unknown tag type!");
2320 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2321 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2322 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2323 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002324 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2325 Kind, KWLoc,
2326 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002327 Diag(KWLoc, diag::err_use_with_wrong_tag)
2328 << ClassTemplate
2329 << CodeModificationHint::CreateReplacement(KWLoc,
2330 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002331 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2332 diag::note_previous_use);
2333 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2334 }
2335
Douglas Gregor40808ce2009-03-09 23:48:35 +00002336 // Translate the parser's template argument list in our AST format.
2337 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2338 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2339
Douglas Gregorcc636682009-02-17 23:15:12 +00002340 // Check that the template argument list is well-formed for this
2341 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002342 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2343 TemplateArgs.size());
Douglas Gregorcc636682009-02-17 23:15:12 +00002344 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00002345 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002346 RAngleLoc, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002347 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002348
Anders Carlssonfb250522009-06-23 01:26:57 +00002349 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00002350 ClassTemplate->getTemplateParameters()->size()) &&
2351 "Converted template argument list is too short!");
2352
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002353 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002354 // corresponds to these arguments.
2355 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002356 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002357 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00002358 if (CheckClassTemplatePartialSpecializationArgs(
2359 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00002360 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00002361 return true;
2362
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002363 if (MirrorsPrimaryTemplate) {
2364 // C++ [temp.class.spec]p9b3:
2365 //
2366 // -- The argument list of the specialization shall not be identical
2367 // to the implicit argument list of the primary template.
2368 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2369 << (TK == TK_Definition)
2370 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2371 RAngleLoc));
2372 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2373 ClassTemplate->getIdentifier(),
2374 TemplateNameLoc,
2375 Attr,
2376 move(TemplateParameterLists),
2377 AS_none);
2378 }
2379
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002380 // FIXME: Template parameter list matters, too
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002381 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002382 Converted.getFlatArguments(),
2383 Converted.flatSize());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002384 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002385 else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002386 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002387 Converted.getFlatArguments(),
2388 Converted.flatSize());
Douglas Gregorcc636682009-02-17 23:15:12 +00002389 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002390 ClassTemplateSpecializationDecl *PrevDecl = 0;
2391
2392 if (isPartialSpecialization)
2393 PrevDecl
2394 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2395 InsertPos);
2396 else
2397 PrevDecl
2398 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002399
2400 ClassTemplateSpecializationDecl *Specialization = 0;
2401
Douglas Gregor88b70942009-02-25 22:02:03 +00002402 // Check whether we can declare a class template specialization in
2403 // the current scope.
2404 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2405 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002406 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002407 isPartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002408 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002409 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002410
Douglas Gregorcc636682009-02-17 23:15:12 +00002411 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2412 // Since the only prior class template specialization with these
2413 // arguments was referenced but not declared, reuse that
2414 // declaration node as our own, updating its source location to
2415 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002416 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002417 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002418 PrevDecl = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002419 } else if (isPartialSpecialization) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002420 // Create a new class template partial specialization declaration node.
2421 TemplateParameterList *TemplateParams
2422 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2423 ClassTemplatePartialSpecializationDecl *PrevPartial
2424 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2425 ClassTemplatePartialSpecializationDecl *Partial
2426 = ClassTemplatePartialSpecializationDecl::Create(Context,
2427 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002428 TemplateNameLoc,
2429 TemplateParams,
2430 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002431 Converted,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002432 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002433
2434 if (PrevPartial) {
2435 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2436 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2437 } else {
2438 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2439 }
2440 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00002441
2442 // Check that all of the template parameters of the class template
2443 // partial specialization are deducible from the template
2444 // arguments. If not, this class template partial specialization
2445 // will never be used.
2446 llvm::SmallVector<bool, 8> DeducibleParams;
2447 DeducibleParams.resize(TemplateParams->size());
2448 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2449 unsigned NumNonDeducible = 0;
2450 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2451 if (!DeducibleParams[I])
2452 ++NumNonDeducible;
2453
2454 if (NumNonDeducible) {
2455 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2456 << (NumNonDeducible > 1)
2457 << SourceRange(TemplateNameLoc, RAngleLoc);
2458 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2459 if (!DeducibleParams[I]) {
2460 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2461 if (Param->getDeclName())
2462 Diag(Param->getLocation(),
2463 diag::note_partial_spec_unused_parameter)
2464 << Param->getDeclName();
2465 else
2466 Diag(Param->getLocation(),
2467 diag::note_partial_spec_unused_parameter)
2468 << std::string("<anonymous>");
2469 }
2470 }
2471 }
2472
Douglas Gregorcc636682009-02-17 23:15:12 +00002473 } else {
2474 // Create a new class template specialization declaration node for
2475 // this explicit specialization.
2476 Specialization
2477 = ClassTemplateSpecializationDecl::Create(Context,
2478 ClassTemplate->getDeclContext(),
2479 TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002480 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002481 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00002482 PrevDecl);
2483
2484 if (PrevDecl) {
2485 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2486 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2487 } else {
2488 ClassTemplate->getSpecializations().InsertNode(Specialization,
2489 InsertPos);
2490 }
2491 }
2492
2493 // Note that this is an explicit specialization.
2494 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2495
2496 // Check that this isn't a redefinition of this specialization.
2497 if (TK == TK_Definition) {
2498 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002499 // FIXME: Should also handle explicit specialization after implicit
2500 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002501 SourceRange Range(TemplateNameLoc, RAngleLoc);
2502 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002503 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002504 Diag(Def->getLocation(), diag::note_previous_definition);
2505 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002506 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002507 }
2508 }
2509
Douglas Gregorfc705b82009-02-26 22:19:44 +00002510 // Build the fully-sugared type for this class template
2511 // specialization as the user wrote in the specialization
2512 // itself. This means that we'll pretty-print the type retrieved
2513 // from the specialization's declaration the way that the user
2514 // actually wrote the specialization, rather than formatting the
2515 // name based on the "canonical" representation used to store the
2516 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002517 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002518 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00002519 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00002520 TemplateArgs.size(),
Douglas Gregore6258932009-03-19 00:39:20 +00002521 Context.getTypeDeclType(Specialization));
Douglas Gregor7532dc62009-03-30 22:58:21 +00002522 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002523 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002524
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002525 // C++ [temp.expl.spec]p9:
2526 // A template explicit specialization is in the scope of the
2527 // namespace in which the template was defined.
2528 //
2529 // We actually implement this paragraph where we set the semantic
2530 // context (in the creation of the ClassTemplateSpecializationDecl),
2531 // but we also maintain the lexical context where the actual
2532 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002533 Specialization->setLexicalDeclContext(CurContext);
2534
2535 // We may be starting the definition of this specialization.
2536 if (TK == TK_Definition)
2537 Specialization->startDefinition();
2538
2539 // Add the specialization into its lexical context, so that it can
2540 // be seen when iterating through the list of declarations in that
2541 // context. However, specializations are not found by name lookup.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002542 CurContext->addDecl(Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002543 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002544}
Douglas Gregord57959a2009-03-27 23:10:48 +00002545
Douglas Gregore542c862009-06-23 23:11:28 +00002546Sema::DeclPtrTy
2547Sema::ActOnTemplateDeclarator(Scope *S,
2548 MultiTemplateParamsArg TemplateParameterLists,
2549 Declarator &D) {
2550 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2551}
2552
Douglas Gregor52591bf2009-06-24 00:54:41 +00002553Sema::DeclPtrTy
2554Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2555 MultiTemplateParamsArg TemplateParameterLists,
2556 Declarator &D) {
2557 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2558 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2559 "Not a function declarator!");
2560 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2561
2562 if (FTI.hasPrototype) {
2563 // FIXME: Diagnose arguments without names in C.
2564 }
2565
2566 Scope *ParentScope = FnBodyScope->getParent();
2567
2568 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2569 move(TemplateParameterLists),
2570 /*IsFunctionDefinition=*/true);
Douglas Gregore53060f2009-06-25 22:08:12 +00002571 FunctionTemplateDecl *FunctionTemplate
2572 = cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>());
2573 if (FunctionTemplate)
2574 return ActOnStartOfFunctionDef(FnBodyScope,
2575 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
2576
2577 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00002578}
2579
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002580// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002581Sema::DeclResult
2582Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2583 unsigned TagSpec,
2584 SourceLocation KWLoc,
2585 const CXXScopeSpec &SS,
2586 TemplateTy TemplateD,
2587 SourceLocation TemplateNameLoc,
2588 SourceLocation LAngleLoc,
2589 ASTTemplateArgsPtr TemplateArgsIn,
2590 SourceLocation *TemplateArgLocs,
2591 SourceLocation RAngleLoc,
2592 AttributeList *Attr) {
2593 // Find the class template we're specializing
2594 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2595 ClassTemplateDecl *ClassTemplate
2596 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2597
2598 // Check that the specialization uses the same tag kind as the
2599 // original template.
2600 TagDecl::TagKind Kind;
2601 switch (TagSpec) {
2602 default: assert(0 && "Unknown tag type!");
2603 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2604 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2605 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2606 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002607 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2608 Kind, KWLoc,
2609 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002610 Diag(KWLoc, diag::err_use_with_wrong_tag)
2611 << ClassTemplate
2612 << CodeModificationHint::CreateReplacement(KWLoc,
2613 ClassTemplate->getTemplatedDecl()->getKindName());
2614 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2615 diag::note_previous_use);
2616 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2617 }
2618
Douglas Gregorff668032009-05-13 18:28:20 +00002619 // C++0x [temp.explicit]p2:
2620 // [...] An explicit instantiation shall appear in an enclosing
2621 // namespace of its template. [...]
2622 //
2623 // This is C++ DR 275.
2624 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2625 TemplateNameLoc,
2626 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002627 /*PartialSpecialization=*/false,
Douglas Gregorff668032009-05-13 18:28:20 +00002628 /*ExplicitInstantiation=*/true))
2629 return true;
2630
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002631 // Translate the parser's template argument list in our AST format.
2632 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2633 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2634
2635 // Check that the template argument list is well-formed for this
2636 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002637 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2638 TemplateArgs.size());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002639 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00002640 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002641 RAngleLoc, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002642 return true;
2643
Anders Carlssonfb250522009-06-23 01:26:57 +00002644 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002645 ClassTemplate->getTemplateParameters()->size()) &&
2646 "Converted template argument list is too short!");
2647
2648 // Find the class template specialization declaration that
2649 // corresponds to these arguments.
2650 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002651 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002652 Converted.getFlatArguments(),
2653 Converted.flatSize());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002654 void *InsertPos = 0;
2655 ClassTemplateSpecializationDecl *PrevDecl
2656 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2657
2658 ClassTemplateSpecializationDecl *Specialization = 0;
2659
Douglas Gregorff668032009-05-13 18:28:20 +00002660 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002661 if (PrevDecl) {
Douglas Gregorff668032009-05-13 18:28:20 +00002662 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002663 // This particular specialization has already been declared or
2664 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002665 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2666 << Context.getTypeDeclType(PrevDecl);
2667 Diag(PrevDecl->getLocation(),
2668 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002669 return DeclPtrTy::make(PrevDecl);
2670 }
2671
Douglas Gregorff668032009-05-13 18:28:20 +00002672 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002673 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002674 // For a given set of template parameters, if an explicit
2675 // instantiation of a template appears after a declaration of
2676 // an explicit specialization for that template, the explicit
2677 // instantiation has no effect.
2678 if (!getLangOptions().CPlusPlus0x) {
2679 Diag(TemplateNameLoc,
2680 diag::ext_explicit_instantiation_after_specialization)
2681 << Context.getTypeDeclType(PrevDecl);
2682 Diag(PrevDecl->getLocation(),
2683 diag::note_previous_template_specialization);
2684 }
2685
2686 // Create a new class template specialization declaration node
2687 // for this explicit specialization. This node is only used to
2688 // record the existence of this explicit instantiation for
2689 // accurate reproduction of the source code; we don't actually
2690 // use it for anything, since it is semantically irrelevant.
2691 Specialization
2692 = ClassTemplateSpecializationDecl::Create(Context,
2693 ClassTemplate->getDeclContext(),
2694 TemplateNameLoc,
2695 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002696 Converted, 0);
Douglas Gregorff668032009-05-13 18:28:20 +00002697 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002698 CurContext->addDecl(Specialization);
Douglas Gregorff668032009-05-13 18:28:20 +00002699 return DeclPtrTy::make(Specialization);
2700 }
2701
2702 // If we have already (implicitly) instantiated this
2703 // specialization, there is less work to do.
2704 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2705 SpecializationRequiresInstantiation = false;
2706
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002707 // Since the only prior class template specialization with these
2708 // arguments was referenced but not declared, reuse that
2709 // declaration node as our own, updating its source location to
2710 // reflect our new declaration.
2711 Specialization = PrevDecl;
2712 Specialization->setLocation(TemplateNameLoc);
2713 PrevDecl = 0;
2714 } else {
2715 // Create a new class template specialization declaration node for
2716 // this explicit specialization.
2717 Specialization
2718 = ClassTemplateSpecializationDecl::Create(Context,
2719 ClassTemplate->getDeclContext(),
2720 TemplateNameLoc,
2721 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002722 Converted, 0);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002723
2724 ClassTemplate->getSpecializations().InsertNode(Specialization,
2725 InsertPos);
2726 }
2727
2728 // Build the fully-sugared type for this explicit instantiation as
2729 // the user wrote in the explicit instantiation itself. This means
2730 // that we'll pretty-print the type retrieved from the
2731 // specialization's declaration the way that the user actually wrote
2732 // the explicit instantiation, rather than formatting the name based
2733 // on the "canonical" representation used to store the template
2734 // arguments in the specialization.
2735 QualType WrittenTy
2736 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00002737 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002738 TemplateArgs.size(),
2739 Context.getTypeDeclType(Specialization));
2740 Specialization->setTypeAsWritten(WrittenTy);
2741 TemplateArgsIn.release();
2742
2743 // Add the explicit instantiation into its lexical context. However,
2744 // since explicit instantiations are never found by name lookup, we
2745 // just put it into the declaration context directly.
2746 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002747 CurContext->addDecl(Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002748
2749 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002750 // A definition of a class template or class member template
2751 // shall be in scope at the point of the explicit instantiation of
2752 // the class template or class member template.
2753 //
2754 // This check comes when we actually try to perform the
2755 // instantiation.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002756 if (SpecializationRequiresInstantiation)
2757 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002758 else // Instantiate the members of this class template specialization.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002759 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002760
2761 return DeclPtrTy::make(Specialization);
2762}
2763
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002764// Explicit instantiation of a member class of a class template.
2765Sema::DeclResult
2766Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2767 unsigned TagSpec,
2768 SourceLocation KWLoc,
2769 const CXXScopeSpec &SS,
2770 IdentifierInfo *Name,
2771 SourceLocation NameLoc,
2772 AttributeList *Attr) {
2773
Douglas Gregor402abb52009-05-28 23:31:59 +00002774 bool Owned = false;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002775 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor402abb52009-05-28 23:31:59 +00002776 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002777 if (!TagD)
2778 return true;
2779
2780 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2781 if (Tag->isEnum()) {
2782 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2783 << Context.getTypeDeclType(Tag);
2784 return true;
2785 }
2786
Douglas Gregord0c87372009-05-27 17:30:49 +00002787 if (Tag->isInvalidDecl())
2788 return true;
2789
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002790 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2791 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2792 if (!Pattern) {
2793 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2794 << Context.getTypeDeclType(Record);
2795 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2796 return true;
2797 }
2798
2799 // C++0x [temp.explicit]p2:
2800 // [...] An explicit instantiation shall appear in an enclosing
2801 // namespace of its template. [...]
2802 //
2803 // This is C++ DR 275.
2804 if (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002805 // FIXME: In C++98, we would like to turn these errors into warnings,
2806 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002807 DeclContext *PatternContext
2808 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2809 if (!CurContext->Encloses(PatternContext)) {
2810 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2811 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2812 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2813 }
2814 }
2815
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002816 if (!Record->getDefinition(Context)) {
2817 // If the class has a definition, instantiate it (and all of its
2818 // members, recursively).
2819 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2820 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002821 getTemplateInstantiationArgs(Record),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002822 /*ExplicitInstantiation=*/true))
2823 return true;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002824 } else // Instantiate all of the members of class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002825 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002826 getTemplateInstantiationArgs(Record));
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002827
Mike Stump390b4cc2009-05-16 07:39:55 +00002828 // FIXME: We don't have any representation for explicit instantiations of
2829 // member classes. Such a representation is not needed for compilation, but it
2830 // should be available for clients that want to see all of the declarations in
2831 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002832 return TagD;
2833}
2834
Douglas Gregord57959a2009-03-27 23:10:48 +00002835Sema::TypeResult
2836Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2837 const IdentifierInfo &II, SourceLocation IdLoc) {
2838 NestedNameSpecifier *NNS
2839 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2840 if (!NNS)
2841 return true;
2842
2843 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002844 if (T.isNull())
2845 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002846 return T.getAsOpaquePtr();
2847}
2848
Douglas Gregor17343172009-04-01 00:28:59 +00002849Sema::TypeResult
2850Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2851 SourceLocation TemplateLoc, TypeTy *Ty) {
2852 QualType T = QualType::getFromOpaquePtr(Ty);
2853 NestedNameSpecifier *NNS
2854 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2855 const TemplateSpecializationType *TemplateId
2856 = T->getAsTemplateSpecializationType();
2857 assert(TemplateId && "Expected a template specialization type");
2858
2859 if (NNS->isDependent())
2860 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2861
2862 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2863}
2864
Douglas Gregord57959a2009-03-27 23:10:48 +00002865/// \brief Build the type that describes a C++ typename specifier,
2866/// e.g., "typename T::type".
2867QualType
2868Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2869 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00002870 CXXRecordDecl *CurrentInstantiation = 0;
2871 if (NNS->isDependent()) {
2872 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00002873
Douglas Gregor42af25f2009-05-11 19:58:34 +00002874 // If the nested-name-specifier does not refer to the current
2875 // instantiation, then build a typename type.
2876 if (!CurrentInstantiation)
2877 return Context.getTypenameType(NNS, &II);
2878 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002879
Douglas Gregor42af25f2009-05-11 19:58:34 +00002880 DeclContext *Ctx = 0;
2881
2882 if (CurrentInstantiation)
2883 Ctx = CurrentInstantiation;
2884 else {
2885 CXXScopeSpec SS;
2886 SS.setScopeRep(NNS);
2887 SS.setRange(Range);
2888 if (RequireCompleteDeclContext(SS))
2889 return QualType();
2890
2891 Ctx = computeDeclContext(SS);
2892 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002893 assert(Ctx && "No declaration context?");
2894
2895 DeclarationName Name(&II);
2896 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2897 false);
2898 unsigned DiagID = 0;
2899 Decl *Referenced = 0;
2900 switch (Result.getKind()) {
2901 case LookupResult::NotFound:
2902 if (Ctx->isTranslationUnit())
2903 DiagID = diag::err_typename_nested_not_found_global;
2904 else
2905 DiagID = diag::err_typename_nested_not_found;
2906 break;
2907
2908 case LookupResult::Found:
2909 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2910 // We found a type. Build a QualifiedNameType, since the
2911 // typename-specifier was just sugar. FIXME: Tell
2912 // QualifiedNameType that it has a "typename" prefix.
2913 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2914 }
2915
2916 DiagID = diag::err_typename_nested_not_type;
2917 Referenced = Result.getAsDecl();
2918 break;
2919
2920 case LookupResult::FoundOverloaded:
2921 DiagID = diag::err_typename_nested_not_type;
2922 Referenced = *Result.begin();
2923 break;
2924
2925 case LookupResult::AmbiguousBaseSubobjectTypes:
2926 case LookupResult::AmbiguousBaseSubobjects:
2927 case LookupResult::AmbiguousReference:
2928 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2929 return QualType();
2930 }
2931
2932 // If we get here, it's because name lookup did not find a
2933 // type. Emit an appropriate diagnostic and return an error.
2934 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2935 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2936 else
2937 Diag(Range.getEnd(), DiagID) << Range << Name;
2938 if (Referenced)
2939 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2940 << Name;
2941 return QualType();
2942}