blob: 42483e419f9af872f8210dcc79e62b6c9832e26c [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregorc45c2322009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregor7532dc62009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor39a8de12009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000033
Douglas Gregor7532dc62009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregor7532dc62009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregorbefc20e2009-03-26 00:10:35 +000046 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47 // C++ [temp.local]p1:
48 // Like normal (non-template) classes, class templates have an
49 // injected-class-name (Clause 9). The injected-class-name
50 // can be used with or without a template-argument-list. When
51 // it is used without a template-argument-list, it is
52 // equivalent to the injected-class-name followed by the
53 // template-parameters of the class template enclosed in
54 // <>. When it is used with a template-argument-list, it
55 // refers to the specified class template specialization,
56 // which could be the current specialization or another
57 // specialization.
58 if (Record->isInjectedClassName()) {
59 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
Douglas Gregor7532dc62009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregorc45c2322009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregorbefc20e2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregorc45c2322009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregorbefc20e2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregor55f6b142009-02-09 18:46:07 +000068 }
Douglas Gregoraaba5e32009-02-04 19:02:06 +000069
Douglas Gregor55f6b142009-02-09 18:46:07 +000070 // FIXME: What follows is a gross hack.
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000072 if (FD->getType()->isDependentType()) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000073 TemplateResult = TemplateTy::make(FD);
Douglas Gregor55f6b142009-02-09 18:46:07 +000074 return TNK_Function_template;
75 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000076 } else if (OverloadedFunctionDecl *Ovl
77 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
78 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
79 FEnd = Ovl->function_end();
80 F != FEnd; ++F) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000081 if ((*F)->getType()->isDependentType()) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000082 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor55f6b142009-02-09 18:46:07 +000083 return TNK_Function_template;
84 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000085 }
86 }
Douglas Gregor7532dc62009-03-30 22:58:21 +000087
88 if (TNK != TNK_Non_template) {
89 if (SS && SS->isSet() && !SS->isInvalid()) {
90 NestedNameSpecifier *Qualifier
91 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
92 TemplateResult
93 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
94 false,
95 Template));
96 } else
97 TemplateResult = TemplateTy::make(TemplateName(Template));
98 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000099 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000100 return TNK;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000101}
102
Douglas Gregor72c3f312008-12-05 18:15:24 +0000103/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
104/// that the template parameter 'PrevDecl' is being shadowed by a new
105/// declaration at location Loc. Returns true to indicate that this is
106/// an error, and false otherwise.
107bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000108 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000109
110 // Microsoft Visual C++ permits template parameters to be shadowed.
111 if (getLangOptions().Microsoft)
112 return false;
113
114 // C++ [temp.local]p4:
115 // A template-parameter shall not be redeclared within its
116 // scope (including nested scopes).
117 Diag(Loc, diag::err_template_param_shadow)
118 << cast<NamedDecl>(PrevDecl)->getDeclName();
119 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
120 return true;
121}
122
Douglas Gregor2943aed2009-03-03 04:44:36 +0000123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000124/// the parameter D to reference the templated declaration and return a pointer
125/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000126TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
127 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
128 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000129 return Temp;
130 }
131 return 0;
132}
133
Douglas Gregor72c3f312008-12-05 18:15:24 +0000134/// ActOnTypeParameter - Called when a C++ template type parameter
135/// (e.g., "typename T") has been parsed. Typename specifies whether
136/// the keyword "typename" was used to declare the type parameter
137/// (otherwise, "class" was used), and KeyLoc is the location of the
138/// "class" or "typename" keyword. ParamName is the name of the
139/// parameter (NULL indicates an unnamed template parameter) and
140/// ParamName is the location of the parameter name (if any).
141/// If the type parameter has a default argument, it will be added
142/// later via ActOnTypeParameterDefault.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000143Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename,
144 SourceLocation KeyLoc,
145 IdentifierInfo *ParamName,
146 SourceLocation ParamNameLoc,
147 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000148 assert(S->isTemplateParamScope() &&
149 "Template type parameter not in template parameter scope!");
150 bool Invalid = false;
151
152 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000153 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000154 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000155 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
156 PrevDecl);
157 }
158
Douglas Gregorddc29e12009-02-06 22:42:48 +0000159 SourceLocation Loc = ParamNameLoc;
160 if (!ParamName)
161 Loc = KeyLoc;
162
Douglas Gregor72c3f312008-12-05 18:15:24 +0000163 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000164 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000165 Depth, Position, ParamName, Typename);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000166 if (Invalid)
167 Param->setInvalidDecl();
168
169 if (ParamName) {
170 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000171 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000172 IdResolver.AddDecl(Param);
173 }
174
Chris Lattnerb28317a2009-03-28 19:18:32 +0000175 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000176}
177
Douglas Gregord684b002009-02-10 19:49:53 +0000178/// ActOnTypeParameterDefault - Adds a default argument (the type
179/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000180void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000181 SourceLocation EqualLoc,
182 SourceLocation DefaultLoc,
183 TypeTy *DefaultT) {
184 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000185 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000186 QualType Default = QualType::getFromOpaquePtr(DefaultT);
187
188 // C++ [temp.param]p14:
189 // A template-parameter shall not be used in its own default argument.
190 // FIXME: Implement this check! Needs a recursive walk over the types.
191
192 // Check the template argument itself.
193 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
194 Parm->setInvalidDecl();
195 return;
196 }
197
198 Parm->setDefaultArgument(Default, DefaultLoc, false);
199}
200
Douglas Gregor2943aed2009-03-03 04:44:36 +0000201/// \brief Check that the type of a non-type template parameter is
202/// well-formed.
203///
204/// \returns the (possibly-promoted) parameter type if valid;
205/// otherwise, produces a diagnostic and returns a NULL type.
206QualType
207Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
208 // C++ [temp.param]p4:
209 //
210 // A non-type template-parameter shall have one of the following
211 // (optionally cv-qualified) types:
212 //
213 // -- integral or enumeration type,
214 if (T->isIntegralType() || T->isEnumeralType() ||
215 // -- pointer to object or pointer to function,
216 (T->isPointerType() &&
217 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
218 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
219 // -- reference to object or reference to function,
220 T->isReferenceType() ||
221 // -- pointer to member.
222 T->isMemberPointerType() ||
223 // If T is a dependent type, we can't do the check now, so we
224 // assume that it is well-formed.
225 T->isDependentType())
226 return T;
227 // C++ [temp.param]p8:
228 //
229 // A non-type template-parameter of type "array of T" or
230 // "function returning T" is adjusted to be of type "pointer to
231 // T" or "pointer to function returning T", respectively.
232 else if (T->isArrayType())
233 // FIXME: Keep the type prior to promotion?
234 return Context.getArrayDecayedType(T);
235 else if (T->isFunctionType())
236 // FIXME: Keep the type prior to promotion?
237 return Context.getPointerType(T);
238
239 Diag(Loc, diag::err_template_nontype_parm_bad_type)
240 << T;
241
242 return QualType();
243}
244
Douglas Gregor72c3f312008-12-05 18:15:24 +0000245/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
246/// template parameter (e.g., "int Size" in "template<int Size>
247/// class Array") has been parsed. S is the current scope and D is
248/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000249Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
250 unsigned Depth,
251 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000252 QualType T = GetTypeForDeclarator(D, S);
253
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000254 assert(S->isTemplateParamScope() &&
255 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000256 bool Invalid = false;
257
258 IdentifierInfo *ParamName = D.getIdentifier();
259 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000260 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000261 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000262 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000263 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000264 }
265
Douglas Gregor2943aed2009-03-03 04:44:36 +0000266 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000267 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000268 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000269 Invalid = true;
270 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000271
Douglas Gregor72c3f312008-12-05 18:15:24 +0000272 NonTypeTemplateParmDecl *Param
273 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000274 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000275 if (Invalid)
276 Param->setInvalidDecl();
277
278 if (D.getIdentifier()) {
279 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000280 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000281 IdResolver.AddDecl(Param);
282 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000283 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000284}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000285
Douglas Gregord684b002009-02-10 19:49:53 +0000286/// \brief Adds a default argument to the given non-type template
287/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000288void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000289 SourceLocation EqualLoc,
290 ExprArg DefaultE) {
291 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000292 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000293 Expr *Default = static_cast<Expr *>(DefaultE.get());
294
295 // C++ [temp.param]p14:
296 // A template-parameter shall not be used in its own default argument.
297 // FIXME: Implement this check! Needs a recursive walk over the types.
298
299 // Check the well-formedness of the default template argument.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000300 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000301 TemplateParm->setInvalidDecl();
302 return;
303 }
304
Anders Carlssone9146f22009-05-01 19:49:17 +0000305 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000306}
307
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000308
309/// ActOnTemplateTemplateParameter - Called when a C++ template template
310/// parameter (e.g. T in template <template <typename> class T> class array)
311/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000312Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
313 SourceLocation TmpLoc,
314 TemplateParamsTy *Params,
315 IdentifierInfo *Name,
316 SourceLocation NameLoc,
317 unsigned Depth,
318 unsigned Position)
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000319{
320 assert(S->isTemplateParamScope() &&
321 "Template template parameter not in template parameter scope!");
322
323 // Construct the parameter object.
324 TemplateTemplateParmDecl *Param =
325 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
326 Position, Name,
327 (TemplateParameterList*)Params);
328
329 // Make sure the parameter is valid.
330 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
331 // do anything yet. However, if the template parameter list or (eventual)
332 // default value is ever invalidated, that will propagate here.
333 bool Invalid = false;
334 if (Invalid) {
335 Param->setInvalidDecl();
336 }
337
338 // If the tt-param has a name, then link the identifier into the scope
339 // and lookup mechanisms.
340 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000341 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000342 IdResolver.AddDecl(Param);
343 }
344
Chris Lattnerb28317a2009-03-28 19:18:32 +0000345 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000346}
347
Douglas Gregord684b002009-02-10 19:49:53 +0000348/// \brief Adds a default argument to the given template template
349/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000350void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000351 SourceLocation EqualLoc,
352 ExprArg DefaultE) {
353 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000354 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000355
356 // Since a template-template parameter's default argument is an
357 // id-expression, it must be a DeclRefExpr.
358 DeclRefExpr *Default
359 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
360
361 // C++ [temp.param]p14:
362 // A template-parameter shall not be used in its own default argument.
363 // FIXME: Implement this check! Needs a recursive walk over the types.
364
365 // Check the well-formedness of the template argument.
366 if (!isa<TemplateDecl>(Default->getDecl())) {
367 Diag(Default->getSourceRange().getBegin(),
368 diag::err_template_arg_must_be_template)
369 << Default->getSourceRange();
370 TemplateParm->setInvalidDecl();
371 return;
372 }
373 if (CheckTemplateArgument(TemplateParm, Default)) {
374 TemplateParm->setInvalidDecl();
375 return;
376 }
377
378 DefaultE.release();
379 TemplateParm->setDefaultArgument(Default);
380}
381
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000382/// ActOnTemplateParameterList - Builds a TemplateParameterList that
383/// contains the template parameters in Params/NumParams.
384Sema::TemplateParamsTy *
385Sema::ActOnTemplateParameterList(unsigned Depth,
386 SourceLocation ExportLoc,
387 SourceLocation TemplateLoc,
388 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000389 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000390 SourceLocation RAngleLoc) {
391 if (ExportLoc.isValid())
392 Diag(ExportLoc, diag::note_template_export_unsupported);
393
Douglas Gregorddc29e12009-02-06 22:42:48 +0000394 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
395 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000396}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000397
Douglas Gregor212e81c2009-03-25 00:13:59 +0000398Sema::DeclResult
Douglas Gregorddc29e12009-02-06 22:42:48 +0000399Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
400 SourceLocation KWLoc, const CXXScopeSpec &SS,
401 IdentifierInfo *Name, SourceLocation NameLoc,
402 AttributeList *Attr,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000403 MultiTemplateParamsArg TemplateParameterLists,
404 AccessSpecifier AS) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000405 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
406 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000407 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000408
409 // Check that we can declare a template here.
410 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000411 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000412
413 TagDecl::TagKind Kind;
414 switch (TagSpec) {
415 default: assert(0 && "Unknown tag type!");
416 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
417 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
418 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
419 }
420
421 // There is no such thing as an unnamed class template.
422 if (!Name) {
423 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000424 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000425 }
426
427 // Find any previous declaration with this name.
428 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
429 true);
430 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
431 NamedDecl *PrevDecl = 0;
432 if (Previous.begin() != Previous.end())
433 PrevDecl = *Previous.begin();
434
435 DeclContext *SemanticContext = CurContext;
436 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000437 SemanticContext = computeDeclContext(SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000438
Mike Stump390b4cc2009-05-16 07:39:55 +0000439 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregorddc29e12009-02-06 22:42:48 +0000440 }
441
442 // FIXME: member templates!
443 TemplateParameterList *TemplateParams
444 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
445
446 // If there is a previous declaration with the same name, check
447 // whether this is a valid redeclaration.
448 ClassTemplateDecl *PrevClassTemplate
449 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
450 if (PrevClassTemplate) {
451 // Ensure that the template parameter lists are compatible.
452 if (!TemplateParameterListsAreEqual(TemplateParams,
453 PrevClassTemplate->getTemplateParameters(),
454 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000455 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000456
457 // C++ [temp.class]p4:
458 // In a redeclaration, partial specialization, explicit
459 // specialization or explicit instantiation of a class template,
460 // the class-key shall agree in kind with the original class
461 // template declaration (7.1.5.3).
462 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000463 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000464 Diag(KWLoc, diag::err_use_with_wrong_tag)
465 << Name
466 << CodeModificationHint::CreateReplacement(KWLoc,
467 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000468 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000469 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000470 }
471
Douglas Gregorddc29e12009-02-06 22:42:48 +0000472 // Check for redefinition of this class template.
473 if (TK == TK_Definition) {
474 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
475 Diag(NameLoc, diag::err_redefinition) << Name;
476 Diag(Def->getLocation(), diag::note_previous_definition);
477 // FIXME: Would it make sense to try to "forget" the previous
478 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000479 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000480 }
481 }
482 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
483 // Maybe we will complain about the shadowed template parameter.
484 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
485 // Just pretend that we didn't see the previous declaration.
486 PrevDecl = 0;
487 } else if (PrevDecl) {
488 // C++ [temp]p5:
489 // A class template shall not have the same name as any other
490 // template, class, function, object, enumeration, enumerator,
491 // namespace, or type in the same scope (3.3), except as specified
492 // in (14.5.4).
493 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
494 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000495 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000496 }
497
Douglas Gregord684b002009-02-10 19:49:53 +0000498 // Check the template parameter list of this declaration, possibly
499 // merging in the template parameter list from the previous class
500 // template declaration.
501 if (CheckTemplateParameterList(TemplateParams,
502 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
503 Invalid = true;
504
Douglas Gregor7da97d02009-05-10 22:57:19 +0000505 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000506 // declaration!
507
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000508 CXXRecordDecl *NewClass =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000509 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
510 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000511 PrevClassTemplate->getTemplatedDecl() : 0,
512 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000513
514 ClassTemplateDecl *NewTemplate
515 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
516 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000517 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000518 NewClass->setDescribedClassTemplate(NewTemplate);
519
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000520 // Build the type for the class template declaration now.
521 QualType T =
522 Context.getTypeDeclType(NewClass,
523 PrevClassTemplate?
524 PrevClassTemplate->getTemplatedDecl() : 0);
525 assert(T->isDependentType() && "Class template type is not dependent?");
526 (void)T;
527
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000528 // Set the access specifier.
529 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
530
Douglas Gregorddc29e12009-02-06 22:42:48 +0000531 // Set the lexical context of these templates
532 NewClass->setLexicalDeclContext(CurContext);
533 NewTemplate->setLexicalDeclContext(CurContext);
534
535 if (TK == TK_Definition)
536 NewClass->startDefinition();
537
538 if (Attr)
539 ProcessDeclAttributeList(NewClass, Attr);
540
541 PushOnScopeChains(NewTemplate, S);
542
Douglas Gregord684b002009-02-10 19:49:53 +0000543 if (Invalid) {
544 NewTemplate->setInvalidDecl();
545 NewClass->setInvalidDecl();
546 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000547 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000548}
549
Douglas Gregord684b002009-02-10 19:49:53 +0000550/// \brief Checks the validity of a template parameter list, possibly
551/// considering the template parameter list from a previous
552/// declaration.
553///
554/// If an "old" template parameter list is provided, it must be
555/// equivalent (per TemplateParameterListsAreEqual) to the "new"
556/// template parameter list.
557///
558/// \param NewParams Template parameter list for a new template
559/// declaration. This template parameter list will be updated with any
560/// default arguments that are carried through from the previous
561/// template parameter list.
562///
563/// \param OldParams If provided, template parameter list from a
564/// previous declaration of the same template. Default template
565/// arguments will be merged from the old template parameter list to
566/// the new template parameter list.
567///
568/// \returns true if an error occurred, false otherwise.
569bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
570 TemplateParameterList *OldParams) {
571 bool Invalid = false;
572
573 // C++ [temp.param]p10:
574 // The set of default template-arguments available for use with a
575 // template declaration or definition is obtained by merging the
576 // default arguments from the definition (if in scope) and all
577 // declarations in scope in the same way default function
578 // arguments are (8.3.6).
579 bool SawDefaultArgument = false;
580 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000581
Mike Stump1a35fde2009-02-11 23:03:27 +0000582 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000583 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000584 if (OldParams)
585 OldParam = OldParams->begin();
586
587 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
588 NewParamEnd = NewParams->end();
589 NewParam != NewParamEnd; ++NewParam) {
590 // Variables used to diagnose redundant default arguments
591 bool RedundantDefaultArg = false;
592 SourceLocation OldDefaultLoc;
593 SourceLocation NewDefaultLoc;
594
595 // Variables used to diagnose missing default arguments
596 bool MissingDefaultArg = false;
597
598 // Merge default arguments for template type parameters.
599 if (TemplateTypeParmDecl *NewTypeParm
600 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
601 TemplateTypeParmDecl *OldTypeParm
602 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
603
604 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
605 NewTypeParm->hasDefaultArgument()) {
606 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
607 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
608 SawDefaultArgument = true;
609 RedundantDefaultArg = true;
610 PreviousDefaultArgLoc = NewDefaultLoc;
611 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
612 // Merge the default argument from the old declaration to the
613 // new declaration.
614 SawDefaultArgument = true;
615 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
616 OldTypeParm->getDefaultArgumentLoc(),
617 true);
618 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
619 } else if (NewTypeParm->hasDefaultArgument()) {
620 SawDefaultArgument = true;
621 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
622 } else if (SawDefaultArgument)
623 MissingDefaultArg = true;
624 }
625 // Merge default arguments for non-type template parameters
626 else if (NonTypeTemplateParmDecl *NewNonTypeParm
627 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
628 NonTypeTemplateParmDecl *OldNonTypeParm
629 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
630 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
631 NewNonTypeParm->hasDefaultArgument()) {
632 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
633 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
634 SawDefaultArgument = true;
635 RedundantDefaultArg = true;
636 PreviousDefaultArgLoc = NewDefaultLoc;
637 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
638 // Merge the default argument from the old declaration to the
639 // new declaration.
640 SawDefaultArgument = true;
641 // FIXME: We need to create a new kind of "default argument"
642 // expression that points to a previous template template
643 // parameter.
644 NewNonTypeParm->setDefaultArgument(
645 OldNonTypeParm->getDefaultArgument());
646 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
647 } else if (NewNonTypeParm->hasDefaultArgument()) {
648 SawDefaultArgument = true;
649 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
650 } else if (SawDefaultArgument)
651 MissingDefaultArg = true;
652 }
653 // Merge default arguments for template template parameters
654 else {
655 TemplateTemplateParmDecl *NewTemplateParm
656 = cast<TemplateTemplateParmDecl>(*NewParam);
657 TemplateTemplateParmDecl *OldTemplateParm
658 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
659 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
660 NewTemplateParm->hasDefaultArgument()) {
661 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
662 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
663 SawDefaultArgument = true;
664 RedundantDefaultArg = true;
665 PreviousDefaultArgLoc = NewDefaultLoc;
666 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
667 // Merge the default argument from the old declaration to the
668 // new declaration.
669 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000670 // FIXME: We need to create a new kind of "default argument" expression
671 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000672 NewTemplateParm->setDefaultArgument(
673 OldTemplateParm->getDefaultArgument());
674 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
675 } else if (NewTemplateParm->hasDefaultArgument()) {
676 SawDefaultArgument = true;
677 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
678 } else if (SawDefaultArgument)
679 MissingDefaultArg = true;
680 }
681
682 if (RedundantDefaultArg) {
683 // C++ [temp.param]p12:
684 // A template-parameter shall not be given default arguments
685 // by two different declarations in the same scope.
686 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
687 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
688 Invalid = true;
689 } else if (MissingDefaultArg) {
690 // C++ [temp.param]p11:
691 // If a template-parameter has a default template-argument,
692 // all subsequent template-parameters shall have a default
693 // template-argument supplied.
694 Diag((*NewParam)->getLocation(),
695 diag::err_template_param_default_arg_missing);
696 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
697 Invalid = true;
698 }
699
700 // If we have an old template parameter list that we're merging
701 // in, move on to the next parameter.
702 if (OldParams)
703 ++OldParam;
704 }
705
706 return Invalid;
707}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000708
Douglas Gregor40808ce2009-03-09 23:48:35 +0000709/// \brief Translates template arguments as provided by the parser
710/// into template arguments used by semantic analysis.
711static void
712translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
713 SourceLocation *TemplateArgLocs,
714 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
715 TemplateArgs.reserve(TemplateArgsIn.size());
716
717 void **Args = TemplateArgsIn.getArgs();
718 bool *ArgIsType = TemplateArgsIn.getArgIsType();
719 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
720 TemplateArgs.push_back(
721 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
722 QualType::getFromOpaquePtr(Args[Arg]))
723 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
724 }
725}
726
Douglas Gregorc45c2322009-03-31 00:43:58 +0000727/// \brief Build a canonical version of a template argument list.
728///
729/// This function builds a canonical version of the given template
730/// argument list, where each of the template arguments has been
731/// converted into its canonical form. This routine is typically used
732/// to canonicalize a template argument list when the template name
733/// itself is dependent. When the template name refers to an actual
734/// template declaration, Sema::CheckTemplateArgumentList should be
735/// used to check and canonicalize the template arguments.
736///
737/// \param TemplateArgs The incoming template arguments.
738///
739/// \param NumTemplateArgs The number of template arguments in \p
740/// TemplateArgs.
741///
742/// \param Canonical A vector to be filled with the canonical versions
743/// of the template arguments.
744///
745/// \param Context The ASTContext in which the template arguments live.
746static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
747 unsigned NumTemplateArgs,
748 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
749 ASTContext &Context) {
750 Canonical.reserve(NumTemplateArgs);
751 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
752 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000753 case TemplateArgument::Null:
754 assert(false && "Should never see a NULL template argument here");
755 break;
756
Douglas Gregorc45c2322009-03-31 00:43:58 +0000757 case TemplateArgument::Expression:
758 // FIXME: Build canonical expression (!)
759 Canonical.push_back(TemplateArgs[Idx]);
760 break;
761
762 case TemplateArgument::Declaration:
Douglas Gregor7da97d02009-05-10 22:57:19 +0000763 Canonical.push_back(
764 TemplateArgument(SourceLocation(),
765 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregorc45c2322009-03-31 00:43:58 +0000766 break;
767
768 case TemplateArgument::Integral:
769 Canonical.push_back(TemplateArgument(SourceLocation(),
770 *TemplateArgs[Idx].getAsIntegral(),
771 TemplateArgs[Idx].getIntegralType()));
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000772 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000773
774 case TemplateArgument::Type: {
775 QualType CanonType
776 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
777 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000778 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000779 }
780 }
781 }
782}
783
Douglas Gregor7532dc62009-03-30 22:58:21 +0000784QualType Sema::CheckTemplateIdType(TemplateName Name,
785 SourceLocation TemplateLoc,
786 SourceLocation LAngleLoc,
787 const TemplateArgument *TemplateArgs,
788 unsigned NumTemplateArgs,
789 SourceLocation RAngleLoc) {
790 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +0000791 if (!Template) {
792 // The template name does not resolve to a template, so we just
793 // build a dependent template-id type.
794
795 // Canonicalize the template arguments to build the canonical
796 // template-id type.
797 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
798 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
799 CanonicalTemplateArgs, Context);
800
Douglas Gregor45fbaf02009-05-07 06:49:52 +0000801 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000802 QualType CanonType
Douglas Gregor45fbaf02009-05-07 06:49:52 +0000803 = Context.getTemplateSpecializationType(CanonName,
804 &CanonicalTemplateArgs[0],
Douglas Gregorc45c2322009-03-31 00:43:58 +0000805 CanonicalTemplateArgs.size());
806
807 // Build the dependent template-id type.
808 return Context.getTemplateSpecializationType(Name, TemplateArgs,
809 NumTemplateArgs, CanonType);
810 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000811
Douglas Gregor40808ce2009-03-09 23:48:35 +0000812 // Check that the template argument list is well-formed for this
813 // template.
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000814 TemplateArgumentListBuilder ConvertedTemplateArgs;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000815 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000816 TemplateArgs, NumTemplateArgs, RAngleLoc,
817 ConvertedTemplateArgs))
818 return QualType();
819
820 assert((ConvertedTemplateArgs.size() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000821 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000822 "Converted template argument list is too short!");
823
824 QualType CanonType;
825
Douglas Gregor7532dc62009-03-30 22:58:21 +0000826 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000827 TemplateArgs,
828 NumTemplateArgs)) {
829 // This class template specialization is a dependent
830 // type. Therefore, its canonical type is another class template
831 // specialization type that contains all of the converted
832 // arguments in canonical form. This ensures that, e.g., A<T> and
833 // A<T, T> have identical types when A is declared as:
834 //
835 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +0000836 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
837 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000838 ConvertedTemplateArgs.getFlatArgumentList(),
839 ConvertedTemplateArgs.flatSize());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000840 } else if (ClassTemplateDecl *ClassTemplate
841 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000842 // Find the class template specialization declaration that
843 // corresponds to these arguments.
844 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000845 ClassTemplateSpecializationDecl::Profile(ID,
846 ConvertedTemplateArgs.getFlatArgumentList(),
847 ConvertedTemplateArgs.flatSize());
Douglas Gregor40808ce2009-03-09 23:48:35 +0000848 void *InsertPos = 0;
849 ClassTemplateSpecializationDecl *Decl
850 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
851 if (!Decl) {
852 // This is the first time we have referenced this class template
853 // specialization. Create the canonical declaration and add it to
854 // the set of specializations.
855 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000856 ClassTemplate->getDeclContext(),
857 TemplateLoc,
858 ClassTemplate,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +0000859 ConvertedTemplateArgs, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000860 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
861 Decl->setLexicalDeclContext(CurContext);
862 }
863
864 CanonType = Context.getTypeDeclType(Decl);
865 }
866
867 // Build the fully-sugared type for this class template
868 // specialization, which refers back to the class template
869 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +0000870 return Context.getTemplateSpecializationType(Name, TemplateArgs,
871 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000872}
873
Douglas Gregorcc636682009-02-17 23:15:12 +0000874Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +0000875Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
876 SourceLocation LAngleLoc,
877 ASTTemplateArgsPtr TemplateArgsIn,
878 SourceLocation *TemplateArgLocs,
879 SourceLocation RAngleLoc) {
880 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000881
Douglas Gregor40808ce2009-03-09 23:48:35 +0000882 // Translate the parser's template argument list in our AST format.
883 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
884 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000885
Douglas Gregor7532dc62009-03-30 22:58:21 +0000886 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000887 TemplateArgs.data(),
888 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +0000889 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000890 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000891
892 if (Result.isNull())
893 return true;
894
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000895 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000896}
897
Douglas Gregorc45c2322009-03-31 00:43:58 +0000898/// \brief Form a dependent template name.
899///
900/// This action forms a dependent template name given the template
901/// name and its (presumably dependent) scope specifier. For
902/// example, given "MetaFun::template apply", the scope specifier \p
903/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
904/// of the "template" keyword, and "apply" is the \p Name.
905Sema::TemplateTy
906Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
907 const IdentifierInfo &Name,
908 SourceLocation NameLoc,
909 const CXXScopeSpec &SS) {
910 if (!SS.isSet() || SS.isInvalid())
911 return TemplateTy();
912
913 NestedNameSpecifier *Qualifier
914 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
915
916 // FIXME: member of the current instantiation
917
918 if (!Qualifier->isDependent()) {
919 // C++0x [temp.names]p5:
920 // If a name prefixed by the keyword template is not the name of
921 // a template, the program is ill-formed. [Note: the keyword
922 // template may not be applied to non-template members of class
923 // templates. -end note ] [ Note: as is the case with the
924 // typename prefix, the template prefix is allowed in cases
925 // where it is not strictly necessary; i.e., when the
926 // nested-name-specifier or the expression on the left of the ->
927 // or . is not dependent on a template-parameter, or the use
928 // does not appear in the scope of a template. -end note]
929 //
930 // Note: C++03 was more strict here, because it banned the use of
931 // the "template" keyword prior to a template-name that was not a
932 // dependent name. C++ DR468 relaxed this requirement (the
933 // "template" keyword is now permitted). We follow the C++0x
934 // rules, even in C++03 mode, retroactively applying the DR.
935 TemplateTy Template;
936 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
937 if (TNK == TNK_Non_template) {
938 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
939 << &Name;
940 return TemplateTy();
941 }
942
943 return Template;
944 }
945
946 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
947}
948
Douglas Gregorc15cb382009-02-09 23:23:08 +0000949/// \brief Check that the given template argument list is well-formed
950/// for specializing the given template.
951bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
952 SourceLocation TemplateLoc,
953 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000954 const TemplateArgument *TemplateArgs,
955 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000956 SourceLocation RAngleLoc,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000957 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000958 TemplateParameterList *Params = Template->getTemplateParameters();
959 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +0000960 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000961 bool Invalid = false;
962
963 if (NumArgs > NumParams ||
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000964 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000965 // FIXME: point at either the first arg beyond what we can handle,
966 // or the '>', depending on whether we have too many or too few
967 // arguments.
968 SourceRange Range;
969 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +0000970 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000971 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
972 << (NumArgs > NumParams)
973 << (isa<ClassTemplateDecl>(Template)? 0 :
974 isa<FunctionTemplateDecl>(Template)? 1 :
975 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
976 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000977 Diag(Template->getLocation(), diag::note_template_decl_here)
978 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +0000979 Invalid = true;
980 }
981
982 // C++ [temp.arg]p1:
983 // [...] The type and form of each template-argument specified in
984 // a template-id shall match the type and form specified for the
985 // corresponding parameter declared by the template in its
986 // template-parameter-list.
987 unsigned ArgIdx = 0;
988 for (TemplateParameterList::iterator Param = Params->begin(),
989 ParamEnd = Params->end();
990 Param != ParamEnd; ++Param, ++ArgIdx) {
991 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +0000992 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000993 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000994 // Retrieve the default template argument from the template
995 // parameter.
996 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
997 if (!TTP->hasDefaultArgument())
998 break;
999
Douglas Gregor40808ce2009-03-09 23:48:35 +00001000 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001001
1002 // If the argument type is dependent, instantiate it now based
1003 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001004 if (ArgType->isDependentType()) {
1005 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001006 Template, Converted.getFlatArgumentList(),
1007 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001008 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001009
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001010 TemplateArgumentList TemplateArgs(Context,
1011 Converted.getFlatArgumentList(),
1012 Converted.flatSize(),
Douglas Gregor7e063902009-05-11 23:53:27 +00001013 /*CopyArgs=*/false);
1014 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor99ebf652009-02-27 19:31:52 +00001015 TTP->getDefaultArgumentLoc(),
1016 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001017 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001018
1019 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001020 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001021
Douglas Gregor40808ce2009-03-09 23:48:35 +00001022 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001023 } else if (NonTypeTemplateParmDecl *NTTP
1024 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1025 if (!NTTP->hasDefaultArgument())
1026 break;
1027
Douglas Gregor2943aed2009-03-03 04:44:36 +00001028 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001029 Arg = TemplateArgument(NTTP->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001030 } else {
1031 TemplateTemplateParmDecl *TempParm
1032 = cast<TemplateTemplateParmDecl>(*Param);
1033
1034 if (!TempParm->hasDefaultArgument())
1035 break;
1036
Douglas Gregor2943aed2009-03-03 04:44:36 +00001037 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001038 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001039 }
1040 } else {
1041 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001042 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001043 }
1044
Douglas Gregorc15cb382009-02-09 23:23:08 +00001045
1046 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1047 // Check template type parameters.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001048 if (Arg.getKind() == TemplateArgument::Type) {
1049 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001050 Invalid = true;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001051
1052 // Add the converted template type argument.
1053 Converted.push_back(
Douglas Gregor40808ce2009-03-09 23:48:35 +00001054 TemplateArgument(Arg.getLocation(),
1055 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregorc15cb382009-02-09 23:23:08 +00001056 continue;
1057 }
1058
1059 // C++ [temp.arg.type]p1:
1060 // A template-argument for a template-parameter which is a
1061 // type shall be a type-id.
1062
1063 // We have a template type parameter but the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001064 // is not a type.
1065 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor8b642592009-02-10 00:53:15 +00001066 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001067 Invalid = true;
1068 } else if (NonTypeTemplateParmDecl *NTTP
1069 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1070 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001071
1072 // Instantiate the type of the non-type template parameter with
1073 // the template arguments we've seen thus far.
1074 QualType NTTPType = NTTP->getType();
1075 if (NTTPType->isDependentType()) {
1076 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001077 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001078 Template, Converted.getFlatArgumentList(),
1079 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001080 SourceRange(TemplateLoc, RAngleLoc));
1081
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001082 TemplateArgumentList TemplateArgs(Context,
1083 Converted.getFlatArgumentList(),
1084 Converted.flatSize(),
Douglas Gregor7e063902009-05-11 23:53:27 +00001085 /*CopyArgs=*/false);
1086 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001087 NTTP->getLocation(),
1088 NTTP->getDeclName());
1089 // If that worked, check the non-type template parameter type
1090 // for validity.
1091 if (!NTTPType.isNull())
1092 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1093 NTTP->getLocation());
1094
1095 if (NTTPType.isNull()) {
1096 Invalid = true;
1097 break;
1098 }
1099 }
1100
Douglas Gregor40808ce2009-03-09 23:48:35 +00001101 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001102 case TemplateArgument::Null:
1103 assert(false && "Should never see a NULL template argument here");
1104 break;
1105
Douglas Gregor40808ce2009-03-09 23:48:35 +00001106 case TemplateArgument::Expression: {
1107 Expr *E = Arg.getAsExpr();
1108 if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001109 Invalid = true;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001110 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001111 }
1112
Douglas Gregor40808ce2009-03-09 23:48:35 +00001113 case TemplateArgument::Declaration:
1114 case TemplateArgument::Integral:
1115 // We've already checked this template argument, so just copy
1116 // it to the list of converted arguments.
1117 Converted.push_back(Arg);
1118 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001119
Douglas Gregor40808ce2009-03-09 23:48:35 +00001120 case TemplateArgument::Type:
1121 // We have a non-type template parameter but the template
1122 // argument is a type.
1123
1124 // C++ [temp.arg]p2:
1125 // In a template-argument, an ambiguity between a type-id and
1126 // an expression is resolved to a type-id, regardless of the
1127 // form of the corresponding template-parameter.
1128 //
1129 // We warn specifically about this case, since it can be rather
1130 // confusing for users.
1131 if (Arg.getAsType()->isFunctionType())
1132 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1133 << Arg.getAsType();
1134 else
1135 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1136 Diag((*Param)->getLocation(), diag::note_template_param_here);
1137 Invalid = true;
1138 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001139 } else {
1140 // Check template template parameters.
1141 TemplateTemplateParmDecl *TempParm
1142 = cast<TemplateTemplateParmDecl>(*Param);
1143
Douglas Gregor40808ce2009-03-09 23:48:35 +00001144 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001145 case TemplateArgument::Null:
1146 assert(false && "Should never see a NULL template argument here");
1147 break;
1148
Douglas Gregor40808ce2009-03-09 23:48:35 +00001149 case TemplateArgument::Expression: {
1150 Expr *ArgExpr = Arg.getAsExpr();
1151 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1152 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1153 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1154 Invalid = true;
1155
1156 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001157 Decl *D
1158 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1159 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001160 continue;
1161 }
1162 }
1163 // fall through
1164
1165 case TemplateArgument::Type: {
1166 // We have a template template parameter but the template
1167 // argument does not refer to a template.
1168 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1169 Invalid = true;
1170 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001171 }
1172
Douglas Gregor40808ce2009-03-09 23:48:35 +00001173 case TemplateArgument::Declaration:
1174 // We've already checked this template argument, so just copy
1175 // it to the list of converted arguments.
1176 Converted.push_back(Arg);
1177 break;
1178
1179 case TemplateArgument::Integral:
1180 assert(false && "Integral argument with template template parameter");
1181 break;
1182 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001183 }
1184 }
1185
1186 return Invalid;
1187}
1188
1189/// \brief Check a template argument against its corresponding
1190/// template type parameter.
1191///
1192/// This routine implements the semantics of C++ [temp.arg.type]. It
1193/// returns true if an error occurred, and false otherwise.
1194bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1195 QualType Arg, SourceLocation ArgLoc) {
1196 // C++ [temp.arg.type]p2:
1197 // A local type, a type with no linkage, an unnamed type or a type
1198 // compounded from any of these types shall not be used as a
1199 // template-argument for a template type-parameter.
1200 //
1201 // FIXME: Perform the recursive and no-linkage type checks.
1202 const TagType *Tag = 0;
1203 if (const EnumType *EnumT = Arg->getAsEnumType())
1204 Tag = EnumT;
1205 else if (const RecordType *RecordT = Arg->getAsRecordType())
1206 Tag = RecordT;
1207 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1208 return Diag(ArgLoc, diag::err_template_arg_local_type)
1209 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001210 else if (Tag && !Tag->getDecl()->getDeclName() &&
1211 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001212 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1213 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1214 return true;
1215 }
1216
1217 return false;
1218}
1219
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001220/// \brief Checks whether the given template argument is the address
1221/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001222bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1223 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001224 bool Invalid = false;
1225
1226 // See through any implicit casts we added to fix the type.
1227 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1228 Arg = Cast->getSubExpr();
1229
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001230 // C++0x allows nullptr, and there's no further checking to be done for that.
1231 if (Arg->getType()->isNullPtrType())
1232 return false;
1233
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001234 // C++ [temp.arg.nontype]p1:
1235 //
1236 // A template-argument for a non-type, non-template
1237 // template-parameter shall be one of: [...]
1238 //
1239 // -- the address of an object or function with external
1240 // linkage, including function templates and function
1241 // template-ids but excluding non-static class members,
1242 // expressed as & id-expression where the & is optional if
1243 // the name refers to a function or array, or if the
1244 // corresponding template-parameter is a reference; or
1245 DeclRefExpr *DRE = 0;
1246
1247 // Ignore (and complain about) any excess parentheses.
1248 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1249 if (!Invalid) {
1250 Diag(Arg->getSourceRange().getBegin(),
1251 diag::err_template_arg_extra_parens)
1252 << Arg->getSourceRange();
1253 Invalid = true;
1254 }
1255
1256 Arg = Parens->getSubExpr();
1257 }
1258
1259 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1260 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1261 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1262 } else
1263 DRE = dyn_cast<DeclRefExpr>(Arg);
1264
1265 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1266 return Diag(Arg->getSourceRange().getBegin(),
1267 diag::err_template_arg_not_object_or_func_form)
1268 << Arg->getSourceRange();
1269
1270 // Cannot refer to non-static data members
1271 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1272 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1273 << Field << Arg->getSourceRange();
1274
1275 // Cannot refer to non-static member functions
1276 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1277 if (!Method->isStatic())
1278 return Diag(Arg->getSourceRange().getBegin(),
1279 diag::err_template_arg_method)
1280 << Method << Arg->getSourceRange();
1281
1282 // Functions must have external linkage.
1283 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1284 if (Func->getStorageClass() == FunctionDecl::Static) {
1285 Diag(Arg->getSourceRange().getBegin(),
1286 diag::err_template_arg_function_not_extern)
1287 << Func << Arg->getSourceRange();
1288 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1289 << true;
1290 return true;
1291 }
1292
1293 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001294 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001295 return Invalid;
1296 }
1297
1298 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1299 if (!Var->hasGlobalStorage()) {
1300 Diag(Arg->getSourceRange().getBegin(),
1301 diag::err_template_arg_object_not_extern)
1302 << Var << Arg->getSourceRange();
1303 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1304 << true;
1305 return true;
1306 }
1307
1308 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001309 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001310 return Invalid;
1311 }
1312
1313 // We found something else, but we don't know specifically what it is.
1314 Diag(Arg->getSourceRange().getBegin(),
1315 diag::err_template_arg_not_object_or_func)
1316 << Arg->getSourceRange();
1317 Diag(DRE->getDecl()->getLocation(),
1318 diag::note_template_arg_refers_here);
1319 return true;
1320}
1321
1322/// \brief Checks whether the given template argument is a pointer to
1323/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001324bool
1325Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001326 bool Invalid = false;
1327
1328 // See through any implicit casts we added to fix the type.
1329 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1330 Arg = Cast->getSubExpr();
1331
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001332 // C++0x allows nullptr, and there's no further checking to be done for that.
1333 if (Arg->getType()->isNullPtrType())
1334 return false;
1335
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001336 // C++ [temp.arg.nontype]p1:
1337 //
1338 // A template-argument for a non-type, non-template
1339 // template-parameter shall be one of: [...]
1340 //
1341 // -- a pointer to member expressed as described in 5.3.1.
1342 QualifiedDeclRefExpr *DRE = 0;
1343
1344 // Ignore (and complain about) any excess parentheses.
1345 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1346 if (!Invalid) {
1347 Diag(Arg->getSourceRange().getBegin(),
1348 diag::err_template_arg_extra_parens)
1349 << Arg->getSourceRange();
1350 Invalid = true;
1351 }
1352
1353 Arg = Parens->getSubExpr();
1354 }
1355
1356 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1357 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1358 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1359
1360 if (!DRE)
1361 return Diag(Arg->getSourceRange().getBegin(),
1362 diag::err_template_arg_not_pointer_to_member_form)
1363 << Arg->getSourceRange();
1364
1365 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1366 assert((isa<FieldDecl>(DRE->getDecl()) ||
1367 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1368 "Only non-static member pointers can make it here");
1369
1370 // Okay: this is the address of a non-static member, and therefore
1371 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001372 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001373 return Invalid;
1374 }
1375
1376 // We found something else, but we don't know specifically what it is.
1377 Diag(Arg->getSourceRange().getBegin(),
1378 diag::err_template_arg_not_pointer_to_member_form)
1379 << Arg->getSourceRange();
1380 Diag(DRE->getDecl()->getLocation(),
1381 diag::note_template_arg_refers_here);
1382 return true;
1383}
1384
Douglas Gregorc15cb382009-02-09 23:23:08 +00001385/// \brief Check a template argument against its corresponding
1386/// non-type template parameter.
1387///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001388/// This routine implements the semantics of C++ [temp.arg.nontype].
1389/// It returns true if an error occurred, and false otherwise. \p
1390/// InstantiatedParamType is the type of the non-type template
1391/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001392///
1393/// If Converted is non-NULL and no errors occur, the value
1394/// of this argument will be added to the end of the Converted vector.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001395bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001396 QualType InstantiatedParamType, Expr *&Arg,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001397 TemplateArgumentListBuilder *Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001398 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1399
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001400 // If either the parameter has a dependent type or the argument is
1401 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001402 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001403 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1404 // FIXME: Produce a cloned, canonical expression?
1405 Converted->push_back(TemplateArgument(Arg));
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001406 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001407 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001408
1409 // C++ [temp.arg.nontype]p5:
1410 // The following conversions are performed on each expression used
1411 // as a non-type template-argument. If a non-type
1412 // template-argument cannot be converted to the type of the
1413 // corresponding template-parameter then the program is
1414 // ill-formed.
1415 //
1416 // -- for a non-type template-parameter of integral or
1417 // enumeration type, integral promotions (4.5) and integral
1418 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001419 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001420 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001421 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001422 // C++ [temp.arg.nontype]p1:
1423 // A template-argument for a non-type, non-template
1424 // template-parameter shall be one of:
1425 //
1426 // -- an integral constant-expression of integral or enumeration
1427 // type; or
1428 // -- the name of a non-type template-parameter; or
1429 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001430 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001431 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1432 Diag(Arg->getSourceRange().getBegin(),
1433 diag::err_template_arg_not_integral_or_enumeral)
1434 << ArgType << Arg->getSourceRange();
1435 Diag(Param->getLocation(), diag::note_template_param_here);
1436 return true;
1437 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001438 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001439 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1440 << ArgType << Arg->getSourceRange();
1441 return true;
1442 }
1443
1444 // FIXME: We need some way to more easily get the unqualified form
1445 // of the types without going all the way to the
1446 // canonical type.
1447 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1448 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1449 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1450 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1451
1452 // Try to convert the argument to the parameter's type.
1453 if (ParamType == ArgType) {
1454 // Okay: no conversion necessary
1455 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1456 !ParamType->isEnumeralType()) {
1457 // This is an integral promotion or conversion.
1458 ImpCastExprToType(Arg, ParamType);
1459 } else {
1460 // We can't perform this conversion.
1461 Diag(Arg->getSourceRange().getBegin(),
1462 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001463 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001464 Diag(Param->getLocation(), diag::note_template_param_here);
1465 return true;
1466 }
1467
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001468 QualType IntegerType = Context.getCanonicalType(ParamType);
1469 if (const EnumType *Enum = IntegerType->getAsEnumType())
1470 IntegerType = Enum->getDecl()->getIntegerType();
1471
1472 if (!Arg->isValueDependent()) {
1473 // Check that an unsigned parameter does not receive a negative
1474 // value.
1475 if (IntegerType->isUnsignedIntegerType()
1476 && (Value.isSigned() && Value.isNegative())) {
1477 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1478 << Value.toString(10) << Param->getType()
1479 << Arg->getSourceRange();
1480 Diag(Param->getLocation(), diag::note_template_param_here);
1481 return true;
1482 }
1483
1484 // Check that we don't overflow the template parameter type.
1485 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1486 if (Value.getActiveBits() > AllowedBits) {
1487 Diag(Arg->getSourceRange().getBegin(),
1488 diag::err_template_arg_too_large)
1489 << Value.toString(10) << Param->getType()
1490 << Arg->getSourceRange();
1491 Diag(Param->getLocation(), diag::note_template_param_here);
1492 return true;
1493 }
1494
1495 if (Value.getBitWidth() != AllowedBits)
1496 Value.extOrTrunc(AllowedBits);
1497 Value.setIsSigned(IntegerType->isSignedIntegerType());
1498 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001499
1500 if (Converted) {
1501 // Add the value of this argument to the list of converted
1502 // arguments. We use the bitwidth and signedness of the template
1503 // parameter.
Douglas Gregorba498172009-03-13 21:01:28 +00001504 if (Arg->isValueDependent()) {
1505 // The argument is value-dependent. Create a new
1506 // TemplateArgument with the converted expression.
1507 Converted->push_back(TemplateArgument(Arg));
1508 return false;
1509 }
1510
Douglas Gregor5b0f7522009-03-14 00:03:48 +00001511 Converted->push_back(TemplateArgument(StartLoc, Value,
Sebastian Redl599fe7c2009-05-27 19:21:29 +00001512 ParamType->isEnumeralType() ? ParamType : IntegerType));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001513 }
1514
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001515 return false;
1516 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001517
Douglas Gregorb86b0572009-02-11 01:18:59 +00001518 // Handle pointer-to-function, reference-to-function, and
1519 // pointer-to-member-function all in (roughly) the same way.
1520 if (// -- For a non-type template-parameter of type pointer to
1521 // function, only the function-to-pointer conversion (4.3) is
1522 // applied. If the template-argument represents a set of
1523 // overloaded functions (or a pointer to such), the matching
1524 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001525 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001526 (ParamType->isPointerType() &&
1527 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1528 // -- For a non-type template-parameter of type reference to
1529 // function, no conversions apply. If the template-argument
1530 // represents a set of overloaded functions, the matching
1531 // function is selected from the set (13.4).
1532 (ParamType->isReferenceType() &&
1533 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1534 // -- For a non-type template-parameter of type pointer to
1535 // member function, no conversions apply. If the
1536 // template-argument represents a set of overloaded member
1537 // functions, the matching member function is selected from
1538 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001539 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001540 (ParamType->isMemberPointerType() &&
1541 ParamType->getAsMemberPointerType()->getPointeeType()
1542 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001543 if (Context.hasSameUnqualifiedType(ArgType,
1544 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001545 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001546 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1547 ParamType->isMemberPointerType())) {
1548 ArgType = ParamType;
1549 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001550 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001551 ArgType = Context.getPointerType(ArgType);
1552 ImpCastExprToType(Arg, ArgType);
1553 } else if (FunctionDecl *Fn
1554 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001555 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1556 return true;
1557
Douglas Gregora35284b2009-02-11 00:19:33 +00001558 FixOverloadedFunctionReference(Arg, Fn);
1559 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001560 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001561 ArgType = Context.getPointerType(Arg->getType());
1562 ImpCastExprToType(Arg, ArgType);
1563 }
1564 }
1565
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001566 if (!Context.hasSameUnqualifiedType(ArgType,
1567 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001568 // We can't perform this conversion.
1569 Diag(Arg->getSourceRange().getBegin(),
1570 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001571 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001572 Diag(Param->getLocation(), diag::note_template_param_here);
1573 return true;
1574 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001575
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001576 if (ParamType->isMemberPointerType()) {
1577 NamedDecl *Member = 0;
1578 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1579 return true;
1580
Douglas Gregor7da97d02009-05-10 22:57:19 +00001581 if (Converted) {
Douglas Gregor92d50772009-05-10 23:27:08 +00001582 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001583 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregor7da97d02009-05-10 22:57:19 +00001584 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001585
1586 return false;
1587 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001588
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001589 NamedDecl *Entity = 0;
1590 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1591 return true;
1592
Douglas Gregor7da97d02009-05-10 22:57:19 +00001593 if (Converted) {
Douglas Gregor92d50772009-05-10 23:27:08 +00001594 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001595 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor7da97d02009-05-10 22:57:19 +00001596 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001597 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001598 }
1599
Chris Lattnerfe90de72009-02-20 21:37:53 +00001600 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001601 // -- for a non-type template-parameter of type pointer to
1602 // object, qualification conversions (4.4) and the
1603 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001604 // C++0x also allows a value of std::nullptr_t.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001605 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001606 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001607
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001608 if (ArgType->isNullPtrType()) {
1609 ArgType = ParamType;
1610 ImpCastExprToType(Arg, ParamType);
1611 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001612 ArgType = Context.getArrayDecayedType(ArgType);
1613 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001614 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001615
Douglas Gregorb86b0572009-02-11 01:18:59 +00001616 if (IsQualificationConversion(ArgType, ParamType)) {
1617 ArgType = ParamType;
1618 ImpCastExprToType(Arg, ParamType);
1619 }
1620
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001621 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001622 // We can't perform this conversion.
1623 Diag(Arg->getSourceRange().getBegin(),
1624 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001625 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001626 Diag(Param->getLocation(), diag::note_template_param_here);
1627 return true;
1628 }
1629
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001630 NamedDecl *Entity = 0;
1631 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1632 return true;
1633
Douglas Gregor7da97d02009-05-10 22:57:19 +00001634 if (Converted) {
Douglas Gregor92d50772009-05-10 23:27:08 +00001635 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001636 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor7da97d02009-05-10 22:57:19 +00001637 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001638
1639 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001640 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001641
1642 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1643 // -- For a non-type template-parameter of type reference to
1644 // object, no conversions apply. The type referred to by the
1645 // reference may be more cv-qualified than the (otherwise
1646 // identical) type of the template-argument. The
1647 // template-parameter is bound directly to the
1648 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001649 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001650 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001651
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001652 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001653 Diag(Arg->getSourceRange().getBegin(),
1654 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001655 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001656 << Arg->getSourceRange();
1657 Diag(Param->getLocation(), diag::note_template_param_here);
1658 return true;
1659 }
1660
1661 unsigned ParamQuals
1662 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1663 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1664
1665 if ((ParamQuals | ArgQuals) != ParamQuals) {
1666 Diag(Arg->getSourceRange().getBegin(),
1667 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001668 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001669 << Arg->getSourceRange();
1670 Diag(Param->getLocation(), diag::note_template_param_here);
1671 return true;
1672 }
1673
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001674 NamedDecl *Entity = 0;
1675 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1676 return true;
1677
Douglas Gregor7da97d02009-05-10 22:57:19 +00001678 if (Converted) {
1679 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001680 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor7da97d02009-05-10 22:57:19 +00001681 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001682
1683 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001684 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001685
1686 // -- For a non-type template-parameter of type pointer to data
1687 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001688 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00001689 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1690
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001691 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001692 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001693 } else if (ArgType->isNullPtrType()) {
1694 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00001695 } else if (IsQualificationConversion(ArgType, ParamType)) {
1696 ImpCastExprToType(Arg, ParamType);
1697 } else {
1698 // We can't perform this conversion.
1699 Diag(Arg->getSourceRange().getBegin(),
1700 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001701 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001702 Diag(Param->getLocation(), diag::note_template_param_here);
1703 return true;
1704 }
1705
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001706 NamedDecl *Member = 0;
1707 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1708 return true;
1709
Douglas Gregor7da97d02009-05-10 22:57:19 +00001710 if (Converted) {
Douglas Gregor92d50772009-05-10 23:27:08 +00001711 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001712 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregor7da97d02009-05-10 22:57:19 +00001713 }
1714
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001715 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001716}
1717
1718/// \brief Check a template argument against its corresponding
1719/// template template parameter.
1720///
1721/// This routine implements the semantics of C++ [temp.arg.template].
1722/// It returns true if an error occurred, and false otherwise.
1723bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1724 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001725 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1726 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1727
1728 // C++ [temp.arg.template]p1:
1729 // A template-argument for a template template-parameter shall be
1730 // the name of a class template, expressed as id-expression. Only
1731 // primary class templates are considered when matching the
1732 // template template argument with the corresponding parameter;
1733 // partial specializations are not considered even if their
1734 // parameter lists match that of the template template parameter.
1735 if (!isa<ClassTemplateDecl>(Template)) {
1736 assert(isa<FunctionTemplateDecl>(Template) &&
1737 "Only function templates are possible here");
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001738 Diag(Arg->getSourceRange().getBegin(),
1739 diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001740 << Template;
1741 }
1742
1743 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1744 Param->getTemplateParameters(),
1745 true, true,
1746 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001747}
1748
Douglas Gregorddc29e12009-02-06 22:42:48 +00001749/// \brief Determine whether the given template parameter lists are
1750/// equivalent.
1751///
1752/// \param New The new template parameter list, typically written in the
1753/// source code as part of a new template declaration.
1754///
1755/// \param Old The old template parameter list, typically found via
1756/// name lookup of the template declared with this template parameter
1757/// list.
1758///
1759/// \param Complain If true, this routine will produce a diagnostic if
1760/// the template parameter lists are not equivalent.
1761///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001762/// \param IsTemplateTemplateParm If true, this routine is being
1763/// called to compare the template parameter lists of a template
1764/// template parameter.
1765///
1766/// \param TemplateArgLoc If this source location is valid, then we
1767/// are actually checking the template parameter list of a template
1768/// argument (New) against the template parameter list of its
1769/// corresponding template template parameter (Old). We produce
1770/// slightly different diagnostics in this scenario.
1771///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001772/// \returns True if the template parameter lists are equal, false
1773/// otherwise.
1774bool
1775Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1776 TemplateParameterList *Old,
1777 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001778 bool IsTemplateTemplateParm,
1779 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001780 if (Old->size() != New->size()) {
1781 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001782 unsigned NextDiag = diag::err_template_param_list_different_arity;
1783 if (TemplateArgLoc.isValid()) {
1784 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1785 NextDiag = diag::note_template_param_list_different_arity;
1786 }
1787 Diag(New->getTemplateLoc(), NextDiag)
1788 << (New->size() > Old->size())
1789 << IsTemplateTemplateParm
1790 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001791 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1792 << IsTemplateTemplateParm
1793 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1794 }
1795
1796 return false;
1797 }
1798
1799 for (TemplateParameterList::iterator OldParm = Old->begin(),
1800 OldParmEnd = Old->end(), NewParm = New->begin();
1801 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1802 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001803 unsigned NextDiag = diag::err_template_param_different_kind;
1804 if (TemplateArgLoc.isValid()) {
1805 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1806 NextDiag = diag::note_template_param_different_kind;
1807 }
1808 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001809 << IsTemplateTemplateParm;
1810 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1811 << IsTemplateTemplateParm;
1812 return false;
1813 }
1814
1815 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1816 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00001817 // know we're at the same index).
1818#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00001819 // FIXME: Enable this code in debug mode *after* we properly go through
1820 // and "instantiate" the template parameter lists of template template
1821 // parameters. It's only after this instantiation that (1) any dependent
1822 // types within the template parameter list of the template template
1823 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00001824 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00001825 QualType OldParmType
1826 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1827 QualType NewParmType
1828 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1829 assert(Context.getCanonicalType(OldParmType) ==
1830 Context.getCanonicalType(NewParmType) &&
1831 "type parameter mismatch?");
1832#endif
1833 } else if (NonTypeTemplateParmDecl *OldNTTP
1834 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1835 // The types of non-type template parameters must agree.
1836 NonTypeTemplateParmDecl *NewNTTP
1837 = cast<NonTypeTemplateParmDecl>(*NewParm);
1838 if (Context.getCanonicalType(OldNTTP->getType()) !=
1839 Context.getCanonicalType(NewNTTP->getType())) {
1840 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001841 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1842 if (TemplateArgLoc.isValid()) {
1843 Diag(TemplateArgLoc,
1844 diag::err_template_arg_template_params_mismatch);
1845 NextDiag = diag::note_template_nontype_parm_different_type;
1846 }
1847 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001848 << NewNTTP->getType()
1849 << IsTemplateTemplateParm;
1850 Diag(OldNTTP->getLocation(),
1851 diag::note_template_nontype_parm_prev_declaration)
1852 << OldNTTP->getType();
1853 }
1854 return false;
1855 }
1856 } else {
1857 // The template parameter lists of template template
1858 // parameters must agree.
1859 // FIXME: Could we perform a faster "type" comparison here?
1860 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1861 "Only template template parameters handled here");
1862 TemplateTemplateParmDecl *OldTTP
1863 = cast<TemplateTemplateParmDecl>(*OldParm);
1864 TemplateTemplateParmDecl *NewTTP
1865 = cast<TemplateTemplateParmDecl>(*NewParm);
1866 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1867 OldTTP->getTemplateParameters(),
1868 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001869 /*IsTemplateTemplateParm=*/true,
1870 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00001871 return false;
1872 }
1873 }
1874
1875 return true;
1876}
1877
1878/// \brief Check whether a template can be declared within this scope.
1879///
1880/// If the template declaration is valid in this scope, returns
1881/// false. Otherwise, issues a diagnostic and returns true.
1882bool
1883Sema::CheckTemplateDeclScope(Scope *S,
1884 MultiTemplateParamsArg &TemplateParameterLists) {
1885 assert(TemplateParameterLists.size() > 0 && "Not a template");
1886
1887 // Find the nearest enclosing declaration scope.
1888 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1889 (S->getFlags() & Scope::TemplateParamScope) != 0)
1890 S = S->getParent();
1891
1892 TemplateParameterList *TemplateParams =
1893 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1894 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1895 SourceRange TemplateRange
1896 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1897
1898 // C++ [temp]p2:
1899 // A template-declaration can appear only as a namespace scope or
1900 // class scope declaration.
1901 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1902 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1903 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1904 return Diag(TemplateLoc, diag::err_template_linkage)
1905 << TemplateRange;
1906
1907 Ctx = Ctx->getParent();
1908 }
1909
1910 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1911 return false;
1912
1913 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1914 << TemplateRange;
1915}
Douglas Gregorcc636682009-02-17 23:15:12 +00001916
Douglas Gregorff668032009-05-13 18:28:20 +00001917/// \brief Check whether a class template specialization or explicit
1918/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00001919///
Douglas Gregorff668032009-05-13 18:28:20 +00001920/// This routine determines whether a class template specialization or
1921/// explicit instantiation can be declared in the current context
1922/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1923/// appropriate diagnostics if there was an error. It returns true if
1924// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00001925bool
1926Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1927 ClassTemplateSpecializationDecl *PrevDecl,
1928 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00001929 SourceRange ScopeSpecifierRange,
1930 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00001931 // C++ [temp.expl.spec]p2:
1932 // An explicit specialization shall be declared in the namespace
1933 // of which the template is a member, or, for member templates, in
1934 // the namespace of which the enclosing class or enclosing class
1935 // template is a member. An explicit specialization of a member
1936 // function, member class or static data member of a class
1937 // template shall be declared in the namespace of which the class
1938 // template is a member. Such a declaration may also be a
1939 // definition. If the declaration is not a definition, the
1940 // specialization may be defined later in the name- space in which
1941 // the explicit specialization was declared, or in a namespace
1942 // that encloses the one in which the explicit specialization was
1943 // declared.
1944 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1945 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregorff668032009-05-13 18:28:20 +00001946 << ExplicitInstantiation << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00001947 return true;
1948 }
1949
1950 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1951 DeclContext *TemplateContext
1952 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00001953 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
1954 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00001955 // There is no prior declaration of this entity, so this
1956 // specialization must be in the same context as the template
1957 // itself.
1958 if (DC != TemplateContext) {
1959 if (isa<TranslationUnitDecl>(TemplateContext))
1960 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1961 << ClassTemplate << ScopeSpecifierRange;
1962 else if (isa<NamespaceDecl>(TemplateContext))
1963 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1964 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1965 << ScopeSpecifierRange;
1966
1967 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1968 }
1969
1970 return false;
1971 }
1972
1973 // We have a previous declaration of this entity. Make sure that
1974 // this redeclaration (or definition) occurs in an enclosing namespace.
1975 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001976 // FIXME: In C++98, we would like to turn these errors into warnings,
1977 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00001978 bool SuppressedDiag = false;
1979 if (isa<TranslationUnitDecl>(TemplateContext)) {
1980 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1981 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1982 << ExplicitInstantiation << ClassTemplate << ScopeSpecifierRange;
1983 else
1984 SuppressedDiag = true;
1985 } else if (isa<NamespaceDecl>(TemplateContext)) {
1986 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1987 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1988 << ExplicitInstantiation << ClassTemplate
1989 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
1990 else
1991 SuppressedDiag = true;
1992 }
Douglas Gregor88b70942009-02-25 22:02:03 +00001993
Douglas Gregorff668032009-05-13 18:28:20 +00001994 if (!SuppressedDiag)
1995 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00001996 }
1997
1998 return false;
1999}
2000
Douglas Gregor212e81c2009-03-25 00:13:59 +00002001Sema::DeclResult
Douglas Gregorcc636682009-02-17 23:15:12 +00002002Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2003 SourceLocation KWLoc,
2004 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002005 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002006 SourceLocation TemplateNameLoc,
2007 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002008 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002009 SourceLocation *TemplateArgLocs,
2010 SourceLocation RAngleLoc,
2011 AttributeList *Attr,
2012 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002013 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002014 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002015 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002016 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002017
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002018 bool isPartialSpecialization = false;
2019
Douglas Gregor88b70942009-02-25 22:02:03 +00002020 // Check the validity of the template headers that introduce this
2021 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002022 // FIXME: Once we have member templates, we'll need to check
2023 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2024 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002025 if (TemplateParameterLists.size() == 0)
2026 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00002027 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002028 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00002029 TemplateParameterList *TemplateParams
2030 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattnerb28317a2009-03-28 19:18:32 +00002031 if (TemplateParameterLists.size() > 1) {
2032 Diag(TemplateParams->getTemplateLoc(),
2033 diag::err_template_spec_extra_headers);
2034 return true;
2035 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002036
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002037 // FIXME: We'll need more checks, here!
2038 if (TemplateParams->size() > 0)
2039 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002040 }
2041
Douglas Gregorcc636682009-02-17 23:15:12 +00002042 // Check that the specialization uses the same tag kind as the
2043 // original template.
2044 TagDecl::TagKind Kind;
2045 switch (TagSpec) {
2046 default: assert(0 && "Unknown tag type!");
2047 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2048 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2049 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2050 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002051 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2052 Kind, KWLoc,
2053 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002054 Diag(KWLoc, diag::err_use_with_wrong_tag)
2055 << ClassTemplate
2056 << CodeModificationHint::CreateReplacement(KWLoc,
2057 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002058 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2059 diag::note_previous_use);
2060 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2061 }
2062
Douglas Gregor40808ce2009-03-09 23:48:35 +00002063 // Translate the parser's template argument list in our AST format.
2064 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2065 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2066
Douglas Gregorcc636682009-02-17 23:15:12 +00002067 // Check that the template argument list is well-formed for this
2068 // template.
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002069 TemplateArgumentListBuilder ConvertedTemplateArgs;
Douglas Gregorcc636682009-02-17 23:15:12 +00002070 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002071 &TemplateArgs[0], TemplateArgs.size(),
2072 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002073 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002074
2075 assert((ConvertedTemplateArgs.size() ==
2076 ClassTemplate->getTemplateParameters()->size()) &&
2077 "Converted template argument list is too short!");
2078
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002079 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002080 // corresponds to these arguments.
2081 llvm::FoldingSetNodeID ID;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002082 if (isPartialSpecialization)
2083 // FIXME: Template parameter list matters, too
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002084 ClassTemplatePartialSpecializationDecl::Profile(ID,
2085 ConvertedTemplateArgs.getFlatArgumentList(),
2086 ConvertedTemplateArgs.flatSize());
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002087 else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002088 ClassTemplateSpecializationDecl::Profile(ID,
2089 ConvertedTemplateArgs.getFlatArgumentList(),
2090 ConvertedTemplateArgs.flatSize());
Douglas Gregorcc636682009-02-17 23:15:12 +00002091 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002092 ClassTemplateSpecializationDecl *PrevDecl = 0;
2093
2094 if (isPartialSpecialization)
2095 PrevDecl
2096 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2097 InsertPos);
2098 else
2099 PrevDecl
2100 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002101
2102 ClassTemplateSpecializationDecl *Specialization = 0;
2103
Douglas Gregor88b70942009-02-25 22:02:03 +00002104 // Check whether we can declare a class template specialization in
2105 // the current scope.
2106 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2107 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002108 SS.getRange(),
2109 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002110 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002111
Douglas Gregorcc636682009-02-17 23:15:12 +00002112 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2113 // Since the only prior class template specialization with these
2114 // arguments was referenced but not declared, reuse that
2115 // declaration node as our own, updating its source location to
2116 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002117 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002118 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002119 PrevDecl = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002120 } else if (isPartialSpecialization) {
2121 // FIXME: extra checking for partial specializations
2122
2123 // Create a new class template partial specialization declaration node.
2124 TemplateParameterList *TemplateParams
2125 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2126 ClassTemplatePartialSpecializationDecl *PrevPartial
2127 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2128 ClassTemplatePartialSpecializationDecl *Partial
2129 = ClassTemplatePartialSpecializationDecl::Create(Context,
2130 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002131 TemplateNameLoc,
2132 TemplateParams,
2133 ClassTemplate,
2134 ConvertedTemplateArgs,
2135 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002136
2137 if (PrevPartial) {
2138 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2139 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2140 } else {
2141 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2142 }
2143 Specialization = Partial;
Douglas Gregorcc636682009-02-17 23:15:12 +00002144 } else {
2145 // Create a new class template specialization declaration node for
2146 // this explicit specialization.
2147 Specialization
2148 = ClassTemplateSpecializationDecl::Create(Context,
2149 ClassTemplate->getDeclContext(),
2150 TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002151 ClassTemplate,
2152 ConvertedTemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +00002153 PrevDecl);
2154
2155 if (PrevDecl) {
2156 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2157 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2158 } else {
2159 ClassTemplate->getSpecializations().InsertNode(Specialization,
2160 InsertPos);
2161 }
2162 }
2163
2164 // Note that this is an explicit specialization.
2165 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2166
2167 // Check that this isn't a redefinition of this specialization.
2168 if (TK == TK_Definition) {
2169 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002170 // FIXME: Should also handle explicit specialization after implicit
2171 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002172 SourceRange Range(TemplateNameLoc, RAngleLoc);
2173 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002174 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002175 Diag(Def->getLocation(), diag::note_previous_definition);
2176 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002177 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002178 }
2179 }
2180
Douglas Gregorfc705b82009-02-26 22:19:44 +00002181 // Build the fully-sugared type for this class template
2182 // specialization as the user wrote in the specialization
2183 // itself. This means that we'll pretty-print the type retrieved
2184 // from the specialization's declaration the way that the user
2185 // actually wrote the specialization, rather than formatting the
2186 // name based on the "canonical" representation used to store the
2187 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002188 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002189 = Context.getTemplateSpecializationType(Name,
2190 &TemplateArgs[0],
2191 TemplateArgs.size(),
Douglas Gregore6258932009-03-19 00:39:20 +00002192 Context.getTypeDeclType(Specialization));
Douglas Gregor7532dc62009-03-30 22:58:21 +00002193 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002194 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002195
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002196 // C++ [temp.expl.spec]p9:
2197 // A template explicit specialization is in the scope of the
2198 // namespace in which the template was defined.
2199 //
2200 // We actually implement this paragraph where we set the semantic
2201 // context (in the creation of the ClassTemplateSpecializationDecl),
2202 // but we also maintain the lexical context where the actual
2203 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002204 Specialization->setLexicalDeclContext(CurContext);
2205
2206 // We may be starting the definition of this specialization.
2207 if (TK == TK_Definition)
2208 Specialization->startDefinition();
2209
2210 // Add the specialization into its lexical context, so that it can
2211 // be seen when iterating through the list of declarations in that
2212 // context. However, specializations are not found by name lookup.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002213 CurContext->addDecl(Context, Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002214 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002215}
Douglas Gregord57959a2009-03-27 23:10:48 +00002216
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002217// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002218Sema::DeclResult
2219Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2220 unsigned TagSpec,
2221 SourceLocation KWLoc,
2222 const CXXScopeSpec &SS,
2223 TemplateTy TemplateD,
2224 SourceLocation TemplateNameLoc,
2225 SourceLocation LAngleLoc,
2226 ASTTemplateArgsPtr TemplateArgsIn,
2227 SourceLocation *TemplateArgLocs,
2228 SourceLocation RAngleLoc,
2229 AttributeList *Attr) {
2230 // Find the class template we're specializing
2231 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2232 ClassTemplateDecl *ClassTemplate
2233 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2234
2235 // Check that the specialization uses the same tag kind as the
2236 // original template.
2237 TagDecl::TagKind Kind;
2238 switch (TagSpec) {
2239 default: assert(0 && "Unknown tag type!");
2240 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2241 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2242 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2243 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002244 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2245 Kind, KWLoc,
2246 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002247 Diag(KWLoc, diag::err_use_with_wrong_tag)
2248 << ClassTemplate
2249 << CodeModificationHint::CreateReplacement(KWLoc,
2250 ClassTemplate->getTemplatedDecl()->getKindName());
2251 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2252 diag::note_previous_use);
2253 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2254 }
2255
Douglas Gregorff668032009-05-13 18:28:20 +00002256 // C++0x [temp.explicit]p2:
2257 // [...] An explicit instantiation shall appear in an enclosing
2258 // namespace of its template. [...]
2259 //
2260 // This is C++ DR 275.
2261 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2262 TemplateNameLoc,
2263 SS.getRange(),
2264 /*ExplicitInstantiation=*/true))
2265 return true;
2266
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002267 // Translate the parser's template argument list in our AST format.
2268 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2269 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2270
2271 // Check that the template argument list is well-formed for this
2272 // template.
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002273 TemplateArgumentListBuilder ConvertedTemplateArgs;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002274 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00002275 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002276 RAngleLoc, ConvertedTemplateArgs))
2277 return true;
2278
2279 assert((ConvertedTemplateArgs.size() ==
2280 ClassTemplate->getTemplateParameters()->size()) &&
2281 "Converted template argument list is too short!");
2282
2283 // Find the class template specialization declaration that
2284 // corresponds to these arguments.
2285 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002286 ClassTemplateSpecializationDecl::Profile(ID,
2287 ConvertedTemplateArgs.getFlatArgumentList(),
2288 ConvertedTemplateArgs.flatSize());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002289 void *InsertPos = 0;
2290 ClassTemplateSpecializationDecl *PrevDecl
2291 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2292
2293 ClassTemplateSpecializationDecl *Specialization = 0;
2294
Douglas Gregorff668032009-05-13 18:28:20 +00002295 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002296 if (PrevDecl) {
Douglas Gregorff668032009-05-13 18:28:20 +00002297 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002298 // This particular specialization has already been declared or
2299 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002300 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2301 << Context.getTypeDeclType(PrevDecl);
2302 Diag(PrevDecl->getLocation(),
2303 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002304 return DeclPtrTy::make(PrevDecl);
2305 }
2306
Douglas Gregorff668032009-05-13 18:28:20 +00002307 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002308 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002309 // For a given set of template parameters, if an explicit
2310 // instantiation of a template appears after a declaration of
2311 // an explicit specialization for that template, the explicit
2312 // instantiation has no effect.
2313 if (!getLangOptions().CPlusPlus0x) {
2314 Diag(TemplateNameLoc,
2315 diag::ext_explicit_instantiation_after_specialization)
2316 << Context.getTypeDeclType(PrevDecl);
2317 Diag(PrevDecl->getLocation(),
2318 diag::note_previous_template_specialization);
2319 }
2320
2321 // Create a new class template specialization declaration node
2322 // for this explicit specialization. This node is only used to
2323 // record the existence of this explicit instantiation for
2324 // accurate reproduction of the source code; we don't actually
2325 // use it for anything, since it is semantically irrelevant.
2326 Specialization
2327 = ClassTemplateSpecializationDecl::Create(Context,
2328 ClassTemplate->getDeclContext(),
2329 TemplateNameLoc,
2330 ClassTemplate,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002331 ConvertedTemplateArgs, 0);
Douglas Gregorff668032009-05-13 18:28:20 +00002332 Specialization->setLexicalDeclContext(CurContext);
2333 CurContext->addDecl(Context, Specialization);
2334 return DeclPtrTy::make(Specialization);
2335 }
2336
2337 // If we have already (implicitly) instantiated this
2338 // specialization, there is less work to do.
2339 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2340 SpecializationRequiresInstantiation = false;
2341
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002342 // Since the only prior class template specialization with these
2343 // arguments was referenced but not declared, reuse that
2344 // declaration node as our own, updating its source location to
2345 // reflect our new declaration.
2346 Specialization = PrevDecl;
2347 Specialization->setLocation(TemplateNameLoc);
2348 PrevDecl = 0;
2349 } else {
2350 // Create a new class template specialization declaration node for
2351 // this explicit specialization.
2352 Specialization
2353 = ClassTemplateSpecializationDecl::Create(Context,
2354 ClassTemplate->getDeclContext(),
2355 TemplateNameLoc,
2356 ClassTemplate,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002357 ConvertedTemplateArgs, 0);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002358
2359 ClassTemplate->getSpecializations().InsertNode(Specialization,
2360 InsertPos);
2361 }
2362
2363 // Build the fully-sugared type for this explicit instantiation as
2364 // the user wrote in the explicit instantiation itself. This means
2365 // that we'll pretty-print the type retrieved from the
2366 // specialization's declaration the way that the user actually wrote
2367 // the explicit instantiation, rather than formatting the name based
2368 // on the "canonical" representation used to store the template
2369 // arguments in the specialization.
2370 QualType WrittenTy
2371 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00002372 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002373 TemplateArgs.size(),
2374 Context.getTypeDeclType(Specialization));
2375 Specialization->setTypeAsWritten(WrittenTy);
2376 TemplateArgsIn.release();
2377
2378 // Add the explicit instantiation into its lexical context. However,
2379 // since explicit instantiations are never found by name lookup, we
2380 // just put it into the declaration context directly.
2381 Specialization->setLexicalDeclContext(CurContext);
2382 CurContext->addDecl(Context, Specialization);
2383
2384 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002385 // A definition of a class template or class member template
2386 // shall be in scope at the point of the explicit instantiation of
2387 // the class template or class member template.
2388 //
2389 // This check comes when we actually try to perform the
2390 // instantiation.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002391 if (SpecializationRequiresInstantiation)
2392 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002393 else // Instantiate the members of this class template specialization.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002394 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002395
2396 return DeclPtrTy::make(Specialization);
2397}
2398
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002399// Explicit instantiation of a member class of a class template.
2400Sema::DeclResult
2401Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2402 unsigned TagSpec,
2403 SourceLocation KWLoc,
2404 const CXXScopeSpec &SS,
2405 IdentifierInfo *Name,
2406 SourceLocation NameLoc,
2407 AttributeList *Attr) {
2408
Douglas Gregor402abb52009-05-28 23:31:59 +00002409 bool Owned = false;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002410 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor402abb52009-05-28 23:31:59 +00002411 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002412 if (!TagD)
2413 return true;
2414
2415 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2416 if (Tag->isEnum()) {
2417 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2418 << Context.getTypeDeclType(Tag);
2419 return true;
2420 }
2421
Douglas Gregord0c87372009-05-27 17:30:49 +00002422 if (Tag->isInvalidDecl())
2423 return true;
2424
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002425 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2426 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2427 if (!Pattern) {
2428 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2429 << Context.getTypeDeclType(Record);
2430 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2431 return true;
2432 }
2433
2434 // C++0x [temp.explicit]p2:
2435 // [...] An explicit instantiation shall appear in an enclosing
2436 // namespace of its template. [...]
2437 //
2438 // This is C++ DR 275.
2439 if (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002440 // FIXME: In C++98, we would like to turn these errors into warnings,
2441 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002442 DeclContext *PatternContext
2443 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2444 if (!CurContext->Encloses(PatternContext)) {
2445 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2446 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2447 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2448 }
2449 }
2450
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002451 if (!Record->getDefinition(Context)) {
2452 // If the class has a definition, instantiate it (and all of its
2453 // members, recursively).
2454 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2455 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002456 getTemplateInstantiationArgs(Record),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002457 /*ExplicitInstantiation=*/true))
2458 return true;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002459 } else // Instantiate all of the members of class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002460 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002461 getTemplateInstantiationArgs(Record));
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002462
Mike Stump390b4cc2009-05-16 07:39:55 +00002463 // FIXME: We don't have any representation for explicit instantiations of
2464 // member classes. Such a representation is not needed for compilation, but it
2465 // should be available for clients that want to see all of the declarations in
2466 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002467 return TagD;
2468}
2469
Douglas Gregord57959a2009-03-27 23:10:48 +00002470Sema::TypeResult
2471Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2472 const IdentifierInfo &II, SourceLocation IdLoc) {
2473 NestedNameSpecifier *NNS
2474 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2475 if (!NNS)
2476 return true;
2477
2478 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002479 if (T.isNull())
2480 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002481 return T.getAsOpaquePtr();
2482}
2483
Douglas Gregor17343172009-04-01 00:28:59 +00002484Sema::TypeResult
2485Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2486 SourceLocation TemplateLoc, TypeTy *Ty) {
2487 QualType T = QualType::getFromOpaquePtr(Ty);
2488 NestedNameSpecifier *NNS
2489 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2490 const TemplateSpecializationType *TemplateId
2491 = T->getAsTemplateSpecializationType();
2492 assert(TemplateId && "Expected a template specialization type");
2493
2494 if (NNS->isDependent())
2495 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2496
2497 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2498}
2499
Douglas Gregord57959a2009-03-27 23:10:48 +00002500/// \brief Build the type that describes a C++ typename specifier,
2501/// e.g., "typename T::type".
2502QualType
2503Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2504 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00002505 CXXRecordDecl *CurrentInstantiation = 0;
2506 if (NNS->isDependent()) {
2507 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00002508
Douglas Gregor42af25f2009-05-11 19:58:34 +00002509 // If the nested-name-specifier does not refer to the current
2510 // instantiation, then build a typename type.
2511 if (!CurrentInstantiation)
2512 return Context.getTypenameType(NNS, &II);
2513 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002514
Douglas Gregor42af25f2009-05-11 19:58:34 +00002515 DeclContext *Ctx = 0;
2516
2517 if (CurrentInstantiation)
2518 Ctx = CurrentInstantiation;
2519 else {
2520 CXXScopeSpec SS;
2521 SS.setScopeRep(NNS);
2522 SS.setRange(Range);
2523 if (RequireCompleteDeclContext(SS))
2524 return QualType();
2525
2526 Ctx = computeDeclContext(SS);
2527 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002528 assert(Ctx && "No declaration context?");
2529
2530 DeclarationName Name(&II);
2531 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2532 false);
2533 unsigned DiagID = 0;
2534 Decl *Referenced = 0;
2535 switch (Result.getKind()) {
2536 case LookupResult::NotFound:
2537 if (Ctx->isTranslationUnit())
2538 DiagID = diag::err_typename_nested_not_found_global;
2539 else
2540 DiagID = diag::err_typename_nested_not_found;
2541 break;
2542
2543 case LookupResult::Found:
2544 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2545 // We found a type. Build a QualifiedNameType, since the
2546 // typename-specifier was just sugar. FIXME: Tell
2547 // QualifiedNameType that it has a "typename" prefix.
2548 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2549 }
2550
2551 DiagID = diag::err_typename_nested_not_type;
2552 Referenced = Result.getAsDecl();
2553 break;
2554
2555 case LookupResult::FoundOverloaded:
2556 DiagID = diag::err_typename_nested_not_type;
2557 Referenced = *Result.begin();
2558 break;
2559
2560 case LookupResult::AmbiguousBaseSubobjectTypes:
2561 case LookupResult::AmbiguousBaseSubobjects:
2562 case LookupResult::AmbiguousReference:
2563 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2564 return QualType();
2565 }
2566
2567 // If we get here, it's because name lookup did not find a
2568 // type. Emit an appropriate diagnostic and return an error.
2569 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2570 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2571 else
2572 Diag(Range.getEnd(), DiagID) << Range << Name;
2573 if (Referenced)
2574 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2575 << Name;
2576 return QualType();
2577}