blob: ee928bccaf9c726d001fd26b6d925c578b2d3079 [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000019#include "clang/Parse/Template.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000020#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000021#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000022#include "llvm/Support/Compiler.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000023#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000024using namespace clang;
25
Douglas Gregor2dd078a2009-09-02 22:59:36 +000026/// \brief Determine whether the declaration found is acceptable as the name
27/// of a template and, if so, return that template declaration. Otherwise,
28/// returns NULL.
29static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
30 if (!D)
31 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000032
Douglas Gregor2dd078a2009-09-02 22:59:36 +000033 if (isa<TemplateDecl>(D))
34 return D;
Mike Stump1eb44332009-09-09 15:08:12 +000035
Douglas Gregor2dd078a2009-09-02 22:59:36 +000036 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
37 // C++ [temp.local]p1:
38 // Like normal (non-template) classes, class templates have an
39 // injected-class-name (Clause 9). The injected-class-name
40 // can be used with or without a template-argument-list. When
41 // it is used without a template-argument-list, it is
42 // equivalent to the injected-class-name followed by the
43 // template-parameters of the class template enclosed in
44 // <>. When it is used with a template-argument-list, it
45 // refers to the specified class template specialization,
46 // which could be the current specialization or another
47 // specialization.
48 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000049 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000050 if (Record->getDescribedClassTemplate())
51 return Record->getDescribedClassTemplate();
52
53 if (ClassTemplateSpecializationDecl *Spec
54 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
55 return Spec->getSpecializedTemplate();
56 }
Mike Stump1eb44332009-09-09 15:08:12 +000057
Douglas Gregor2dd078a2009-09-02 22:59:36 +000058 return 0;
59 }
Mike Stump1eb44332009-09-09 15:08:12 +000060
Douglas Gregor2dd078a2009-09-02 22:59:36 +000061 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
62 if (!Ovl)
63 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000064
Douglas Gregor2dd078a2009-09-02 22:59:36 +000065 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
66 FEnd = Ovl->function_end();
67 F != FEnd; ++F) {
68 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
69 // We've found a function template. Determine whether there are
70 // any other function templates we need to bundle together in an
71 // OverloadedFunctionDecl
72 for (++F; F != FEnd; ++F) {
73 if (isa<FunctionTemplateDecl>(*F))
74 break;
75 }
Mike Stump1eb44332009-09-09 15:08:12 +000076
Douglas Gregor2dd078a2009-09-02 22:59:36 +000077 if (F != FEnd) {
78 // Build an overloaded function decl containing only the
79 // function templates in Ovl.
Mike Stump1eb44332009-09-09 15:08:12 +000080 OverloadedFunctionDecl *OvlTemplate
Douglas Gregor2dd078a2009-09-02 22:59:36 +000081 = OverloadedFunctionDecl::Create(Context,
82 Ovl->getDeclContext(),
83 Ovl->getDeclName());
84 OvlTemplate->addOverload(FuncTmpl);
85 OvlTemplate->addOverload(*F);
86 for (++F; F != FEnd; ++F) {
87 if (isa<FunctionTemplateDecl>(*F))
88 OvlTemplate->addOverload(*F);
89 }
Mike Stump1eb44332009-09-09 15:08:12 +000090
Douglas Gregor2dd078a2009-09-02 22:59:36 +000091 return OvlTemplate;
92 }
93
94 return FuncTmpl;
95 }
96 }
Mike Stump1eb44332009-09-09 15:08:12 +000097
Douglas Gregor2dd078a2009-09-02 22:59:36 +000098 return 0;
99}
100
101TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000102 const CXXScopeSpec &SS,
103 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000104 TypeTy *ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000105 bool EnteringContext,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000106 TemplateTy &TemplateResult) {
Douglas Gregor014e88d2009-11-03 23:16:33 +0000107 DeclarationName TName;
108
109 switch (Name.getKind()) {
110 case UnqualifiedId::IK_Identifier:
111 TName = DeclarationName(Name.Identifier);
112 break;
113
114 case UnqualifiedId::IK_OperatorFunctionId:
115 TName = Context.DeclarationNames.getCXXOperatorName(
116 Name.OperatorFunctionId.Operator);
117 break;
118
119 default:
120 return TNK_Non_template;
121 }
122
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000123 // Determine where to perform name lookup
124 DeclContext *LookupCtx = 0;
125 bool isDependent = false;
126 if (ObjectTypePtr) {
127 // This nested-name-specifier occurs in a member access expression, e.g.,
128 // x->B::f, and we are looking into the type of the object.
Douglas Gregor014e88d2009-11-03 23:16:33 +0000129 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000130 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
131 LookupCtx = computeDeclContext(ObjectType);
132 isDependent = ObjectType->isDependentType();
Douglas Gregor014e88d2009-11-03 23:16:33 +0000133 } else if (SS.isSet()) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000134 // This nested-name-specifier occurs after another nested-name-specifier,
135 // so long into the context associated with the prior nested-name-specifier.
136
Douglas Gregor014e88d2009-11-03 23:16:33 +0000137 LookupCtx = computeDeclContext(SS, EnteringContext);
138 isDependent = isDependentScopeSpecifier(SS);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000139 }
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000141 LookupResult Found;
142 bool ObjectTypeSearchedInScope = false;
143 if (LookupCtx) {
144 // Perform "qualified" name lookup into the declaration context we
145 // computed, which is either the type of the base of a member access
Mike Stump1eb44332009-09-09 15:08:12 +0000146 // expression or the declaration context associated with a prior
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000147 // nested-name-specifier.
148
149 // The declaration context must be complete.
Douglas Gregor014e88d2009-11-03 23:16:33 +0000150 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(SS))
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000151 return TNK_Non_template;
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Douglas Gregor014e88d2009-11-03 23:16:33 +0000153 LookupQualifiedName(Found, LookupCtx, TName, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000155 if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
156 // C++ [basic.lookup.classref]p1:
157 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump1eb44332009-09-09 15:08:12 +0000158 // immediately followed by an identifier followed by a <, the
159 // identifier must be looked up to determine whether the < is the
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000160 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump1eb44332009-09-09 15:08:12 +0000161 // The identifier is first looked up in the class of the object
162 // expression. If the identifier is not found, it is then looked up in
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000163 // the context of the entire postfix-expression and shall name a class
164 // or function template.
165 //
166 // FIXME: When we're instantiating a template, do we actually have to
167 // look in the scope of the template? Seems fishy...
Douglas Gregor014e88d2009-11-03 23:16:33 +0000168 LookupName(Found, S, TName, LookupOrdinaryName);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000169 ObjectTypeSearchedInScope = true;
170 }
171 } else if (isDependent) {
Mike Stump1eb44332009-09-09 15:08:12 +0000172 // We cannot look into a dependent object type or
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000173 return TNK_Non_template;
174 } else {
175 // Perform unqualified name lookup in the current scope.
Douglas Gregor014e88d2009-11-03 23:16:33 +0000176 LookupName(Found, S, TName, LookupOrdinaryName);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000177 }
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Douglas Gregor495c35d2009-08-25 22:51:20 +0000179 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump1eb44332009-09-09 15:08:12 +0000180 assert(!Found.isAmbiguous() &&
Douglas Gregor495c35d2009-08-25 22:51:20 +0000181 "Cannot handle template name-lookup ambiguities");
Douglas Gregor7532dc62009-03-30 22:58:21 +0000182
John McCallf36e02d2009-10-09 21:13:30 +0000183 NamedDecl *Template
184 = isAcceptableTemplateName(Context, Found.getAsSingleDecl(Context));
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000185 if (!Template)
186 return TNK_Non_template;
187
188 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
189 // C++ [basic.lookup.classref]p1:
Mike Stump1eb44332009-09-09 15:08:12 +0000190 // [...] If the lookup in the class of the object expression finds a
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000191 // template, the name is also looked up in the context of the entire
192 // postfix-expression and [...]
193 //
John McCallf36e02d2009-10-09 21:13:30 +0000194 LookupResult FoundOuter;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000195 LookupName(FoundOuter, S, TName, LookupOrdinaryName);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000196 // FIXME: Handle ambiguities in this lookup better
John McCallf36e02d2009-10-09 21:13:30 +0000197 NamedDecl *OuterTemplate
198 = isAcceptableTemplateName(Context, FoundOuter.getAsSingleDecl(Context));
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000200 if (!OuterTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +0000201 // - if the name is not found, the name found in the class of the
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000202 // object expression is used, otherwise
203 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000204 // - if the name is found in the context of the entire
205 // postfix-expression and does not name a class template, the name
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000206 // found in the class of the object expression is used, otherwise
207 } else {
208 // - if the name found is a class template, it must refer to the same
Mike Stump1eb44332009-09-09 15:08:12 +0000209 // entity as the one found in the class of the object expression,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000210 // otherwise the program is ill-formed.
211 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
Douglas Gregor014e88d2009-11-03 23:16:33 +0000212 Diag(Name.getSourceRange().getBegin(),
213 diag::err_nested_name_member_ref_lookup_ambiguous)
214 << TName
215 << Name.getSourceRange();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000216 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
217 << QualType::getFromOpaquePtr(ObjectTypePtr);
218 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump1eb44332009-09-09 15:08:12 +0000219
220 // Recover by taking the template that we found in the object
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000221 // expression's type.
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000222 }
Mike Stump1eb44332009-09-09 15:08:12 +0000223 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000224 }
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Douglas Gregor014e88d2009-11-03 23:16:33 +0000226 if (SS.isSet() && !SS.isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000227 NestedNameSpecifier *Qualifier
Douglas Gregor014e88d2009-11-03 23:16:33 +0000228 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +0000229 if (OverloadedFunctionDecl *Ovl
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000230 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump1eb44332009-09-09 15:08:12 +0000231 TemplateResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000232 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
233 Ovl));
234 else
Mike Stump1eb44332009-09-09 15:08:12 +0000235 TemplateResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000236 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump1eb44332009-09-09 15:08:12 +0000237 cast<TemplateDecl>(Template)));
238 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000239 = dyn_cast<OverloadedFunctionDecl>(Template)) {
240 TemplateResult = TemplateTy::make(TemplateName(Ovl));
241 } else {
242 TemplateResult = TemplateTy::make(
243 TemplateName(cast<TemplateDecl>(Template)));
244 }
Mike Stump1eb44332009-09-09 15:08:12 +0000245
246 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000247 isa<TemplateTemplateParmDecl>(Template))
248 return TNK_Type_template;
Mike Stump1eb44332009-09-09 15:08:12 +0000249
250 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000251 isa<OverloadedFunctionDecl>(Template)) &&
252 "Unhandled template kind in Sema::isTemplateName");
253 return TNK_Function_template;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000254}
255
Douglas Gregor72c3f312008-12-05 18:15:24 +0000256/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
257/// that the template parameter 'PrevDecl' is being shadowed by a new
258/// declaration at location Loc. Returns true to indicate that this is
259/// an error, and false otherwise.
260bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000261 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000262
263 // Microsoft Visual C++ permits template parameters to be shadowed.
264 if (getLangOptions().Microsoft)
265 return false;
266
267 // C++ [temp.local]p4:
268 // A template-parameter shall not be redeclared within its
269 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000270 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000271 << cast<NamedDecl>(PrevDecl)->getDeclName();
272 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
273 return true;
274}
275
Douglas Gregor2943aed2009-03-03 04:44:36 +0000276/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000277/// the parameter D to reference the templated declaration and return a pointer
278/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000279TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000280 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000281 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000282 return Temp;
283 }
284 return 0;
285}
286
Douglas Gregor788cd062009-11-11 01:00:40 +0000287static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
288 const ParsedTemplateArgument &Arg) {
289
290 switch (Arg.getKind()) {
291 case ParsedTemplateArgument::Type: {
292 DeclaratorInfo *DI;
293 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
294 if (!DI)
295 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation());
296 return TemplateArgumentLoc(TemplateArgument(T), DI);
297 }
298
299 case ParsedTemplateArgument::NonType: {
300 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
301 return TemplateArgumentLoc(TemplateArgument(E), E);
302 }
303
304 case ParsedTemplateArgument::Template: {
305 TemplateName Template
306 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
307 return TemplateArgumentLoc(TemplateArgument(Template),
308 Arg.getScopeSpec().getRange(),
309 Arg.getLocation());
310 }
311 }
312
313 llvm::llvm_unreachable("Unhandled parsed template argument");
314 return TemplateArgumentLoc();
315}
316
317/// \brief Translates template arguments as provided by the parser
318/// into template arguments used by semantic analysis.
319void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
320 llvm::SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs) {
321 TemplateArgs.reserve(TemplateArgsIn.size());
322
323 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
324 TemplateArgs.push_back(translateTemplateArgument(*this, TemplateArgsIn[I]));
325}
326
Douglas Gregor72c3f312008-12-05 18:15:24 +0000327/// ActOnTypeParameter - Called when a C++ template type parameter
328/// (e.g., "typename T") has been parsed. Typename specifies whether
329/// the keyword "typename" was used to declare the type parameter
330/// (otherwise, "class" was used), and KeyLoc is the location of the
331/// "class" or "typename" keyword. ParamName is the name of the
332/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump1eb44332009-09-09 15:08:12 +0000333/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000334/// If the type parameter has a default argument, it will be added
335/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000336Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000337 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000338 SourceLocation KeyLoc,
339 IdentifierInfo *ParamName,
340 SourceLocation ParamNameLoc,
341 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000342 assert(S->isTemplateParamScope() &&
343 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000344 bool Invalid = false;
345
346 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000347 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000348 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000349 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000350 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000351 }
352
Douglas Gregorddc29e12009-02-06 22:42:48 +0000353 SourceLocation Loc = ParamNameLoc;
354 if (!ParamName)
355 Loc = KeyLoc;
356
Douglas Gregor72c3f312008-12-05 18:15:24 +0000357 TemplateTypeParmDecl *Param
Mike Stump1eb44332009-09-09 15:08:12 +0000358 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
359 Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000360 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000361 if (Invalid)
362 Param->setInvalidDecl();
363
364 if (ParamName) {
365 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000366 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000367 IdResolver.AddDecl(Param);
368 }
369
Chris Lattnerb28317a2009-03-28 19:18:32 +0000370 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000371}
372
Douglas Gregord684b002009-02-10 19:49:53 +0000373/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000374/// Default) to the given template type parameter (TypeParam).
375void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000376 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000377 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000378 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000379 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000380 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000381
382 DeclaratorInfo *DefaultDInfo;
383 GetTypeFromParser(DefaultT, &DefaultDInfo);
384
385 assert(DefaultDInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000386
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000387 // C++0x [temp.param]p9:
388 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000389 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000390 if (Parm->isParameterPack()) {
391 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000392 return;
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Douglas Gregord684b002009-02-10 19:49:53 +0000395 // C++ [temp.param]p14:
396 // A template-parameter shall not be used in its own default argument.
397 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Douglas Gregord684b002009-02-10 19:49:53 +0000399 // Check the template argument itself.
John McCall833ca992009-10-29 08:12:44 +0000400 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000401 Parm->setInvalidDecl();
402 return;
403 }
404
John McCall833ca992009-10-29 08:12:44 +0000405 Parm->setDefaultArgument(DefaultDInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000406}
407
Douglas Gregor2943aed2009-03-03 04:44:36 +0000408/// \brief Check that the type of a non-type template parameter is
409/// well-formed.
410///
411/// \returns the (possibly-promoted) parameter type if valid;
412/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000413QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000414Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
415 // C++ [temp.param]p4:
416 //
417 // A non-type template-parameter shall have one of the following
418 // (optionally cv-qualified) types:
419 //
420 // -- integral or enumeration type,
421 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000422 // -- pointer to object or pointer to function,
423 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000424 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
425 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000426 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000427 T->isReferenceType() ||
428 // -- pointer to member.
429 T->isMemberPointerType() ||
430 // If T is a dependent type, we can't do the check now, so we
431 // assume that it is well-formed.
432 T->isDependentType())
433 return T;
434 // C++ [temp.param]p8:
435 //
436 // A non-type template-parameter of type "array of T" or
437 // "function returning T" is adjusted to be of type "pointer to
438 // T" or "pointer to function returning T", respectively.
439 else if (T->isArrayType())
440 // FIXME: Keep the type prior to promotion?
441 return Context.getArrayDecayedType(T);
442 else if (T->isFunctionType())
443 // FIXME: Keep the type prior to promotion?
444 return Context.getPointerType(T);
445
446 Diag(Loc, diag::err_template_nontype_parm_bad_type)
447 << T;
448
449 return QualType();
450}
451
Douglas Gregor72c3f312008-12-05 18:15:24 +0000452/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
453/// template parameter (e.g., "int Size" in "template<int Size>
454/// class Array") has been parsed. S is the current scope and D is
455/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000456Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000457 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000458 unsigned Position) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000459 DeclaratorInfo *DInfo = 0;
460 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000461
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000462 assert(S->isTemplateParamScope() &&
463 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000464 bool Invalid = false;
465
466 IdentifierInfo *ParamName = D.getIdentifier();
467 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000468 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000469 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000470 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000471 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000472 }
473
Douglas Gregor2943aed2009-03-03 04:44:36 +0000474 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000475 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000476 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000477 Invalid = true;
478 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000479
Douglas Gregor72c3f312008-12-05 18:15:24 +0000480 NonTypeTemplateParmDecl *Param
481 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000482 Depth, Position, ParamName, T, DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000483 if (Invalid)
484 Param->setInvalidDecl();
485
486 if (D.getIdentifier()) {
487 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000488 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000489 IdResolver.AddDecl(Param);
490 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000491 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000492}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000493
Douglas Gregord684b002009-02-10 19:49:53 +0000494/// \brief Adds a default argument to the given non-type template
495/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000496void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000497 SourceLocation EqualLoc,
498 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000499 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000500 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000501 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Douglas Gregord684b002009-02-10 19:49:53 +0000503 // C++ [temp.param]p14:
504 // A template-parameter shall not be used in its own default argument.
505 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Douglas Gregord684b002009-02-10 19:49:53 +0000507 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000508 TemplateArgument Converted;
509 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
510 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000511 TemplateParm->setInvalidDecl();
512 return;
513 }
514
Anders Carlssone9146f22009-05-01 19:49:17 +0000515 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000516}
517
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000518
519/// ActOnTemplateTemplateParameter - Called when a C++ template template
520/// parameter (e.g. T in template <template <typename> class T> class array)
521/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000522Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
523 SourceLocation TmpLoc,
524 TemplateParamsTy *Params,
525 IdentifierInfo *Name,
526 SourceLocation NameLoc,
527 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000528 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000529 assert(S->isTemplateParamScope() &&
530 "Template template parameter not in template parameter scope!");
531
532 // Construct the parameter object.
533 TemplateTemplateParmDecl *Param =
534 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
535 Position, Name,
536 (TemplateParameterList*)Params);
537
538 // Make sure the parameter is valid.
539 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
540 // do anything yet. However, if the template parameter list or (eventual)
541 // default value is ever invalidated, that will propagate here.
542 bool Invalid = false;
543 if (Invalid) {
544 Param->setInvalidDecl();
545 }
546
547 // If the tt-param has a name, then link the identifier into the scope
548 // and lookup mechanisms.
549 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000550 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000551 IdResolver.AddDecl(Param);
552 }
553
Chris Lattnerb28317a2009-03-28 19:18:32 +0000554 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000555}
556
Douglas Gregord684b002009-02-10 19:49:53 +0000557/// \brief Adds a default argument to the given template template
558/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000559void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000560 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000561 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000562 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000563 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000564
Douglas Gregord684b002009-02-10 19:49:53 +0000565 // C++ [temp.param]p14:
566 // A template-parameter shall not be used in its own default argument.
567 // FIXME: Implement this check! Needs a recursive walk over the types.
568
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000569 // Check only that we have a template template argument. We don't want to
570 // try to check well-formedness now, because our template template parameter
571 // might have dependent types in its template parameters, which we wouldn't
572 // be able to match now.
573 //
574 // If none of the template template parameter's template arguments mention
575 // other template parameters, we could actually perform more checking here.
576 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000577 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000578 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
579 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
580 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000581 return;
582 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000583
Douglas Gregor788cd062009-11-11 01:00:40 +0000584 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregord684b002009-02-10 19:49:53 +0000585}
586
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000587/// ActOnTemplateParameterList - Builds a TemplateParameterList that
588/// contains the template parameters in Params/NumParams.
589Sema::TemplateParamsTy *
590Sema::ActOnTemplateParameterList(unsigned Depth,
591 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000592 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000593 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000594 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000595 SourceLocation RAngleLoc) {
596 if (ExportLoc.isValid())
597 Diag(ExportLoc, diag::note_template_export_unsupported);
598
Douglas Gregorddc29e12009-02-06 22:42:48 +0000599 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000600 (NamedDecl**)Params, NumParams,
601 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000602}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000603
Douglas Gregor212e81c2009-03-25 00:13:59 +0000604Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000605Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000606 SourceLocation KWLoc, const CXXScopeSpec &SS,
607 IdentifierInfo *Name, SourceLocation NameLoc,
608 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000609 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000610 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000611 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000612 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000613 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000614 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000615
616 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000617 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000618 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000619
John McCall05b23ea2009-09-14 21:59:20 +0000620 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
621 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000622
623 // There is no such thing as an unnamed class template.
624 if (!Name) {
625 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000626 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000627 }
628
629 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000630 DeclContext *SemanticContext;
631 LookupResult Previous;
632 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregorf0510d42009-10-12 23:11:44 +0000633 if (RequireCompleteDeclContext(SS))
634 return true;
635
Douglas Gregor05396e22009-08-25 17:23:04 +0000636 SemanticContext = computeDeclContext(SS, true);
637 if (!SemanticContext) {
638 // FIXME: Produce a reasonable diagnostic here
639 return true;
640 }
Mike Stump1eb44332009-09-09 15:08:12 +0000641
John McCallf36e02d2009-10-09 21:13:30 +0000642 LookupQualifiedName(Previous, SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor05396e22009-08-25 17:23:04 +0000643 true);
644 } else {
645 SemanticContext = CurContext;
John McCallf36e02d2009-10-09 21:13:30 +0000646 LookupName(Previous, S, Name, LookupOrdinaryName, true);
Douglas Gregor05396e22009-08-25 17:23:04 +0000647 }
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Douglas Gregorddc29e12009-02-06 22:42:48 +0000649 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
650 NamedDecl *PrevDecl = 0;
651 if (Previous.begin() != Previous.end())
652 PrevDecl = *Previous.begin();
653
Douglas Gregor6102d982009-09-26 07:05:09 +0000654 if (PrevDecl && TUK == TUK_Friend) {
655 // C++ [namespace.memdef]p3:
656 // [...] When looking for a prior declaration of a class or a function
657 // declared as a friend, and when the name of the friend class or
658 // function is neither a qualified name nor a template-id, scopes outside
659 // the innermost enclosing namespace scope are not considered.
660 DeclContext *OutermostContext = CurContext;
661 while (!OutermostContext->isFileContext())
662 OutermostContext = OutermostContext->getLookupParent();
663
664 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
665 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
666 SemanticContext = PrevDecl->getDeclContext();
667 } else {
668 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregor259571e2009-10-30 22:42:42 +0000669 // context we computed is the semantic context for our new
Douglas Gregor6102d982009-09-26 07:05:09 +0000670 // declaration.
671 PrevDecl = 0;
672 SemanticContext = OutermostContext;
673 }
Douglas Gregor259571e2009-10-30 22:42:42 +0000674
675 if (CurContext->isDependentContext()) {
676 // If this is a dependent context, we don't want to link the friend
677 // class template to the template in scope, because that would perform
678 // checking of the template parameter lists that can't be performed
679 // until the outer context is instantiated.
680 PrevDecl = 0;
681 }
Douglas Gregor6102d982009-09-26 07:05:09 +0000682 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000683 PrevDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Douglas Gregorddc29e12009-02-06 22:42:48 +0000685 // If there is a previous declaration with the same name, check
686 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000687 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000688 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000689
690 // We may have found the injected-class-name of a class template,
691 // class template partial specialization, or class template specialization.
692 // In these cases, grab the template that is being defined or specialized.
693 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
694 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
695 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
696 PrevClassTemplate
697 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
698 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
699 PrevClassTemplate
700 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
701 ->getSpecializedTemplate();
702 }
703 }
704
Douglas Gregorddc29e12009-02-06 22:42:48 +0000705 if (PrevClassTemplate) {
706 // Ensure that the template parameter lists are compatible.
707 if (!TemplateParameterListsAreEqual(TemplateParams,
708 PrevClassTemplate->getTemplateParameters(),
709 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000710 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000711
712 // C++ [temp.class]p4:
713 // In a redeclaration, partial specialization, explicit
714 // specialization or explicit instantiation of a class template,
715 // the class-key shall agree in kind with the original class
716 // template declaration (7.1.5.3).
717 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000718 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000719 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000720 << Name
Mike Stump1eb44332009-09-09 15:08:12 +0000721 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +0000722 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000723 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000724 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000725 }
726
Douglas Gregorddc29e12009-02-06 22:42:48 +0000727 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000728 if (TUK == TUK_Definition) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000729 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
730 Diag(NameLoc, diag::err_redefinition) << Name;
731 Diag(Def->getLocation(), diag::note_previous_definition);
732 // FIXME: Would it make sense to try to "forget" the previous
733 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000734 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000735 }
736 }
737 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
738 // Maybe we will complain about the shadowed template parameter.
739 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
740 // Just pretend that we didn't see the previous declaration.
741 PrevDecl = 0;
742 } else if (PrevDecl) {
743 // C++ [temp]p5:
744 // A class template shall not have the same name as any other
745 // template, class, function, object, enumeration, enumerator,
746 // namespace, or type in the same scope (3.3), except as specified
747 // in (14.5.4).
748 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
749 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000750 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000751 }
752
Douglas Gregord684b002009-02-10 19:49:53 +0000753 // Check the template parameter list of this declaration, possibly
754 // merging in the template parameter list from the previous class
755 // template declaration.
756 if (CheckTemplateParameterList(TemplateParams,
757 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
758 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Douglas Gregor7da97d02009-05-10 22:57:19 +0000760 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000761 // declaration!
762
Mike Stump1eb44332009-09-09 15:08:12 +0000763 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000764 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000765 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000766 PrevClassTemplate->getTemplatedDecl() : 0,
767 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000768
769 ClassTemplateDecl *NewTemplate
770 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
771 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000772 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000773 NewClass->setDescribedClassTemplate(NewTemplate);
774
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000775 // Build the type for the class template declaration now.
Mike Stump1eb44332009-09-09 15:08:12 +0000776 QualType T =
777 Context.getTypeDeclType(NewClass,
778 PrevClassTemplate?
779 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000780 assert(T->isDependentType() && "Class template type is not dependent?");
781 (void)T;
782
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000783 // If we are providing an explicit specialization of a member that is a
784 // class template, make a note of that.
785 if (PrevClassTemplate &&
786 PrevClassTemplate->getInstantiatedFromMemberTemplate())
787 PrevClassTemplate->setMemberSpecialization();
788
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000789 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000790 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000791 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Douglas Gregorddc29e12009-02-06 22:42:48 +0000793 // Set the lexical context of these templates
794 NewClass->setLexicalDeclContext(CurContext);
795 NewTemplate->setLexicalDeclContext(CurContext);
796
John McCall0f434ec2009-07-31 02:45:11 +0000797 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000798 NewClass->startDefinition();
799
800 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000801 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000802
John McCall05b23ea2009-09-14 21:59:20 +0000803 if (TUK != TUK_Friend)
804 PushOnScopeChains(NewTemplate, S);
805 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000806 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000807 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000808 NewClass->setAccess(PrevClassTemplate->getAccess());
809 }
John McCall05b23ea2009-09-14 21:59:20 +0000810
Douglas Gregord85bea22009-09-26 06:47:28 +0000811 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
812 PrevClassTemplate != NULL);
813
John McCall05b23ea2009-09-14 21:59:20 +0000814 // Friend templates are visible in fairly strange ways.
815 if (!CurContext->isDependentContext()) {
816 DeclContext *DC = SemanticContext->getLookupContext();
817 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
818 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
819 PushOnScopeChains(NewTemplate, EnclosingScope,
820 /* AddToContext = */ false);
821 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000822
823 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
824 NewClass->getLocation(),
825 NewTemplate,
826 /*FIXME:*/NewClass->getLocation());
827 Friend->setAccess(AS_public);
828 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000829 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000830
Douglas Gregord684b002009-02-10 19:49:53 +0000831 if (Invalid) {
832 NewTemplate->setInvalidDecl();
833 NewClass->setInvalidDecl();
834 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000835 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000836}
837
Douglas Gregord684b002009-02-10 19:49:53 +0000838/// \brief Checks the validity of a template parameter list, possibly
839/// considering the template parameter list from a previous
840/// declaration.
841///
842/// If an "old" template parameter list is provided, it must be
843/// equivalent (per TemplateParameterListsAreEqual) to the "new"
844/// template parameter list.
845///
846/// \param NewParams Template parameter list for a new template
847/// declaration. This template parameter list will be updated with any
848/// default arguments that are carried through from the previous
849/// template parameter list.
850///
851/// \param OldParams If provided, template parameter list from a
852/// previous declaration of the same template. Default template
853/// arguments will be merged from the old template parameter list to
854/// the new template parameter list.
855///
856/// \returns true if an error occurred, false otherwise.
857bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
858 TemplateParameterList *OldParams) {
859 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Douglas Gregord684b002009-02-10 19:49:53 +0000861 // C++ [temp.param]p10:
862 // The set of default template-arguments available for use with a
863 // template declaration or definition is obtained by merging the
864 // default arguments from the definition (if in scope) and all
865 // declarations in scope in the same way default function
866 // arguments are (8.3.6).
867 bool SawDefaultArgument = false;
868 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000869
Anders Carlsson49d25572009-06-12 23:20:15 +0000870 bool SawParameterPack = false;
871 SourceLocation ParameterPackLoc;
872
Mike Stump1a35fde2009-02-11 23:03:27 +0000873 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000874 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000875 if (OldParams)
876 OldParam = OldParams->begin();
877
878 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
879 NewParamEnd = NewParams->end();
880 NewParam != NewParamEnd; ++NewParam) {
881 // Variables used to diagnose redundant default arguments
882 bool RedundantDefaultArg = false;
883 SourceLocation OldDefaultLoc;
884 SourceLocation NewDefaultLoc;
885
886 // Variables used to diagnose missing default arguments
887 bool MissingDefaultArg = false;
888
Anders Carlsson49d25572009-06-12 23:20:15 +0000889 // C++0x [temp.param]p11:
890 // If a template parameter of a class template is a template parameter pack,
891 // it must be the last template parameter.
892 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +0000893 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +0000894 diag::err_template_param_pack_must_be_last_template_parameter);
895 Invalid = true;
896 }
897
Douglas Gregord684b002009-02-10 19:49:53 +0000898 // Merge default arguments for template type parameters.
899 if (TemplateTypeParmDecl *NewTypeParm
900 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000901 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +0000902 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Anders Carlsson49d25572009-06-12 23:20:15 +0000904 if (NewTypeParm->isParameterPack()) {
905 assert(!NewTypeParm->hasDefaultArgument() &&
906 "Parameter packs can't have a default argument!");
907 SawParameterPack = true;
908 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000909 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +0000910 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +0000911 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
912 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
913 SawDefaultArgument = true;
914 RedundantDefaultArg = true;
915 PreviousDefaultArgLoc = NewDefaultLoc;
916 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
917 // Merge the default argument from the old declaration to the
918 // new declaration.
919 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +0000920 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +0000921 true);
922 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
923 } else if (NewTypeParm->hasDefaultArgument()) {
924 SawDefaultArgument = true;
925 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
926 } else if (SawDefaultArgument)
927 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000928 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +0000929 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000930 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000931 NonTypeTemplateParmDecl *OldNonTypeParm
932 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000933 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000934 NewNonTypeParm->hasDefaultArgument()) {
935 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
936 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
937 SawDefaultArgument = true;
938 RedundantDefaultArg = true;
939 PreviousDefaultArgLoc = NewDefaultLoc;
940 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
941 // Merge the default argument from the old declaration to the
942 // new declaration.
943 SawDefaultArgument = true;
944 // FIXME: We need to create a new kind of "default argument"
945 // expression that points to a previous template template
946 // parameter.
947 NewNonTypeParm->setDefaultArgument(
948 OldNonTypeParm->getDefaultArgument());
949 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
950 } else if (NewNonTypeParm->hasDefaultArgument()) {
951 SawDefaultArgument = true;
952 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
953 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000954 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000955 } else {
Douglas Gregord684b002009-02-10 19:49:53 +0000956 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000957 TemplateTemplateParmDecl *NewTemplateParm
958 = cast<TemplateTemplateParmDecl>(*NewParam);
959 TemplateTemplateParmDecl *OldTemplateParm
960 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000961 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000962 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000963 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
964 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +0000965 SawDefaultArgument = true;
966 RedundantDefaultArg = true;
967 PreviousDefaultArgLoc = NewDefaultLoc;
968 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
969 // Merge the default argument from the old declaration to the
970 // new declaration.
971 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000972 // FIXME: We need to create a new kind of "default argument" expression
973 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000974 NewTemplateParm->setDefaultArgument(
975 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +0000976 PreviousDefaultArgLoc
977 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +0000978 } else if (NewTemplateParm->hasDefaultArgument()) {
979 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +0000980 PreviousDefaultArgLoc
981 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +0000982 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000983 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +0000984 }
985
986 if (RedundantDefaultArg) {
987 // C++ [temp.param]p12:
988 // A template-parameter shall not be given default arguments
989 // by two different declarations in the same scope.
990 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
991 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
992 Invalid = true;
993 } else if (MissingDefaultArg) {
994 // C++ [temp.param]p11:
995 // If a template-parameter has a default template-argument,
996 // all subsequent template-parameters shall have a default
997 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +0000998 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +0000999 diag::err_template_param_default_arg_missing);
1000 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1001 Invalid = true;
1002 }
1003
1004 // If we have an old template parameter list that we're merging
1005 // in, move on to the next parameter.
1006 if (OldParams)
1007 ++OldParam;
1008 }
1009
1010 return Invalid;
1011}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001012
Mike Stump1eb44332009-09-09 15:08:12 +00001013/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001014/// specifier, returning the template parameter list that applies to the
1015/// name.
1016///
1017/// \param DeclStartLoc the start of the declaration that has a scope
1018/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001019///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001020/// \param SS the scope specifier that will be matched to the given template
1021/// parameter lists. This scope specifier precedes a qualified name that is
1022/// being declared.
1023///
1024/// \param ParamLists the template parameter lists, from the outermost to the
1025/// innermost template parameter lists.
1026///
1027/// \param NumParamLists the number of template parameter lists in ParamLists.
1028///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001029/// \param IsExplicitSpecialization will be set true if the entity being
1030/// declared is an explicit specialization, false otherwise.
1031///
Mike Stump1eb44332009-09-09 15:08:12 +00001032/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001033/// name that is preceded by the scope specifier @p SS. This template
1034/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001035/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001036/// template specialization), or may be NULL (if we were's declaring isn't
1037/// itself a template).
1038TemplateParameterList *
1039Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1040 const CXXScopeSpec &SS,
1041 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001042 unsigned NumParamLists,
1043 bool &IsExplicitSpecialization) {
1044 IsExplicitSpecialization = false;
1045
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001046 // Find the template-ids that occur within the nested-name-specifier. These
1047 // template-ids will match up with the template parameter lists.
1048 llvm::SmallVector<const TemplateSpecializationType *, 4>
1049 TemplateIdsInSpecifier;
1050 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1051 NNS; NNS = NNS->getPrefix()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001052 if (const TemplateSpecializationType *SpecType
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001053 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1054 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1055 if (!Template)
1056 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Ted Kremenek6217b802009-07-29 21:53:49 +00001058 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001059 ClassTemplateSpecializationDecl *SpecDecl
1060 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1061 // If the nested name specifier refers to an explicit specialization,
1062 // we don't need a template<> header.
Douglas Gregor861d0e82009-09-16 00:01:48 +00001063 // FIXME: revisit this approach once we cope with specializations
Douglas Gregorb88e8882009-07-30 17:40:51 +00001064 // properly.
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001065 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
1066 continue;
1067 }
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001069 TemplateIdsInSpecifier.push_back(SpecType);
1070 }
1071 }
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001073 // Reverse the list of template-ids in the scope specifier, so that we can
1074 // more easily match up the template-ids and the template parameter lists.
1075 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001077 SourceLocation FirstTemplateLoc = DeclStartLoc;
1078 if (NumParamLists)
1079 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001081 // Match the template-ids found in the specifier to the template parameter
1082 // lists.
1083 unsigned Idx = 0;
1084 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1085 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001086 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1087 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001088 if (Idx >= NumParamLists) {
1089 // We have a template-id without a corresponding template parameter
1090 // list.
1091 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001092 // FIXME: the location information here isn't great.
1093 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001094 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001095 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001096 << SS.getRange();
1097 } else {
1098 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1099 << SS.getRange()
1100 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1101 "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001102 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001103 }
1104 return 0;
1105 }
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001107 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001108 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001109 TemplateDecl *Template
Douglas Gregorb88e8882009-07-30 17:40:51 +00001110 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1111
Mike Stump1eb44332009-09-09 15:08:12 +00001112 if (ClassTemplateDecl *ClassTemplate
Douglas Gregorb88e8882009-07-30 17:40:51 +00001113 = dyn_cast<ClassTemplateDecl>(Template)) {
1114 TemplateParameterList *ExpectedTemplateParams = 0;
1115 // Is this template-id naming the primary template?
1116 if (Context.hasSameType(TemplateId,
1117 ClassTemplate->getInjectedClassNameType(Context)))
1118 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1119 // ... or a partial specialization?
1120 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1121 = ClassTemplate->findPartialSpecialization(TemplateId))
1122 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1123
1124 if (ExpectedTemplateParams)
Mike Stump1eb44332009-09-09 15:08:12 +00001125 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregorb88e8882009-07-30 17:40:51 +00001126 ExpectedTemplateParams,
1127 true);
Mike Stump1eb44332009-09-09 15:08:12 +00001128 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00001129 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001130 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001131 diag::err_template_param_list_matches_nontemplate)
1132 << TemplateId
1133 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001134 else
1135 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001136 }
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001138 // If there were at least as many template-ids as there were template
1139 // parameter lists, then there are no template parameter lists remaining for
1140 // the declaration itself.
1141 if (Idx >= NumParamLists)
1142 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001144 // If there were too many template parameter lists, complain about that now.
1145 if (Idx != NumParamLists - 1) {
1146 while (Idx < NumParamLists - 1) {
Mike Stump1eb44332009-09-09 15:08:12 +00001147 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001148 diag::err_template_spec_extra_headers)
1149 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1150 ParamLists[Idx]->getRAngleLoc());
1151 ++Idx;
1152 }
1153 }
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001155 // Return the last template parameter list, which corresponds to the
1156 // entity being declared.
1157 return ParamLists[NumParamLists - 1];
1158}
1159
Douglas Gregor7532dc62009-03-30 22:58:21 +00001160QualType Sema::CheckTemplateIdType(TemplateName Name,
1161 SourceLocation TemplateLoc,
1162 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001163 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001164 unsigned NumTemplateArgs,
1165 SourceLocation RAngleLoc) {
1166 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001167 if (!Template) {
1168 // The template name does not resolve to a template, so we just
1169 // build a dependent template-id type.
Douglas Gregorc45c2322009-03-31 00:43:58 +00001170 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001171 NumTemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001172 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001173
Douglas Gregor40808ce2009-03-09 23:48:35 +00001174 // Check that the template argument list is well-formed for this
1175 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001176 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1177 NumTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001178 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001179 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001180 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001181 return QualType();
1182
Mike Stump1eb44332009-09-09 15:08:12 +00001183 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001184 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001185 "Converted template argument list is too short!");
1186
1187 QualType CanonType;
1188
Douglas Gregor7532dc62009-03-30 22:58:21 +00001189 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +00001190 TemplateArgs,
1191 NumTemplateArgs)) {
1192 // This class template specialization is a dependent
1193 // type. Therefore, its canonical type is another class template
1194 // specialization type that contains all of the converted
1195 // arguments in canonical form. This ensures that, e.g., A<T> and
1196 // A<T, T> have identical types when A is declared as:
1197 //
1198 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001199 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001200 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001201 Converted.getFlatArguments(),
1202 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Douglas Gregor1275ae02009-07-28 23:00:59 +00001204 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001205 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001206 // In the future, we need to teach getTemplateSpecializationType to only
1207 // build the canonical type and return that to us.
1208 CanonType = Context.getCanonicalType(CanonType);
Mike Stump1eb44332009-09-09 15:08:12 +00001209 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001210 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001211 // Find the class template specialization declaration that
1212 // corresponds to these arguments.
1213 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001214 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001215 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001216 Converted.flatSize(),
1217 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001218 void *InsertPos = 0;
1219 ClassTemplateSpecializationDecl *Decl
1220 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1221 if (!Decl) {
1222 // This is the first time we have referenced this class template
1223 // specialization. Create the canonical declaration and add it to
1224 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001225 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001226 ClassTemplate->getDeclContext(),
John McCall9cc78072009-09-11 07:25:08 +00001227 ClassTemplate->getLocation(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001228 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001229 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001230 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1231 Decl->setLexicalDeclContext(CurContext);
1232 }
1233
1234 CanonType = Context.getTypeDeclType(Decl);
1235 }
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Douglas Gregor40808ce2009-03-09 23:48:35 +00001237 // Build the fully-sugared type for this class template
1238 // specialization, which refers back to the class template
1239 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +00001240 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1241 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001242}
1243
Douglas Gregorcc636682009-02-17 23:15:12 +00001244Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001245Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001246 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001247 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001248 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001249 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001250
Douglas Gregor40808ce2009-03-09 23:48:35 +00001251 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00001252 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor314b97f2009-11-10 19:49:08 +00001253 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001254
Douglas Gregor7532dc62009-03-30 22:58:21 +00001255 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001256 TemplateArgs.data(),
1257 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00001258 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001259 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001260
1261 if (Result.isNull())
1262 return true;
1263
John McCall833ca992009-10-29 08:12:44 +00001264 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1265 TemplateSpecializationTypeLoc TL
1266 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1267 TL.setTemplateNameLoc(TemplateLoc);
1268 TL.setLAngleLoc(LAngleLoc);
1269 TL.setRAngleLoc(RAngleLoc);
1270 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1271 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1272
1273 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001274}
John McCallf1bbbb42009-09-04 01:14:41 +00001275
John McCall6b2becf2009-09-08 17:47:29 +00001276Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1277 TagUseKind TUK,
1278 DeclSpec::TST TagSpec,
1279 SourceLocation TagLoc) {
1280 if (TypeResult.isInvalid())
1281 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001282
John McCall833ca992009-10-29 08:12:44 +00001283 // FIXME: preserve source info, ideally without copying the DI.
1284 DeclaratorInfo *DI;
1285 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001286
John McCall6b2becf2009-09-08 17:47:29 +00001287 // Verify the tag specifier.
1288 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001289
John McCall6b2becf2009-09-08 17:47:29 +00001290 if (const RecordType *RT = Type->getAs<RecordType>()) {
1291 RecordDecl *D = RT->getDecl();
1292
1293 IdentifierInfo *Id = D->getIdentifier();
1294 assert(Id && "templated class must have an identifier");
1295
1296 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1297 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001298 << Type
John McCall6b2becf2009-09-08 17:47:29 +00001299 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1300 D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001301 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001302 }
1303 }
1304
John McCall6b2becf2009-09-08 17:47:29 +00001305 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1306
1307 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001308}
1309
Douglas Gregorf17bb742009-10-22 17:20:55 +00001310Sema::OwningExprResult Sema::BuildTemplateIdExpr(NestedNameSpecifier *Qualifier,
1311 SourceRange QualifierRange,
1312 TemplateName Template,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001313 SourceLocation TemplateNameLoc,
1314 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001315 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001316 unsigned NumTemplateArgs,
1317 SourceLocation RAngleLoc) {
1318 // FIXME: Can we do any checking at this point? I guess we could check the
1319 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001320 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001321 // though.
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001322
1323 // Cope with an implicit member access in a C++ non-static member function.
1324 NamedDecl *D = Template.getAsTemplateDecl();
1325 if (!D)
1326 D = Template.getAsOverloadedFunctionDecl();
1327
Douglas Gregorf17bb742009-10-22 17:20:55 +00001328 CXXScopeSpec SS;
1329 SS.setRange(QualifierRange);
1330 SS.setScopeRep(Qualifier);
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001331 QualType ThisType, MemberType;
Douglas Gregorf17bb742009-10-22 17:20:55 +00001332 if (D && isImplicitMemberReference(&SS, D, TemplateNameLoc,
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001333 ThisType, MemberType)) {
1334 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
1335 return Owned(MemberExpr::Create(Context, This, true,
Douglas Gregorf17bb742009-10-22 17:20:55 +00001336 Qualifier, QualifierRange,
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001337 D, TemplateNameLoc, true,
1338 LAngleLoc, TemplateArgs,
1339 NumTemplateArgs, RAngleLoc,
1340 Context.OverloadTy));
1341 }
1342
Douglas Gregorf17bb742009-10-22 17:20:55 +00001343 return Owned(TemplateIdRefExpr::Create(Context, Context.OverloadTy,
1344 Qualifier, QualifierRange,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001345 Template, TemplateNameLoc, LAngleLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001346 TemplateArgs,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001347 NumTemplateArgs, RAngleLoc));
1348}
1349
Douglas Gregorf17bb742009-10-22 17:20:55 +00001350Sema::OwningExprResult Sema::ActOnTemplateIdExpr(const CXXScopeSpec &SS,
1351 TemplateTy TemplateD,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001352 SourceLocation TemplateNameLoc,
1353 SourceLocation LAngleLoc,
1354 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001355 SourceLocation RAngleLoc) {
1356 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001358 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00001359 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor314b97f2009-11-10 19:49:08 +00001360 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001361 TemplateArgsIn.release();
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Douglas Gregorf17bb742009-10-22 17:20:55 +00001363 return BuildTemplateIdExpr((NestedNameSpecifier *)SS.getScopeRep(),
1364 SS.getRange(),
1365 Template, TemplateNameLoc, LAngleLoc,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001366 TemplateArgs.data(), TemplateArgs.size(),
1367 RAngleLoc);
1368}
1369
Douglas Gregorc45c2322009-03-31 00:43:58 +00001370/// \brief Form a dependent template name.
1371///
1372/// This action forms a dependent template name given the template
1373/// name and its (presumably dependent) scope specifier. For
1374/// example, given "MetaFun::template apply", the scope specifier \p
1375/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1376/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001377Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001378Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001379 const CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001380 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001381 TypeTy *ObjectType) {
Mike Stump1eb44332009-09-09 15:08:12 +00001382 if ((ObjectType &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001383 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1384 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001385 // C++0x [temp.names]p5:
1386 // If a name prefixed by the keyword template is not the name of
1387 // a template, the program is ill-formed. [Note: the keyword
1388 // template may not be applied to non-template members of class
1389 // templates. -end note ] [ Note: as is the case with the
1390 // typename prefix, the template prefix is allowed in cases
1391 // where it is not strictly necessary; i.e., when the
1392 // nested-name-specifier or the expression on the left of the ->
1393 // or . is not dependent on a template-parameter, or the use
1394 // does not appear in the scope of a template. -end note]
1395 //
1396 // Note: C++03 was more strict here, because it banned the use of
1397 // the "template" keyword prior to a template-name that was not a
1398 // dependent name. C++ DR468 relaxed this requirement (the
1399 // "template" keyword is now permitted). We follow the C++0x
1400 // rules, even in C++03 mode, retroactively applying the DR.
1401 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001402 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001403 false, Template);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001404 if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001405 Diag(Name.getSourceRange().getBegin(),
1406 diag::err_template_kw_refers_to_non_template)
1407 << GetNameFromUnqualifiedId(Name)
1408 << Name.getSourceRange();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001409 return TemplateTy();
1410 }
1411
1412 return Template;
1413 }
1414
Mike Stump1eb44332009-09-09 15:08:12 +00001415 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001416 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001417
1418 switch (Name.getKind()) {
1419 case UnqualifiedId::IK_Identifier:
1420 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1421 Name.Identifier));
1422
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001423 case UnqualifiedId::IK_OperatorFunctionId:
1424 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1425 Name.OperatorFunctionId.Operator));
1426
Douglas Gregor014e88d2009-11-03 23:16:33 +00001427 default:
1428 break;
1429 }
1430
1431 Diag(Name.getSourceRange().getBegin(),
1432 diag::err_template_kw_refers_to_non_template)
1433 << GetNameFromUnqualifiedId(Name)
1434 << Name.getSourceRange();
1435 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001436}
1437
Mike Stump1eb44332009-09-09 15:08:12 +00001438bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001439 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001440 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001441 const TemplateArgument &Arg = AL.getArgument();
1442
Anders Carlsson436b1562009-06-13 00:33:33 +00001443 // Check template type parameter.
1444 if (Arg.getKind() != TemplateArgument::Type) {
1445 // C++ [temp.arg.type]p1:
1446 // A template-argument for a template-parameter which is a
1447 // type shall be a type-id.
1448
1449 // We have a template type parameter but the template argument
1450 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001451 SourceRange SR = AL.getSourceRange();
1452 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001453 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001454
Anders Carlsson436b1562009-06-13 00:33:33 +00001455 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001456 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001457
John McCall833ca992009-10-29 08:12:44 +00001458 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001459 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Anders Carlsson436b1562009-06-13 00:33:33 +00001461 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001462 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001463 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001464 return false;
1465}
1466
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001467/// \brief Substitute template arguments into the default template argument for
1468/// the given template type parameter.
1469///
1470/// \param SemaRef the semantic analysis object for which we are performing
1471/// the substitution.
1472///
1473/// \param Template the template that we are synthesizing template arguments
1474/// for.
1475///
1476/// \param TemplateLoc the location of the template name that started the
1477/// template-id we are checking.
1478///
1479/// \param RAngleLoc the location of the right angle bracket ('>') that
1480/// terminates the template-id.
1481///
1482/// \param Param the template template parameter whose default we are
1483/// substituting into.
1484///
1485/// \param Converted the list of template arguments provided for template
1486/// parameters that precede \p Param in the template parameter list.
1487///
1488/// \returns the substituted template argument, or NULL if an error occurred.
1489static DeclaratorInfo *
1490SubstDefaultTemplateArgument(Sema &SemaRef,
1491 TemplateDecl *Template,
1492 SourceLocation TemplateLoc,
1493 SourceLocation RAngleLoc,
1494 TemplateTypeParmDecl *Param,
1495 TemplateArgumentListBuilder &Converted) {
1496 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1497
1498 // If the argument type is dependent, instantiate it now based
1499 // on the previously-computed template arguments.
1500 if (ArgType->getType()->isDependentType()) {
1501 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1502 /*TakeArgs=*/false);
1503
1504 MultiLevelTemplateArgumentList AllTemplateArgs
1505 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1506
1507 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1508 Template, Converted.getFlatArguments(),
1509 Converted.flatSize(),
1510 SourceRange(TemplateLoc, RAngleLoc));
1511
1512 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1513 Param->getDefaultArgumentLoc(),
1514 Param->getDeclName());
1515 }
1516
1517 return ArgType;
1518}
1519
1520/// \brief Substitute template arguments into the default template argument for
1521/// the given non-type template parameter.
1522///
1523/// \param SemaRef the semantic analysis object for which we are performing
1524/// the substitution.
1525///
1526/// \param Template the template that we are synthesizing template arguments
1527/// for.
1528///
1529/// \param TemplateLoc the location of the template name that started the
1530/// template-id we are checking.
1531///
1532/// \param RAngleLoc the location of the right angle bracket ('>') that
1533/// terminates the template-id.
1534///
Douglas Gregor788cd062009-11-11 01:00:40 +00001535/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001536/// substituting into.
1537///
1538/// \param Converted the list of template arguments provided for template
1539/// parameters that precede \p Param in the template parameter list.
1540///
1541/// \returns the substituted template argument, or NULL if an error occurred.
1542static Sema::OwningExprResult
1543SubstDefaultTemplateArgument(Sema &SemaRef,
1544 TemplateDecl *Template,
1545 SourceLocation TemplateLoc,
1546 SourceLocation RAngleLoc,
1547 NonTypeTemplateParmDecl *Param,
1548 TemplateArgumentListBuilder &Converted) {
1549 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1550 /*TakeArgs=*/false);
1551
1552 MultiLevelTemplateArgumentList AllTemplateArgs
1553 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1554
1555 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1556 Template, Converted.getFlatArguments(),
1557 Converted.flatSize(),
1558 SourceRange(TemplateLoc, RAngleLoc));
1559
1560 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1561}
1562
Douglas Gregor788cd062009-11-11 01:00:40 +00001563/// \brief Substitute template arguments into the default template argument for
1564/// the given template template parameter.
1565///
1566/// \param SemaRef the semantic analysis object for which we are performing
1567/// the substitution.
1568///
1569/// \param Template the template that we are synthesizing template arguments
1570/// for.
1571///
1572/// \param TemplateLoc the location of the template name that started the
1573/// template-id we are checking.
1574///
1575/// \param RAngleLoc the location of the right angle bracket ('>') that
1576/// terminates the template-id.
1577///
1578/// \param Param the template template parameter whose default we are
1579/// substituting into.
1580///
1581/// \param Converted the list of template arguments provided for template
1582/// parameters that precede \p Param in the template parameter list.
1583///
1584/// \returns the substituted template argument, or NULL if an error occurred.
1585static TemplateName
1586SubstDefaultTemplateArgument(Sema &SemaRef,
1587 TemplateDecl *Template,
1588 SourceLocation TemplateLoc,
1589 SourceLocation RAngleLoc,
1590 TemplateTemplateParmDecl *Param,
1591 TemplateArgumentListBuilder &Converted) {
1592 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1593 /*TakeArgs=*/false);
1594
1595 MultiLevelTemplateArgumentList AllTemplateArgs
1596 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1597
1598 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1599 Template, Converted.getFlatArguments(),
1600 Converted.flatSize(),
1601 SourceRange(TemplateLoc, RAngleLoc));
1602
1603 return SemaRef.SubstTemplateName(
1604 Param->getDefaultArgument().getArgument().getAsTemplate(),
1605 Param->getDefaultArgument().getTemplateNameLoc(),
1606 AllTemplateArgs);
1607}
1608
Douglas Gregore7526412009-11-11 19:31:23 +00001609/// \brief Check that the given template argument corresponds to the given
1610/// template parameter.
1611bool Sema::CheckTemplateArgument(NamedDecl *Param,
1612 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00001613 TemplateDecl *Template,
1614 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001615 SourceLocation RAngleLoc,
1616 TemplateArgumentListBuilder &Converted) {
Douglas Gregord9e15302009-11-11 19:41:09 +00001617 // Check template type parameters.
1618 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00001619 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00001620
Douglas Gregord9e15302009-11-11 19:41:09 +00001621 // Check non-type template parameters.
1622 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00001623 // Do substitution on the type of the non-type template parameter
1624 // with the template arguments we've seen thus far.
1625 QualType NTTPType = NTTP->getType();
1626 if (NTTPType->isDependentType()) {
1627 // Do substitution on the type of the non-type template parameter.
1628 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1629 NTTP, Converted.getFlatArguments(),
1630 Converted.flatSize(),
1631 SourceRange(TemplateLoc, RAngleLoc));
1632
1633 TemplateArgumentList TemplateArgs(Context, Converted,
1634 /*TakeArgs=*/false);
1635 NTTPType = SubstType(NTTPType,
1636 MultiLevelTemplateArgumentList(TemplateArgs),
1637 NTTP->getLocation(),
1638 NTTP->getDeclName());
1639 // If that worked, check the non-type template parameter type
1640 // for validity.
1641 if (!NTTPType.isNull())
1642 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1643 NTTP->getLocation());
1644 if (NTTPType.isNull())
1645 return true;
1646 }
1647
1648 switch (Arg.getArgument().getKind()) {
1649 case TemplateArgument::Null:
1650 assert(false && "Should never see a NULL template argument here");
1651 return true;
1652
1653 case TemplateArgument::Expression: {
1654 Expr *E = Arg.getArgument().getAsExpr();
1655 TemplateArgument Result;
1656 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1657 return true;
1658
1659 Converted.Append(Result);
1660 break;
1661 }
1662
1663 case TemplateArgument::Declaration:
1664 case TemplateArgument::Integral:
1665 // We've already checked this template argument, so just copy
1666 // it to the list of converted arguments.
1667 Converted.Append(Arg.getArgument());
1668 break;
1669
1670 case TemplateArgument::Template:
1671 // We were given a template template argument. It may not be ill-formed;
1672 // see below.
1673 if (DependentTemplateName *DTN
1674 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1675 // We have a template argument such as \c T::template X, which we
1676 // parsed as a template template argument. However, since we now
1677 // know that we need a non-type template argument, convert this
1678 // template name into an expression.
1679 Expr *E = new (Context) UnresolvedDeclRefExpr(DTN->getIdentifier(),
1680 Context.DependentTy,
1681 Arg.getTemplateNameLoc(),
1682 Arg.getTemplateQualifierRange(),
1683 DTN->getQualifier(),
1684 /*isAddressOfOperand=*/false);
1685
1686 TemplateArgument Result;
1687 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1688 return true;
1689
1690 Converted.Append(Result);
1691 break;
1692 }
1693
1694 // We have a template argument that actually does refer to a class
1695 // template, template alias, or template template parameter, and
1696 // therefore cannot be a non-type template argument.
1697 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1698 << Arg.getSourceRange();
1699
1700 Diag(Param->getLocation(), diag::note_template_param_here);
1701 return true;
1702
1703 case TemplateArgument::Type: {
1704 // We have a non-type template parameter but the template
1705 // argument is a type.
1706
1707 // C++ [temp.arg]p2:
1708 // In a template-argument, an ambiguity between a type-id and
1709 // an expression is resolved to a type-id, regardless of the
1710 // form of the corresponding template-parameter.
1711 //
1712 // We warn specifically about this case, since it can be rather
1713 // confusing for users.
1714 QualType T = Arg.getArgument().getAsType();
1715 SourceRange SR = Arg.getSourceRange();
1716 if (T->isFunctionType())
1717 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1718 else
1719 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1720 Diag(Param->getLocation(), diag::note_template_param_here);
1721 return true;
1722 }
1723
1724 case TemplateArgument::Pack:
Douglas Gregord9e15302009-11-11 19:41:09 +00001725 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00001726 break;
1727 }
1728
1729 return false;
1730 }
1731
1732
1733 // Check template template parameters.
1734 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1735
1736 // Substitute into the template parameter list of the template
1737 // template parameter, since previously-supplied template arguments
1738 // may appear within the template template parameter.
1739 {
1740 // Set up a template instantiation context.
1741 LocalInstantiationScope Scope(*this);
1742 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1743 TempParm, Converted.getFlatArguments(),
1744 Converted.flatSize(),
1745 SourceRange(TemplateLoc, RAngleLoc));
1746
1747 TemplateArgumentList TemplateArgs(Context, Converted,
1748 /*TakeArgs=*/false);
1749 TempParm = cast_or_null<TemplateTemplateParmDecl>(
1750 SubstDecl(TempParm, CurContext,
1751 MultiLevelTemplateArgumentList(TemplateArgs)));
1752 if (!TempParm)
1753 return true;
1754
1755 // FIXME: TempParam is leaked.
1756 }
1757
1758 switch (Arg.getArgument().getKind()) {
1759 case TemplateArgument::Null:
1760 assert(false && "Should never see a NULL template argument here");
1761 return true;
1762
1763 case TemplateArgument::Template:
1764 if (CheckTemplateArgument(TempParm, Arg))
1765 return true;
1766
1767 Converted.Append(Arg.getArgument());
1768 break;
1769
1770 case TemplateArgument::Expression:
1771 case TemplateArgument::Type:
1772 // We have a template template parameter but the template
1773 // argument does not refer to a template.
1774 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1775 return true;
1776
1777 case TemplateArgument::Declaration:
1778 llvm::llvm_unreachable(
1779 "Declaration argument with template template parameter");
1780 break;
1781 case TemplateArgument::Integral:
1782 llvm::llvm_unreachable(
1783 "Integral argument with template template parameter");
1784 break;
1785
1786 case TemplateArgument::Pack:
Douglas Gregord9e15302009-11-11 19:41:09 +00001787 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00001788 break;
1789 }
1790
1791 return false;
1792}
1793
Douglas Gregorc15cb382009-02-09 23:23:08 +00001794/// \brief Check that the given template argument list is well-formed
1795/// for specializing the given template.
1796bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1797 SourceLocation TemplateLoc,
1798 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001799 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001800 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001801 SourceLocation RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001802 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001803 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001804 TemplateParameterList *Params = Template->getTemplateParameters();
1805 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001806 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001807 bool Invalid = false;
1808
Mike Stump1eb44332009-09-09 15:08:12 +00001809 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001810 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001812 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00001813 (NumArgs < Params->getMinRequiredArguments() &&
1814 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001815 // FIXME: point at either the first arg beyond what we can handle,
1816 // or the '>', depending on whether we have too many or too few
1817 // arguments.
1818 SourceRange Range;
1819 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001820 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001821 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1822 << (NumArgs > NumParams)
1823 << (isa<ClassTemplateDecl>(Template)? 0 :
1824 isa<FunctionTemplateDecl>(Template)? 1 :
1825 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1826 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001827 Diag(Template->getLocation(), diag::note_template_decl_here)
1828 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001829 Invalid = true;
1830 }
Mike Stump1eb44332009-09-09 15:08:12 +00001831
1832 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00001833 // [...] The type and form of each template-argument specified in
1834 // a template-id shall match the type and form specified for the
1835 // corresponding parameter declared by the template in its
1836 // template-parameter-list.
1837 unsigned ArgIdx = 0;
1838 for (TemplateParameterList::iterator Param = Params->begin(),
1839 ParamEnd = Params->end();
1840 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00001841 if (ArgIdx > NumArgs && PartialTemplateArgs)
1842 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Douglas Gregord9e15302009-11-11 19:41:09 +00001844 // If we have a template parameter pack, check every remaining template
1845 // argument against that template parameter pack.
1846 if ((*Param)->isTemplateParameterPack()) {
1847 Converted.BeginPack();
1848 for (; ArgIdx < NumArgs; ++ArgIdx) {
1849 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
1850 TemplateLoc, RAngleLoc, Converted)) {
1851 Invalid = true;
1852 break;
1853 }
1854 }
1855 Converted.EndPack();
1856 continue;
1857 }
1858
Douglas Gregorf35f8282009-11-11 21:54:23 +00001859 if (ArgIdx < NumArgs) {
1860 // Check the template argument we were given.
1861 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
1862 TemplateLoc, RAngleLoc, Converted))
1863 return true;
1864
1865 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001866 }
Douglas Gregore7526412009-11-11 19:31:23 +00001867
Douglas Gregorf35f8282009-11-11 21:54:23 +00001868 // We have a default template argument that we will use.
1869 TemplateArgumentLoc Arg;
1870
1871 // Retrieve the default template argument from the template
1872 // parameter. For each kind of template parameter, we substitute the
1873 // template arguments provided thus far and any "outer" template arguments
1874 // (when the template parameter was part of a nested template) into
1875 // the default argument.
1876 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1877 if (!TTP->hasDefaultArgument()) {
1878 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1879 break;
1880 }
1881
1882 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
1883 Template,
1884 TemplateLoc,
1885 RAngleLoc,
1886 TTP,
1887 Converted);
1888 if (!ArgType)
1889 return true;
1890
1891 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
1892 ArgType);
1893 } else if (NonTypeTemplateParmDecl *NTTP
1894 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1895 if (!NTTP->hasDefaultArgument()) {
1896 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1897 break;
1898 }
1899
1900 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
1901 TemplateLoc,
1902 RAngleLoc,
1903 NTTP,
1904 Converted);
1905 if (E.isInvalid())
1906 return true;
1907
1908 Expr *Ex = E.takeAs<Expr>();
1909 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
1910 } else {
1911 TemplateTemplateParmDecl *TempParm
1912 = cast<TemplateTemplateParmDecl>(*Param);
1913
1914 if (!TempParm->hasDefaultArgument()) {
1915 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1916 break;
1917 }
1918
1919 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
1920 TemplateLoc,
1921 RAngleLoc,
1922 TempParm,
1923 Converted);
1924 if (Name.isNull())
1925 return true;
1926
1927 Arg = TemplateArgumentLoc(TemplateArgument(Name),
1928 TempParm->getDefaultArgument().getTemplateQualifierRange(),
1929 TempParm->getDefaultArgument().getTemplateNameLoc());
1930 }
1931
1932 // Introduce an instantiation record that describes where we are using
1933 // the default template argument.
1934 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
1935 Converted.getFlatArguments(),
1936 Converted.flatSize(),
1937 SourceRange(TemplateLoc, RAngleLoc));
1938
1939 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00001940 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001941 RAngleLoc, Converted))
1942 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001943 }
1944
1945 return Invalid;
1946}
1947
1948/// \brief Check a template argument against its corresponding
1949/// template type parameter.
1950///
1951/// This routine implements the semantics of C++ [temp.arg.type]. It
1952/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001953bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001954 DeclaratorInfo *ArgInfo) {
1955 assert(ArgInfo && "invalid DeclaratorInfo");
1956 QualType Arg = ArgInfo->getType();
1957
Douglas Gregorc15cb382009-02-09 23:23:08 +00001958 // C++ [temp.arg.type]p2:
1959 // A local type, a type with no linkage, an unnamed type or a type
1960 // compounded from any of these types shall not be used as a
1961 // template-argument for a template type-parameter.
1962 //
1963 // FIXME: Perform the recursive and no-linkage type checks.
1964 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00001965 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001966 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00001967 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001968 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00001969 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
1970 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1971 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
1972 << QualType(Tag, 0) << SR;
1973 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00001974 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00001975 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1976 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001977 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1978 return true;
1979 }
1980
1981 return false;
1982}
1983
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001984/// \brief Checks whether the given template argument is the address
1985/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001986bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1987 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001988 bool Invalid = false;
1989
1990 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00001991 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001992 Arg = Cast->getSubExpr();
1993
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001994 // C++0x allows nullptr, and there's no further checking to be done for that.
1995 if (Arg->getType()->isNullPtrType())
1996 return false;
1997
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001998 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00001999 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002000 // A template-argument for a non-type, non-template
2001 // template-parameter shall be one of: [...]
2002 //
2003 // -- the address of an object or function with external
2004 // linkage, including function templates and function
2005 // template-ids but excluding non-static class members,
2006 // expressed as & id-expression where the & is optional if
2007 // the name refers to a function or array, or if the
2008 // corresponding template-parameter is a reference; or
2009 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002011 // Ignore (and complain about) any excess parentheses.
2012 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2013 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002014 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002015 diag::err_template_arg_extra_parens)
2016 << Arg->getSourceRange();
2017 Invalid = true;
2018 }
2019
2020 Arg = Parens->getSubExpr();
2021 }
2022
2023 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2024 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2025 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2026 } else
2027 DRE = dyn_cast<DeclRefExpr>(Arg);
2028
2029 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00002030 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002031 diag::err_template_arg_not_object_or_func_form)
2032 << Arg->getSourceRange();
2033
2034 // Cannot refer to non-static data members
2035 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2036 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2037 << Field << Arg->getSourceRange();
2038
2039 // Cannot refer to non-static member functions
2040 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2041 if (!Method->isStatic())
Mike Stump1eb44332009-09-09 15:08:12 +00002042 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002043 diag::err_template_arg_method)
2044 << Method << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002046 // Functions must have external linkage.
2047 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2048 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump1eb44332009-09-09 15:08:12 +00002049 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002050 diag::err_template_arg_function_not_extern)
2051 << Func << Arg->getSourceRange();
2052 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2053 << true;
2054 return true;
2055 }
2056
2057 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002058 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002059 return Invalid;
2060 }
2061
2062 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2063 if (!Var->hasGlobalStorage()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002064 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002065 diag::err_template_arg_object_not_extern)
2066 << Var << Arg->getSourceRange();
2067 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2068 << true;
2069 return true;
2070 }
2071
2072 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002073 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002074 return Invalid;
2075 }
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002077 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002078 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002079 diag::err_template_arg_not_object_or_func)
2080 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002081 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002082 diag::note_template_arg_refers_here);
2083 return true;
2084}
2085
2086/// \brief Checks whether the given template argument is a pointer to
2087/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump1eb44332009-09-09 15:08:12 +00002088bool
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002089Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002090 bool Invalid = false;
2091
2092 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002093 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002094 Arg = Cast->getSubExpr();
2095
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002096 // C++0x allows nullptr, and there's no further checking to be done for that.
2097 if (Arg->getType()->isNullPtrType())
2098 return false;
2099
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002100 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002101 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002102 // A template-argument for a non-type, non-template
2103 // template-parameter shall be one of: [...]
2104 //
2105 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002106 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002107
2108 // Ignore (and complain about) any excess parentheses.
2109 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2110 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002111 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002112 diag::err_template_arg_extra_parens)
2113 << Arg->getSourceRange();
2114 Invalid = true;
2115 }
2116
2117 Arg = Parens->getSubExpr();
2118 }
2119
2120 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
Douglas Gregora2813ce2009-10-23 18:54:35 +00002121 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2122 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2123 if (DRE && !DRE->getQualifier())
2124 DRE = 0;
2125 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002126
2127 if (!DRE)
2128 return Diag(Arg->getSourceRange().getBegin(),
2129 diag::err_template_arg_not_pointer_to_member_form)
2130 << Arg->getSourceRange();
2131
2132 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2133 assert((isa<FieldDecl>(DRE->getDecl()) ||
2134 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2135 "Only non-static member pointers can make it here");
2136
2137 // Okay: this is the address of a non-static member, and therefore
2138 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002139 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002140 return Invalid;
2141 }
2142
2143 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002144 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002145 diag::err_template_arg_not_pointer_to_member_form)
2146 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002147 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002148 diag::note_template_arg_refers_here);
2149 return true;
2150}
2151
Douglas Gregorc15cb382009-02-09 23:23:08 +00002152/// \brief Check a template argument against its corresponding
2153/// non-type template parameter.
2154///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002155/// This routine implements the semantics of C++ [temp.arg.nontype].
2156/// It returns true if an error occurred, and false otherwise. \p
2157/// InstantiatedParamType is the type of the non-type template
2158/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002159///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002160/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002161bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002162 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002163 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002164 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2165
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002166 // If either the parameter has a dependent type or the argument is
2167 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002168 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00002169 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2170 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002171 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002172 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002173 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002174
2175 // C++ [temp.arg.nontype]p5:
2176 // The following conversions are performed on each expression used
2177 // as a non-type template-argument. If a non-type
2178 // template-argument cannot be converted to the type of the
2179 // corresponding template-parameter then the program is
2180 // ill-formed.
2181 //
2182 // -- for a non-type template-parameter of integral or
2183 // enumeration type, integral promotions (4.5) and integral
2184 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002185 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002186 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002187 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002188 // C++ [temp.arg.nontype]p1:
2189 // A template-argument for a non-type, non-template
2190 // template-parameter shall be one of:
2191 //
2192 // -- an integral constant-expression of integral or enumeration
2193 // type; or
2194 // -- the name of a non-type template-parameter; or
2195 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002196 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002197 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002198 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002199 diag::err_template_arg_not_integral_or_enumeral)
2200 << ArgType << Arg->getSourceRange();
2201 Diag(Param->getLocation(), diag::note_template_param_here);
2202 return true;
2203 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002204 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002205 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2206 << ArgType << Arg->getSourceRange();
2207 return true;
2208 }
2209
2210 // FIXME: We need some way to more easily get the unqualified form
2211 // of the types without going all the way to the
2212 // canonical type.
2213 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2214 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2215 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2216 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2217
2218 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002219 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002220 // Okay: no conversion necessary
2221 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2222 !ParamType->isEnumeralType()) {
2223 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002224 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002225 } else {
2226 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002227 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002228 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002229 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002230 Diag(Param->getLocation(), diag::note_template_param_here);
2231 return true;
2232 }
2233
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002234 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002235 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002236 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002237
2238 if (!Arg->isValueDependent()) {
2239 // Check that an unsigned parameter does not receive a negative
2240 // value.
2241 if (IntegerType->isUnsignedIntegerType()
2242 && (Value.isSigned() && Value.isNegative())) {
2243 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2244 << Value.toString(10) << Param->getType()
2245 << Arg->getSourceRange();
2246 Diag(Param->getLocation(), diag::note_template_param_here);
2247 return true;
2248 }
2249
2250 // Check that we don't overflow the template parameter type.
2251 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2252 if (Value.getActiveBits() > AllowedBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00002253 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002254 diag::err_template_arg_too_large)
2255 << Value.toString(10) << Param->getType()
2256 << Arg->getSourceRange();
2257 Diag(Param->getLocation(), diag::note_template_param_here);
2258 return true;
2259 }
2260
2261 if (Value.getBitWidth() != AllowedBits)
2262 Value.extOrTrunc(AllowedBits);
2263 Value.setIsSigned(IntegerType->isSignedIntegerType());
2264 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002265
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002266 // Add the value of this argument to the list of converted
2267 // arguments. We use the bitwidth and signedness of the template
2268 // parameter.
2269 if (Arg->isValueDependent()) {
2270 // The argument is value-dependent. Create a new
2271 // TemplateArgument with the converted expression.
2272 Converted = TemplateArgument(Arg);
2273 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002274 }
2275
John McCall833ca992009-10-29 08:12:44 +00002276 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002277 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002278 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002279 return false;
2280 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002281
Douglas Gregorb86b0572009-02-11 01:18:59 +00002282 // Handle pointer-to-function, reference-to-function, and
2283 // pointer-to-member-function all in (roughly) the same way.
2284 if (// -- For a non-type template-parameter of type pointer to
2285 // function, only the function-to-pointer conversion (4.3) is
2286 // applied. If the template-argument represents a set of
2287 // overloaded functions (or a pointer to such), the matching
2288 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002289 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002290 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002291 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002292 // -- For a non-type template-parameter of type reference to
2293 // function, no conversions apply. If the template-argument
2294 // represents a set of overloaded functions, the matching
2295 // function is selected from the set (13.4).
2296 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002297 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002298 // -- For a non-type template-parameter of type pointer to
2299 // member function, no conversions apply. If the
2300 // template-argument represents a set of overloaded member
2301 // functions, the matching member function is selected from
2302 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002303 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002304 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002305 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002306 ->isFunctionType())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002307 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002308 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002309 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002310 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2311 ParamType->isMemberPointerType())) {
2312 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002313 if (ParamType->isMemberPointerType())
2314 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2315 else
2316 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002317 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002318 ArgType = Context.getPointerType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002319 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump1eb44332009-09-09 15:08:12 +00002320 } else if (FunctionDecl *Fn
Douglas Gregora35284b2009-02-11 00:19:33 +00002321 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002322 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2323 return true;
2324
Anders Carlsson96ad5332009-10-21 17:16:23 +00002325 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00002326 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002327 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002328 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman73c39ab2009-10-20 08:27:19 +00002329 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregora35284b2009-02-11 00:19:33 +00002330 }
2331 }
2332
Mike Stump1eb44332009-09-09 15:08:12 +00002333 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002334 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002335 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002336 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002337 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002338 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002339 Diag(Param->getLocation(), diag::note_template_param_here);
2340 return true;
2341 }
Mike Stump1eb44332009-09-09 15:08:12 +00002342
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002343 if (ParamType->isMemberPointerType()) {
2344 NamedDecl *Member = 0;
2345 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2346 return true;
2347
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002348 if (Member)
2349 Member = cast<NamedDecl>(Member->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002350 Converted = TemplateArgument(Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002351 return false;
2352 }
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002354 NamedDecl *Entity = 0;
2355 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2356 return true;
2357
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002358 if (Entity)
2359 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002360 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002361 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00002362 }
2363
Chris Lattnerfe90de72009-02-20 21:37:53 +00002364 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002365 // -- for a non-type template-parameter of type pointer to
2366 // object, qualification conversions (4.4) and the
2367 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002368 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002369 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002370 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002371
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002372 if (ArgType->isNullPtrType()) {
2373 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002374 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002375 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002376 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002377 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002378 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002379
Douglas Gregorb86b0572009-02-11 01:18:59 +00002380 if (IsQualificationConversion(ArgType, ParamType)) {
2381 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002382 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002383 }
Mike Stump1eb44332009-09-09 15:08:12 +00002384
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002385 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002386 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002387 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002388 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002389 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002390 Diag(Param->getLocation(), diag::note_template_param_here);
2391 return true;
2392 }
Mike Stump1eb44332009-09-09 15:08:12 +00002393
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002394 NamedDecl *Entity = 0;
2395 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2396 return true;
2397
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002398 if (Entity)
2399 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002400 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002401 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002402 }
Mike Stump1eb44332009-09-09 15:08:12 +00002403
Ted Kremenek6217b802009-07-29 21:53:49 +00002404 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002405 // -- For a non-type template-parameter of type reference to
2406 // object, no conversions apply. The type referred to by the
2407 // reference may be more cv-qualified than the (otherwise
2408 // identical) type of the template-argument. The
2409 // template-parameter is bound directly to the
2410 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002411 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002412 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002413
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002414 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002415 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002416 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002417 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002418 << Arg->getSourceRange();
2419 Diag(Param->getLocation(), diag::note_template_param_here);
2420 return true;
2421 }
2422
Mike Stump1eb44332009-09-09 15:08:12 +00002423 unsigned ParamQuals
Douglas Gregorb86b0572009-02-11 01:18:59 +00002424 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2425 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00002426
Douglas Gregorb86b0572009-02-11 01:18:59 +00002427 if ((ParamQuals | ArgQuals) != ParamQuals) {
2428 Diag(Arg->getSourceRange().getBegin(),
2429 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002430 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002431 << Arg->getSourceRange();
2432 Diag(Param->getLocation(), diag::note_template_param_here);
2433 return true;
2434 }
Mike Stump1eb44332009-09-09 15:08:12 +00002435
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002436 NamedDecl *Entity = 0;
2437 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2438 return true;
2439
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002440 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002441 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002442 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002443 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002444
2445 // -- For a non-type template-parameter of type pointer to data
2446 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002447 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00002448 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2449
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002450 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002451 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002452 } else if (ArgType->isNullPtrType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002453 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002454 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002455 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002456 } else {
2457 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002458 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002459 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002460 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002461 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002462 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002463 }
2464
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002465 NamedDecl *Member = 0;
2466 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2467 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002468
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002469 if (Member)
2470 Member = cast<NamedDecl>(Member->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002471 Converted = TemplateArgument(Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002472 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002473}
2474
2475/// \brief Check a template argument against its corresponding
2476/// template template parameter.
2477///
2478/// This routine implements the semantics of C++ [temp.arg.template].
2479/// It returns true if an error occurred, and false otherwise.
2480bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00002481 const TemplateArgumentLoc &Arg) {
2482 TemplateName Name = Arg.getArgument().getAsTemplate();
2483 TemplateDecl *Template = Name.getAsTemplateDecl();
2484 if (!Template) {
2485 // Any dependent template name is fine.
2486 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2487 return false;
2488 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002489
2490 // C++ [temp.arg.template]p1:
2491 // A template-argument for a template template-parameter shall be
2492 // the name of a class template, expressed as id-expression. Only
2493 // primary class templates are considered when matching the
2494 // template template argument with the corresponding parameter;
2495 // partial specializations are not considered even if their
2496 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002497 //
2498 // Note that we also allow template template parameters here, which
2499 // will happen when we are dealing with, e.g., class template
2500 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002501 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002502 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002503 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00002504 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00002505 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00002506 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002507 << Template;
2508 }
2509
2510 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2511 Param->getTemplateParameters(),
2512 true, true,
Douglas Gregor788cd062009-11-11 01:00:40 +00002513 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002514}
2515
Douglas Gregorddc29e12009-02-06 22:42:48 +00002516/// \brief Determine whether the given template parameter lists are
2517/// equivalent.
2518///
Mike Stump1eb44332009-09-09 15:08:12 +00002519/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00002520/// source code as part of a new template declaration.
2521///
2522/// \param Old The old template parameter list, typically found via
2523/// name lookup of the template declared with this template parameter
2524/// list.
2525///
2526/// \param Complain If true, this routine will produce a diagnostic if
2527/// the template parameter lists are not equivalent.
2528///
Douglas Gregordd0574e2009-02-10 00:24:35 +00002529/// \param IsTemplateTemplateParm If true, this routine is being
2530/// called to compare the template parameter lists of a template
2531/// template parameter.
2532///
2533/// \param TemplateArgLoc If this source location is valid, then we
2534/// are actually checking the template parameter list of a template
2535/// argument (New) against the template parameter list of its
2536/// corresponding template template parameter (Old). We produce
2537/// slightly different diagnostics in this scenario.
2538///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002539/// \returns True if the template parameter lists are equal, false
2540/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002541bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00002542Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2543 TemplateParameterList *Old,
2544 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002545 bool IsTemplateTemplateParm,
2546 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002547 if (Old->size() != New->size()) {
2548 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002549 unsigned NextDiag = diag::err_template_param_list_different_arity;
2550 if (TemplateArgLoc.isValid()) {
2551 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2552 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00002553 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002554 Diag(New->getTemplateLoc(), NextDiag)
2555 << (New->size() > Old->size())
2556 << IsTemplateTemplateParm
2557 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002558 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2559 << IsTemplateTemplateParm
2560 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2561 }
2562
2563 return false;
2564 }
2565
2566 for (TemplateParameterList::iterator OldParm = Old->begin(),
2567 OldParmEnd = Old->end(), NewParm = New->begin();
2568 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2569 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002570 if (Complain) {
2571 unsigned NextDiag = diag::err_template_param_different_kind;
2572 if (TemplateArgLoc.isValid()) {
2573 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2574 NextDiag = diag::note_template_param_different_kind;
2575 }
2576 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor9148c3f2009-11-11 19:13:48 +00002577 << IsTemplateTemplateParm;
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002578 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor9148c3f2009-11-11 19:13:48 +00002579 << IsTemplateTemplateParm;
Douglas Gregordd0574e2009-02-10 00:24:35 +00002580 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002581 return false;
2582 }
2583
2584 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2585 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002586 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00002587 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002588 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2589 // The types of non-type template parameters must agree.
2590 NonTypeTemplateParmDecl *NewNTTP
2591 = cast<NonTypeTemplateParmDecl>(*NewParm);
2592 if (Context.getCanonicalType(OldNTTP->getType()) !=
2593 Context.getCanonicalType(NewNTTP->getType())) {
2594 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002595 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2596 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002597 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002598 diag::err_template_arg_template_params_mismatch);
2599 NextDiag = diag::note_template_nontype_parm_different_type;
2600 }
2601 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002602 << NewNTTP->getType()
2603 << IsTemplateTemplateParm;
Mike Stump1eb44332009-09-09 15:08:12 +00002604 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00002605 diag::note_template_nontype_parm_prev_declaration)
2606 << OldNTTP->getType();
2607 }
2608 return false;
2609 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +00002610 assert(OldNTTP->getDepth() == NewNTTP->getDepth() &&
2611 "Non-type template parameter depth mismatch");
2612 assert(OldNTTP->getPosition() == NewNTTP->getPosition() &&
2613 "Non-type template parameter position mismatch");
Douglas Gregorddc29e12009-02-06 22:42:48 +00002614 } else {
2615 // The template parameter lists of template template
2616 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00002617 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00002618 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00002619 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002620 = cast<TemplateTemplateParmDecl>(*OldParm);
2621 TemplateTemplateParmDecl *NewTTP
2622 = cast<TemplateTemplateParmDecl>(*NewParm);
2623 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2624 OldTTP->getTemplateParameters(),
2625 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002626 /*IsTemplateTemplateParm=*/true,
2627 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002628 return false;
Douglas Gregor9148c3f2009-11-11 19:13:48 +00002629
2630 assert(OldTTP->getDepth() == NewTTP->getDepth() &&
2631 "Template template parameter depth mismatch");
2632 assert(OldTTP->getPosition() == NewTTP->getPosition() &&
2633 "Template template parameter position mismatch");
Douglas Gregorddc29e12009-02-06 22:42:48 +00002634 }
2635 }
2636
2637 return true;
2638}
2639
2640/// \brief Check whether a template can be declared within this scope.
2641///
2642/// If the template declaration is valid in this scope, returns
2643/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00002644bool
Douglas Gregor05396e22009-08-25 17:23:04 +00002645Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002646 // Find the nearest enclosing declaration scope.
2647 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2648 (S->getFlags() & Scope::TemplateParamScope) != 0)
2649 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002650
Douglas Gregorddc29e12009-02-06 22:42:48 +00002651 // C++ [temp]p2:
2652 // A template-declaration can appear only as a namespace scope or
2653 // class scope declaration.
2654 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002655 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2656 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00002657 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00002658 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002659
Eli Friedman1503f772009-07-31 01:43:05 +00002660 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002661 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002662
2663 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2664 return false;
2665
Mike Stump1eb44332009-09-09 15:08:12 +00002666 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002667 diag::err_template_outside_namespace_or_class_scope)
2668 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002669}
Douglas Gregorcc636682009-02-17 23:15:12 +00002670
Douglas Gregord5cb8762009-10-07 00:13:32 +00002671/// \brief Determine what kind of template specialization the given declaration
2672/// is.
2673static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2674 if (!D)
2675 return TSK_Undeclared;
2676
Douglas Gregorf6b11852009-10-08 15:14:33 +00002677 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2678 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00002679 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2680 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002681 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2682 return Var->getTemplateSpecializationKind();
2683
Douglas Gregord5cb8762009-10-07 00:13:32 +00002684 return TSK_Undeclared;
2685}
2686
Douglas Gregor9302da62009-10-14 23:50:59 +00002687/// \brief Check whether a specialization is well-formed in the current
2688/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00002689///
Douglas Gregor9302da62009-10-14 23:50:59 +00002690/// This routine determines whether a template specialization can be declared
2691/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002692///
2693/// \param S the semantic analysis object for which this check is being
2694/// performed.
2695///
2696/// \param Specialized the entity being specialized or instantiated, which
2697/// may be a kind of template (class template, function template, etc.) or
2698/// a member of a class template (member function, static data member,
2699/// member class).
2700///
2701/// \param PrevDecl the previous declaration of this entity, if any.
2702///
2703/// \param Loc the location of the explicit specialization or instantiation of
2704/// this entity.
2705///
2706/// \param IsPartialSpecialization whether this is a partial specialization of
2707/// a class template.
2708///
Douglas Gregord5cb8762009-10-07 00:13:32 +00002709/// \returns true if there was an error that we cannot recover from, false
2710/// otherwise.
2711static bool CheckTemplateSpecializationScope(Sema &S,
2712 NamedDecl *Specialized,
2713 NamedDecl *PrevDecl,
2714 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00002715 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002716 // Keep these "kind" numbers in sync with the %select statements in the
2717 // various diagnostics emitted by this routine.
2718 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002719 bool isTemplateSpecialization = false;
2720 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002721 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002722 isTemplateSpecialization = true;
2723 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002724 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002725 isTemplateSpecialization = true;
2726 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00002727 EntityKind = 3;
2728 else if (isa<VarDecl>(Specialized))
2729 EntityKind = 4;
2730 else if (isa<RecordDecl>(Specialized))
2731 EntityKind = 5;
2732 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00002733 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2734 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00002735 return true;
2736 }
2737
Douglas Gregor88b70942009-02-25 22:02:03 +00002738 // C++ [temp.expl.spec]p2:
2739 // An explicit specialization shall be declared in the namespace
2740 // of which the template is a member, or, for member templates, in
2741 // the namespace of which the enclosing class or enclosing class
2742 // template is a member. An explicit specialization of a member
2743 // function, member class or static data member of a class
2744 // template shall be declared in the namespace of which the class
2745 // template is a member. Such a declaration may also be a
2746 // definition. If the declaration is not a definition, the
2747 // specialization may be defined later in the name- space in which
2748 // the explicit specialization was declared, or in a namespace
2749 // that encloses the one in which the explicit specialization was
2750 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00002751 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2752 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00002753 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00002754 return true;
2755 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002756
Douglas Gregor0a407472009-10-07 17:30:37 +00002757 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2758 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00002759 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00002760 return true;
2761 }
2762
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002763 // C++ [temp.class.spec]p6:
2764 // A class template partial specialization may be declared or redeclared
2765 // in any namespace scope in which its definition may be defined (14.5.1
2766 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002767 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002768 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00002769 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002770 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00002771 if ((!PrevDecl ||
2772 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2773 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2774 // There is no prior declaration of this entity, so this
2775 // specialization must be in the same context as the template
2776 // itself.
2777 if (!DC->Equals(SpecializedContext)) {
2778 if (isa<TranslationUnitDecl>(SpecializedContext))
2779 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2780 << EntityKind << Specialized;
2781 else if (isa<NamespaceDecl>(SpecializedContext))
2782 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2783 << EntityKind << Specialized
2784 << cast<NamedDecl>(SpecializedContext);
2785
2786 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2787 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002788 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002789 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00002790
2791 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00002792 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00002793 // Note that HandleDeclarator() performs this check for explicit
2794 // specializations of function templates, static data members, and member
2795 // functions, so we skip the check here for those kinds of entities.
2796 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002797 // Should we refactor that check, so that it occurs later?
2798 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00002799 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2800 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002801 if (isa<TranslationUnitDecl>(SpecializedContext))
2802 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2803 << EntityKind << Specialized;
2804 else if (isa<NamespaceDecl>(SpecializedContext))
2805 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2806 << EntityKind << Specialized
2807 << cast<NamedDecl>(SpecializedContext);
2808
Douglas Gregor9302da62009-10-14 23:50:59 +00002809 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00002810 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00002811
2812 // FIXME: check for specialization-after-instantiation errors and such.
2813
Douglas Gregor88b70942009-02-25 22:02:03 +00002814 return false;
2815}
Douglas Gregord5cb8762009-10-07 00:13:32 +00002816
Douglas Gregore94866f2009-06-12 21:21:02 +00002817/// \brief Check the non-type template arguments of a class template
2818/// partial specialization according to C++ [temp.class.spec]p9.
2819///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002820/// \param TemplateParams the template parameters of the primary class
2821/// template.
2822///
2823/// \param TemplateArg the template arguments of the class template
2824/// partial specialization.
2825///
2826/// \param MirrorsPrimaryTemplate will be set true if the class
2827/// template partial specialization arguments are identical to the
2828/// implicit template arguments of the primary template. This is not
2829/// necessarily an error (C++0x), and it is left to the caller to diagnose
2830/// this condition when it is an error.
2831///
Douglas Gregore94866f2009-06-12 21:21:02 +00002832/// \returns true if there was an error, false otherwise.
2833bool Sema::CheckClassTemplatePartialSpecializationArgs(
2834 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002835 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002836 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002837 // FIXME: the interface to this function will have to change to
2838 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002839 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002840
Anders Carlssonfb250522009-06-23 01:26:57 +00002841 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00002842
Douglas Gregore94866f2009-06-12 21:21:02 +00002843 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002844 // Determine whether the template argument list of the partial
2845 // specialization is identical to the implicit argument list of
2846 // the primary template. The caller may need to diagnostic this as
2847 // an error per C++ [temp.class.spec]p9b3.
2848 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00002849 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002850 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2851 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002852 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002853 MirrorsPrimaryTemplate = false;
2854 } else if (TemplateTemplateParmDecl *TTP
2855 = dyn_cast<TemplateTemplateParmDecl>(
2856 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00002857 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00002858 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00002859 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002860 if (!ArgDecl ||
2861 ArgDecl->getIndex() != TTP->getIndex() ||
2862 ArgDecl->getDepth() != TTP->getDepth())
2863 MirrorsPrimaryTemplate = false;
2864 }
2865 }
2866
Mike Stump1eb44332009-09-09 15:08:12 +00002867 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00002868 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002869 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002870 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002871 }
2872
Anders Carlsson6360be72009-06-13 18:20:51 +00002873 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002874 if (!ArgExpr) {
2875 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002876 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002877 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002878
2879 // C++ [temp.class.spec]p8:
2880 // A non-type argument is non-specialized if it is the name of a
2881 // non-type parameter. All other non-type arguments are
2882 // specialized.
2883 //
2884 // Below, we check the two conditions that only apply to
2885 // specialized non-type arguments, so skip any non-specialized
2886 // arguments.
2887 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00002888 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002889 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002890 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002891 (Param->getIndex() != NTTP->getIndex() ||
2892 Param->getDepth() != NTTP->getDepth()))
2893 MirrorsPrimaryTemplate = false;
2894
Douglas Gregore94866f2009-06-12 21:21:02 +00002895 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002896 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002897
2898 // C++ [temp.class.spec]p9:
2899 // Within the argument list of a class template partial
2900 // specialization, the following restrictions apply:
2901 // -- A partially specialized non-type argument expression
2902 // shall not involve a template parameter of the partial
2903 // specialization except when the argument expression is a
2904 // simple identifier.
2905 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002906 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00002907 diag::err_dependent_non_type_arg_in_partial_spec)
2908 << ArgExpr->getSourceRange();
2909 return true;
2910 }
2911
2912 // -- The type of a template parameter corresponding to a
2913 // specialized non-type argument shall not be dependent on a
2914 // parameter of the specialization.
2915 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002916 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00002917 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2918 << Param->getType()
2919 << ArgExpr->getSourceRange();
2920 Diag(Param->getLocation(), diag::note_template_param_here);
2921 return true;
2922 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002923
2924 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002925 }
2926
2927 return false;
2928}
2929
Douglas Gregor212e81c2009-03-25 00:13:59 +00002930Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00002931Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2932 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00002933 SourceLocation KWLoc,
Douglas Gregorcc636682009-02-17 23:15:12 +00002934 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002935 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002936 SourceLocation TemplateNameLoc,
2937 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002938 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002939 SourceLocation RAngleLoc,
2940 AttributeList *Attr,
2941 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002942 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00002943
Douglas Gregorcc636682009-02-17 23:15:12 +00002944 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002945 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00002946 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002947 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002948
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002949 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002950 bool isPartialSpecialization = false;
2951
Douglas Gregor88b70942009-02-25 22:02:03 +00002952 // Check the validity of the template headers that introduce this
2953 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002954 // FIXME: We probably shouldn't complain about these headers for
2955 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00002956 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00002957 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2958 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002959 TemplateParameterLists.size(),
2960 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00002961 if (TemplateParams && TemplateParams->size() > 0) {
2962 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002963
Douglas Gregor05396e22009-08-25 17:23:04 +00002964 // C++ [temp.class.spec]p10:
2965 // The template parameter list of a specialization shall not
2966 // contain default template argument values.
2967 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2968 Decl *Param = TemplateParams->getParam(I);
2969 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2970 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002971 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002972 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00002973 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00002974 }
2975 } else if (NonTypeTemplateParmDecl *NTTP
2976 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2977 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002978 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002979 diag::err_default_arg_in_partial_spec)
2980 << DefArg->getSourceRange();
2981 NTTP->setDefaultArgument(0);
2982 DefArg->Destroy(Context);
2983 }
2984 } else {
2985 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00002986 if (TTP->hasDefaultArgument()) {
2987 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002988 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00002989 << TTP->getDefaultArgument().getSourceRange();
2990 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002991 }
2992 }
2993 }
Douglas Gregora735b202009-10-13 14:39:41 +00002994 } else if (TemplateParams) {
2995 if (TUK == TUK_Friend)
2996 Diag(KWLoc, diag::err_template_spec_friend)
2997 << CodeModificationHint::CreateRemoval(
2998 SourceRange(TemplateParams->getTemplateLoc(),
2999 TemplateParams->getRAngleLoc()))
3000 << SourceRange(LAngleLoc, RAngleLoc);
3001 else
3002 isExplicitSpecialization = true;
3003 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003004 Diag(KWLoc, diag::err_template_spec_needs_header)
3005 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003006 isExplicitSpecialization = true;
3007 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003008
Douglas Gregorcc636682009-02-17 23:15:12 +00003009 // Check that the specialization uses the same tag kind as the
3010 // original template.
3011 TagDecl::TagKind Kind;
3012 switch (TagSpec) {
3013 default: assert(0 && "Unknown tag type!");
3014 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3015 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3016 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3017 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003018 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003019 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003020 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003021 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003022 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003023 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003024 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003025 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003026 diag::note_previous_use);
3027 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3028 }
3029
Douglas Gregor40808ce2009-03-09 23:48:35 +00003030 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00003031 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor314b97f2009-11-10 19:49:08 +00003032 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003033
Douglas Gregorcc636682009-02-17 23:15:12 +00003034 // Check that the template argument list is well-formed for this
3035 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003036 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3037 TemplateArgs.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003038 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00003039 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00003040 RAngleLoc, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003041 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003042
Mike Stump1eb44332009-09-09 15:08:12 +00003043 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003044 ClassTemplate->getTemplateParameters()->size()) &&
3045 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003046
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003047 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003048 // corresponds to these arguments.
3049 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003050 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003051 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003052 if (CheckClassTemplatePartialSpecializationArgs(
3053 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003054 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003055 return true;
3056
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003057 if (MirrorsPrimaryTemplate) {
3058 // C++ [temp.class.spec]p9b3:
3059 //
Mike Stump1eb44332009-09-09 15:08:12 +00003060 // -- The argument list of the specialization shall not be identical
3061 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003062 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003063 << (TUK == TUK_Definition)
Mike Stump1eb44332009-09-09 15:08:12 +00003064 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003065 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003066 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003067 ClassTemplate->getIdentifier(),
3068 TemplateNameLoc,
3069 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003070 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003071 AS_none);
3072 }
3073
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003074 // FIXME: Diagnose friend partial specializations
3075
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003076 // FIXME: Template parameter list matters, too
Mike Stump1eb44332009-09-09 15:08:12 +00003077 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003078 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003079 Converted.flatSize(),
3080 Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003081 } else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003082 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003083 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003084 Converted.flatSize(),
3085 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003086 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003087 ClassTemplateSpecializationDecl *PrevDecl = 0;
3088
3089 if (isPartialSpecialization)
3090 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003091 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003092 InsertPos);
3093 else
3094 PrevDecl
3095 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003096
3097 ClassTemplateSpecializationDecl *Specialization = 0;
3098
Douglas Gregor88b70942009-02-25 22:02:03 +00003099 // Check whether we can declare a class template specialization in
3100 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003101 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003102 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003103 TemplateNameLoc,
3104 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003105 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003106
Douglas Gregorb88e8882009-07-30 17:40:51 +00003107 // The canonical type
3108 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003109 if (PrevDecl &&
3110 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3111 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003112 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003113 // arguments was referenced but not declared, or we're only
3114 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003115 // declaration node as our own, updating its source location to
3116 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003117 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003118 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003119 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003120 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003121 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003122 // Build the canonical type that describes the converted template
3123 // arguments of the class template partial specialization.
3124 CanonType = Context.getTemplateSpecializationType(
3125 TemplateName(ClassTemplate),
3126 Converted.getFlatArguments(),
3127 Converted.flatSize());
3128
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003129 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003130 ClassTemplatePartialSpecializationDecl *PrevPartial
3131 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00003132 ClassTemplatePartialSpecializationDecl *Partial
3133 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003134 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003135 TemplateNameLoc,
3136 TemplateParams,
3137 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003138 Converted,
John McCall833ca992009-10-29 08:12:44 +00003139 TemplateArgs.data(),
3140 TemplateArgs.size(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003141 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003142
3143 if (PrevPartial) {
3144 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3145 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3146 } else {
3147 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3148 }
3149 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003150
Douglas Gregored9c0f92009-10-29 00:04:11 +00003151 // If we are providing an explicit specialization of a member class
3152 // template specialization, make a note of that.
3153 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3154 PrevPartial->setMemberSpecialization();
3155
Douglas Gregor031a5882009-06-13 00:26:55 +00003156 // Check that all of the template parameters of the class template
3157 // partial specialization are deducible from the template
3158 // arguments. If not, this class template partial specialization
3159 // will never be used.
3160 llvm::SmallVector<bool, 8> DeducibleParams;
3161 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003162 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003163 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003164 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003165 unsigned NumNonDeducible = 0;
3166 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3167 if (!DeducibleParams[I])
3168 ++NumNonDeducible;
3169
3170 if (NumNonDeducible) {
3171 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3172 << (NumNonDeducible > 1)
3173 << SourceRange(TemplateNameLoc, RAngleLoc);
3174 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3175 if (!DeducibleParams[I]) {
3176 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3177 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003178 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003179 diag::note_partial_spec_unused_parameter)
3180 << Param->getDeclName();
3181 else
Mike Stump1eb44332009-09-09 15:08:12 +00003182 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003183 diag::note_partial_spec_unused_parameter)
3184 << std::string("<anonymous>");
3185 }
3186 }
3187 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003188 } else {
3189 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003190 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003191 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003192 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorcc636682009-02-17 23:15:12 +00003193 ClassTemplate->getDeclContext(),
3194 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003195 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003196 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003197 PrevDecl);
3198
3199 if (PrevDecl) {
3200 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3201 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3202 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003203 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003204 InsertPos);
3205 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003206
3207 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003208 }
3209
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003210 // C++ [temp.expl.spec]p6:
3211 // If a template, a member template or the member of a class template is
3212 // explicitly specialized then that specialization shall be declared
3213 // before the first use of that specialization that would cause an implicit
3214 // instantiation to take place, in every translation unit in which such a
3215 // use occurs; no diagnostic is required.
3216 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3217 SourceRange Range(TemplateNameLoc, RAngleLoc);
3218 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3219 << Context.getTypeDeclType(Specialization) << Range;
3220
3221 Diag(PrevDecl->getPointOfInstantiation(),
3222 diag::note_instantiation_required_here)
3223 << (PrevDecl->getTemplateSpecializationKind()
3224 != TSK_ImplicitInstantiation);
3225 return true;
3226 }
3227
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003228 // If this is not a friend, note that this is an explicit specialization.
3229 if (TUK != TUK_Friend)
3230 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003231
3232 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003233 if (TUK == TUK_Definition) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003234 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003235 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003236 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003237 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003238 Diag(Def->getLocation(), diag::note_previous_definition);
3239 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003240 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003241 }
3242 }
3243
Douglas Gregorfc705b82009-02-26 22:19:44 +00003244 // Build the fully-sugared type for this class template
3245 // specialization as the user wrote in the specialization
3246 // itself. This means that we'll pretty-print the type retrieved
3247 // from the specialization's declaration the way that the user
3248 // actually wrote the specialization, rather than formatting the
3249 // name based on the "canonical" representation used to store the
3250 // template arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003251 QualType WrittenTy
3252 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00003253 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00003254 TemplateArgs.size(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00003255 CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003256 if (TUK != TUK_Friend)
3257 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003258 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003259
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003260 // C++ [temp.expl.spec]p9:
3261 // A template explicit specialization is in the scope of the
3262 // namespace in which the template was defined.
3263 //
3264 // We actually implement this paragraph where we set the semantic
3265 // context (in the creation of the ClassTemplateSpecializationDecl),
3266 // but we also maintain the lexical context where the actual
3267 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003268 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003269
Douglas Gregorcc636682009-02-17 23:15:12 +00003270 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003271 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003272 Specialization->startDefinition();
3273
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003274 if (TUK == TUK_Friend) {
3275 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3276 TemplateNameLoc,
3277 WrittenTy.getTypePtr(),
3278 /*FIXME:*/KWLoc);
3279 Friend->setAccess(AS_public);
3280 CurContext->addDecl(Friend);
3281 } else {
3282 // Add the specialization into its lexical context, so that it can
3283 // be seen when iterating through the list of declarations in that
3284 // context. However, specializations are not found by name lookup.
3285 CurContext->addDecl(Specialization);
3286 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003287 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003288}
Douglas Gregord57959a2009-03-27 23:10:48 +00003289
Mike Stump1eb44332009-09-09 15:08:12 +00003290Sema::DeclPtrTy
3291Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003292 MultiTemplateParamsArg TemplateParameterLists,
3293 Declarator &D) {
3294 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3295}
3296
Mike Stump1eb44332009-09-09 15:08:12 +00003297Sema::DeclPtrTy
3298Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003299 MultiTemplateParamsArg TemplateParameterLists,
3300 Declarator &D) {
3301 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3302 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3303 "Not a function declarator!");
3304 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003305
Douglas Gregor52591bf2009-06-24 00:54:41 +00003306 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003307 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003308 }
Mike Stump1eb44332009-09-09 15:08:12 +00003309
Douglas Gregor52591bf2009-06-24 00:54:41 +00003310 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003311
3312 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003313 move(TemplateParameterLists),
3314 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003315 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003316 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003317 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003318 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003319 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3320 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00003321 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00003322}
3323
Douglas Gregor454885e2009-10-15 15:54:05 +00003324/// \brief Diagnose cases where we have an explicit template specialization
3325/// before/after an explicit template instantiation, producing diagnostics
3326/// for those cases where they are required and determining whether the
3327/// new specialization/instantiation will have any effect.
3328///
Douglas Gregor454885e2009-10-15 15:54:05 +00003329/// \param NewLoc the location of the new explicit specialization or
3330/// instantiation.
3331///
3332/// \param NewTSK the kind of the new explicit specialization or instantiation.
3333///
3334/// \param PrevDecl the previous declaration of the entity.
3335///
3336/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3337///
3338/// \param PrevPointOfInstantiation if valid, indicates where the previus
3339/// declaration was instantiated (either implicitly or explicitly).
3340///
3341/// \param SuppressNew will be set to true to indicate that the new
3342/// specialization or instantiation has no effect and should be ignored.
3343///
3344/// \returns true if there was an error that should prevent the introduction of
3345/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00003346bool
3347Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3348 TemplateSpecializationKind NewTSK,
3349 NamedDecl *PrevDecl,
3350 TemplateSpecializationKind PrevTSK,
3351 SourceLocation PrevPointOfInstantiation,
3352 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003353 SuppressNew = false;
3354
3355 switch (NewTSK) {
3356 case TSK_Undeclared:
3357 case TSK_ImplicitInstantiation:
3358 assert(false && "Don't check implicit instantiations here");
3359 return false;
3360
3361 case TSK_ExplicitSpecialization:
3362 switch (PrevTSK) {
3363 case TSK_Undeclared:
3364 case TSK_ExplicitSpecialization:
3365 // Okay, we're just specializing something that is either already
3366 // explicitly specialized or has merely been mentioned without any
3367 // instantiation.
3368 return false;
3369
3370 case TSK_ImplicitInstantiation:
3371 if (PrevPointOfInstantiation.isInvalid()) {
3372 // The declaration itself has not actually been instantiated, so it is
3373 // still okay to specialize it.
3374 return false;
3375 }
3376 // Fall through
3377
3378 case TSK_ExplicitInstantiationDeclaration:
3379 case TSK_ExplicitInstantiationDefinition:
3380 assert((PrevTSK == TSK_ImplicitInstantiation ||
3381 PrevPointOfInstantiation.isValid()) &&
3382 "Explicit instantiation without point of instantiation?");
3383
3384 // C++ [temp.expl.spec]p6:
3385 // If a template, a member template or the member of a class template
3386 // is explicitly specialized then that specialization shall be declared
3387 // before the first use of that specialization that would cause an
3388 // implicit instantiation to take place, in every translation unit in
3389 // which such a use occurs; no diagnostic is required.
Douglas Gregor0d035142009-10-27 18:42:08 +00003390 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00003391 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003392 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00003393 << (PrevTSK != TSK_ImplicitInstantiation);
3394
3395 return true;
3396 }
3397 break;
3398
3399 case TSK_ExplicitInstantiationDeclaration:
3400 switch (PrevTSK) {
3401 case TSK_ExplicitInstantiationDeclaration:
3402 // This explicit instantiation declaration is redundant (that's okay).
3403 SuppressNew = true;
3404 return false;
3405
3406 case TSK_Undeclared:
3407 case TSK_ImplicitInstantiation:
3408 // We're explicitly instantiating something that may have already been
3409 // implicitly instantiated; that's fine.
3410 return false;
3411
3412 case TSK_ExplicitSpecialization:
3413 // C++0x [temp.explicit]p4:
3414 // For a given set of template parameters, if an explicit instantiation
3415 // of a template appears after a declaration of an explicit
3416 // specialization for that template, the explicit instantiation has no
3417 // effect.
3418 return false;
3419
3420 case TSK_ExplicitInstantiationDefinition:
3421 // C++0x [temp.explicit]p10:
3422 // If an entity is the subject of both an explicit instantiation
3423 // declaration and an explicit instantiation definition in the same
3424 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00003425 Diag(NewLoc,
3426 diag::err_explicit_instantiation_declaration_after_definition);
3427 Diag(PrevPointOfInstantiation,
3428 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00003429 assert(PrevPointOfInstantiation.isValid() &&
3430 "Explicit instantiation without point of instantiation?");
3431 SuppressNew = true;
3432 return false;
3433 }
3434 break;
3435
3436 case TSK_ExplicitInstantiationDefinition:
3437 switch (PrevTSK) {
3438 case TSK_Undeclared:
3439 case TSK_ImplicitInstantiation:
3440 // We're explicitly instantiating something that may have already been
3441 // implicitly instantiated; that's fine.
3442 return false;
3443
3444 case TSK_ExplicitSpecialization:
3445 // C++ DR 259, C++0x [temp.explicit]p4:
3446 // For a given set of template parameters, if an explicit
3447 // instantiation of a template appears after a declaration of
3448 // an explicit specialization for that template, the explicit
3449 // instantiation has no effect.
3450 //
3451 // In C++98/03 mode, we only give an extension warning here, because it
3452 // is not not harmful to try to explicitly instantiate something that
3453 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00003454 if (!getLangOptions().CPlusPlus0x) {
3455 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00003456 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003457 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00003458 diag::note_previous_template_specialization);
3459 }
3460 SuppressNew = true;
3461 return false;
3462
3463 case TSK_ExplicitInstantiationDeclaration:
3464 // We're explicity instantiating a definition for something for which we
3465 // were previously asked to suppress instantiations. That's fine.
3466 return false;
3467
3468 case TSK_ExplicitInstantiationDefinition:
3469 // C++0x [temp.spec]p5:
3470 // For a given template and a given set of template-arguments,
3471 // - an explicit instantiation definition shall appear at most once
3472 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00003473 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00003474 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003475 Diag(PrevPointOfInstantiation,
3476 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00003477 SuppressNew = true;
3478 return false;
3479 }
3480 break;
3481 }
3482
3483 assert(false && "Missing specialization/instantiation case?");
3484
3485 return false;
3486}
3487
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003488/// \brief Perform semantic analysis for the given function template
3489/// specialization.
3490///
3491/// This routine performs all of the semantic analysis required for an
3492/// explicit function template specialization. On successful completion,
3493/// the function declaration \p FD will become a function template
3494/// specialization.
3495///
3496/// \param FD the function declaration, which will be updated to become a
3497/// function template specialization.
3498///
3499/// \param HasExplicitTemplateArgs whether any template arguments were
3500/// explicitly provided.
3501///
3502/// \param LAngleLoc the location of the left angle bracket ('<'), if
3503/// template arguments were explicitly provided.
3504///
3505/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3506/// if any.
3507///
3508/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3509/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3510/// true as in, e.g., \c void sort<>(char*, char*);
3511///
3512/// \param RAngleLoc the location of the right angle bracket ('>'), if
3513/// template arguments were explicitly provided.
3514///
3515/// \param PrevDecl the set of declarations that
3516bool
3517Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3518 bool HasExplicitTemplateArgs,
3519 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00003520 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003521 unsigned NumExplicitTemplateArgs,
3522 SourceLocation RAngleLoc,
3523 NamedDecl *&PrevDecl) {
3524 // The set of function template specializations that could match this
3525 // explicit function template specialization.
3526 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3527 CandidateSet Candidates;
3528
3529 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3530 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3531 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3532 // Only consider templates found within the same semantic lookup scope as
3533 // FD.
3534 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3535 continue;
3536
3537 // C++ [temp.expl.spec]p11:
3538 // A trailing template-argument can be left unspecified in the
3539 // template-id naming an explicit function template specialization
3540 // provided it can be deduced from the function argument type.
3541 // Perform template argument deduction to determine whether we may be
3542 // specializing this template.
3543 // FIXME: It is somewhat wasteful to build
3544 TemplateDeductionInfo Info(Context);
3545 FunctionDecl *Specialization = 0;
3546 if (TemplateDeductionResult TDK
3547 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3548 ExplicitTemplateArgs,
3549 NumExplicitTemplateArgs,
3550 FD->getType(),
3551 Specialization,
3552 Info)) {
3553 // FIXME: Template argument deduction failed; record why it failed, so
3554 // that we can provide nifty diagnostics.
3555 (void)TDK;
3556 continue;
3557 }
3558
3559 // Record this candidate.
3560 Candidates.push_back(Specialization);
3561 }
3562 }
3563
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003564 // Find the most specialized function template.
3565 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3566 Candidates.size(),
3567 TPOC_Other,
3568 FD->getLocation(),
3569 PartialDiagnostic(diag::err_function_template_spec_no_match)
3570 << FD->getDeclName(),
3571 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3572 << FD->getDeclName() << HasExplicitTemplateArgs,
3573 PartialDiagnostic(diag::note_function_template_spec_matched));
3574 if (!Specialization)
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003575 return true;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003576
3577 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003578 // If so, we have run afoul of .
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003579
Douglas Gregord5cb8762009-10-07 00:13:32 +00003580 // Check the scope of this explicit specialization.
3581 if (CheckTemplateSpecializationScope(*this,
3582 Specialization->getPrimaryTemplate(),
3583 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003584 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003585 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003586
3587 // C++ [temp.expl.spec]p6:
3588 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00003589 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003590 // before the first use of that specialization that would cause an implicit
3591 // instantiation to take place, in every translation unit in which such a
3592 // use occurs; no diagnostic is required.
3593 FunctionTemplateSpecializationInfo *SpecInfo
3594 = Specialization->getTemplateSpecializationInfo();
3595 assert(SpecInfo && "Function template specialization info missing?");
3596 if (SpecInfo->getPointOfInstantiation().isValid()) {
3597 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3598 << FD;
3599 Diag(SpecInfo->getPointOfInstantiation(),
3600 diag::note_instantiation_required_here)
3601 << (Specialization->getTemplateSpecializationKind()
3602 != TSK_ImplicitInstantiation);
3603 return true;
3604 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003605
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003606 // Mark the prior declaration as an explicit specialization, so that later
3607 // clients know that this is an explicit specialization.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003608 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003609
3610 // Turn the given function declaration into a function template
3611 // specialization, with the template arguments from the previous
3612 // specialization.
3613 FD->setFunctionTemplateSpecialization(Context,
3614 Specialization->getPrimaryTemplate(),
3615 new (Context) TemplateArgumentList(
3616 *Specialization->getTemplateSpecializationArgs()),
3617 /*InsertPos=*/0,
3618 TSK_ExplicitSpecialization);
3619
3620 // The "previous declaration" for this function template specialization is
3621 // the prior function template specialization.
3622 PrevDecl = Specialization;
3623 return false;
3624}
3625
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003626/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003627/// specialization.
3628///
3629/// This routine performs all of the semantic analysis required for an
3630/// explicit member function specialization. On successful completion,
3631/// the function declaration \p FD will become a member function
3632/// specialization.
3633///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003634/// \param Member the member declaration, which will be updated to become a
3635/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003636///
3637/// \param PrevDecl the set of declarations, one of which may be specialized
3638/// by this function specialization.
3639bool
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003640Sema::CheckMemberSpecialization(NamedDecl *Member, NamedDecl *&PrevDecl) {
3641 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3642
3643 // Try to find the member we are instantiating.
3644 NamedDecl *Instantiation = 0;
3645 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003646 MemberSpecializationInfo *MSInfo = 0;
3647
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003648 if (!PrevDecl) {
3649 // Nowhere to look anyway.
3650 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3651 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3652 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl)) {
3653 if (Context.hasSameType(Function->getType(), Method->getType())) {
3654 Instantiation = Method;
3655 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003656 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003657 break;
3658 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003659 }
3660 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003661 } else if (isa<VarDecl>(Member)) {
3662 if (VarDecl *PrevVar = dyn_cast<VarDecl>(PrevDecl))
3663 if (PrevVar->isStaticDataMember()) {
3664 Instantiation = PrevDecl;
3665 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003666 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003667 }
3668 } else if (isa<RecordDecl>(Member)) {
3669 if (CXXRecordDecl *PrevRecord = dyn_cast<CXXRecordDecl>(PrevDecl)) {
3670 Instantiation = PrevDecl;
3671 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003672 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003673 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003674 }
3675
3676 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003677 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003678 // specializations are always out-of-line, the caller will complain about
3679 // this mismatch later.
3680 return false;
3681 }
3682
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003683 // Make sure that this is a specialization of a member.
3684 if (!InstantiatedFrom) {
3685 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3686 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003687 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3688 return true;
3689 }
3690
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003691 // C++ [temp.expl.spec]p6:
3692 // If a template, a member template or the member of a class template is
3693 // explicitly specialized then that spe- cialization shall be declared
3694 // before the first use of that specialization that would cause an implicit
3695 // instantiation to take place, in every translation unit in which such a
3696 // use occurs; no diagnostic is required.
3697 assert(MSInfo && "Member specialization info missing?");
3698 if (MSInfo->getPointOfInstantiation().isValid()) {
3699 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3700 << Member;
3701 Diag(MSInfo->getPointOfInstantiation(),
3702 diag::note_instantiation_required_here)
3703 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3704 return true;
3705 }
3706
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003707 // Check the scope of this explicit specialization.
3708 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003709 InstantiatedFrom,
3710 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003711 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003712 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00003713
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003714 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00003715 // the original declaration to note that it is an explicit specialization
3716 // (if it was previously an implicit instantiation). This latter step
3717 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003718 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003719 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3720 if (InstantiationFunction->getTemplateSpecializationKind() ==
3721 TSK_ImplicitInstantiation) {
3722 InstantiationFunction->setTemplateSpecializationKind(
3723 TSK_ExplicitSpecialization);
3724 InstantiationFunction->setLocation(Member->getLocation());
3725 }
3726
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003727 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3728 cast<CXXMethodDecl>(InstantiatedFrom),
3729 TSK_ExplicitSpecialization);
3730 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003731 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3732 if (InstantiationVar->getTemplateSpecializationKind() ==
3733 TSK_ImplicitInstantiation) {
3734 InstantiationVar->setTemplateSpecializationKind(
3735 TSK_ExplicitSpecialization);
3736 InstantiationVar->setLocation(Member->getLocation());
3737 }
3738
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003739 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3740 cast<VarDecl>(InstantiatedFrom),
3741 TSK_ExplicitSpecialization);
3742 } else {
3743 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00003744 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3745 if (InstantiationClass->getTemplateSpecializationKind() ==
3746 TSK_ImplicitInstantiation) {
3747 InstantiationClass->setTemplateSpecializationKind(
3748 TSK_ExplicitSpecialization);
3749 InstantiationClass->setLocation(Member->getLocation());
3750 }
3751
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003752 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00003753 cast<CXXRecordDecl>(InstantiatedFrom),
3754 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003755 }
3756
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003757 // Save the caller the trouble of having to figure out which declaration
3758 // this specialization matches.
3759 PrevDecl = Instantiation;
3760 return false;
3761}
3762
Douglas Gregor558c0322009-10-14 23:41:34 +00003763/// \brief Check the scope of an explicit instantiation.
3764static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3765 SourceLocation InstLoc,
3766 bool WasQualifiedName) {
3767 DeclContext *ExpectedContext
3768 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3769 DeclContext *CurContext = S.CurContext->getLookupContext();
3770
3771 // C++0x [temp.explicit]p2:
3772 // An explicit instantiation shall appear in an enclosing namespace of its
3773 // template.
3774 //
3775 // This is DR275, which we do not retroactively apply to C++98/03.
3776 if (S.getLangOptions().CPlusPlus0x &&
3777 !CurContext->Encloses(ExpectedContext)) {
3778 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3779 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3780 << D << NS;
3781 else
3782 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3783 << D;
3784 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3785 return;
3786 }
3787
3788 // C++0x [temp.explicit]p2:
3789 // If the name declared in the explicit instantiation is an unqualified
3790 // name, the explicit instantiation shall appear in the namespace where
3791 // its template is declared or, if that namespace is inline (7.3.1), any
3792 // namespace from its enclosing namespace set.
3793 if (WasQualifiedName)
3794 return;
3795
3796 if (CurContext->Equals(ExpectedContext))
3797 return;
3798
3799 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3800 << D << ExpectedContext;
3801 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3802}
3803
3804/// \brief Determine whether the given scope specifier has a template-id in it.
3805static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3806 if (!SS.isSet())
3807 return false;
3808
3809 // C++0x [temp.explicit]p2:
3810 // If the explicit instantiation is for a member function, a member class
3811 // or a static data member of a class template specialization, the name of
3812 // the class template specialization in the qualified-id for the member
3813 // name shall be a simple-template-id.
3814 //
3815 // C++98 has the same restriction, just worded differently.
3816 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3817 NNS; NNS = NNS->getPrefix())
3818 if (Type *T = NNS->getAsType())
3819 if (isa<TemplateSpecializationType>(T))
3820 return true;
3821
3822 return false;
3823}
3824
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003825// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00003826// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003827Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00003828Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00003829 SourceLocation ExternLoc,
3830 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003831 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003832 SourceLocation KWLoc,
3833 const CXXScopeSpec &SS,
3834 TemplateTy TemplateD,
3835 SourceLocation TemplateNameLoc,
3836 SourceLocation LAngleLoc,
3837 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003838 SourceLocation RAngleLoc,
3839 AttributeList *Attr) {
3840 // Find the class template we're specializing
3841 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003842 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003843 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3844
3845 // Check that the specialization uses the same tag kind as the
3846 // original template.
3847 TagDecl::TagKind Kind;
3848 switch (TagSpec) {
3849 default: assert(0 && "Unknown tag type!");
3850 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3851 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3852 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3853 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003854 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003855 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003856 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003857 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003858 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003859 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003860 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003861 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003862 diag::note_previous_use);
3863 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3864 }
3865
Douglas Gregor558c0322009-10-14 23:41:34 +00003866 // C++0x [temp.explicit]p2:
3867 // There are two forms of explicit instantiation: an explicit instantiation
3868 // definition and an explicit instantiation declaration. An explicit
3869 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00003870 TemplateSpecializationKind TSK
3871 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3872 : TSK_ExplicitInstantiationDeclaration;
3873
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003874 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00003875 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor314b97f2009-11-10 19:49:08 +00003876 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003877
3878 // Check that the template argument list is well-formed for this
3879 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003880 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3881 TemplateArgs.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003882 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00003883 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00003884 RAngleLoc, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003885 return true;
3886
Mike Stump1eb44332009-09-09 15:08:12 +00003887 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003888 ClassTemplate->getTemplateParameters()->size()) &&
3889 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003891 // Find the class template specialization declaration that
3892 // corresponds to these arguments.
3893 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00003894 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003895 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003896 Converted.flatSize(),
3897 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003898 void *InsertPos = 0;
3899 ClassTemplateSpecializationDecl *PrevDecl
3900 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3901
Douglas Gregord5cb8762009-10-07 00:13:32 +00003902 // C++0x [temp.explicit]p2:
3903 // [...] An explicit instantiation shall appear in an enclosing
3904 // namespace of its template. [...]
3905 //
3906 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00003907 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
3908 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00003909
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003910 ClassTemplateSpecializationDecl *Specialization = 0;
3911
3912 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003913 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00003914 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003915 PrevDecl,
3916 PrevDecl->getSpecializationKind(),
3917 PrevDecl->getPointOfInstantiation(),
3918 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003919 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003920
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003921 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00003922 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003923
Douglas Gregor52604ab2009-09-11 21:19:12 +00003924 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3925 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3926 // Since the only prior class template specialization with these
3927 // arguments was referenced but not declared, reuse that
3928 // declaration node as our own, updating its source location to
3929 // reflect our new declaration.
3930 Specialization = PrevDecl;
3931 Specialization->setLocation(TemplateNameLoc);
3932 PrevDecl = 0;
3933 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003934 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00003935
3936 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003937 // Create a new class template specialization declaration node for
3938 // this explicit specialization.
3939 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003940 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003941 ClassTemplate->getDeclContext(),
3942 TemplateNameLoc,
3943 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00003944 Converted, PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003945
Douglas Gregor52604ab2009-09-11 21:19:12 +00003946 if (PrevDecl) {
3947 // Remove the previous declaration from the folding set, since we want
3948 // to introduce a new declaration.
3949 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3950 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3951 }
3952
3953 // Insert the new specialization.
3954 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003955 }
3956
3957 // Build the fully-sugared type for this explicit instantiation as
3958 // the user wrote in the explicit instantiation itself. This means
3959 // that we'll pretty-print the type retrieved from the
3960 // specialization's declaration the way that the user actually wrote
3961 // the explicit instantiation, rather than formatting the name based
3962 // on the "canonical" representation used to store the template
3963 // arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003964 QualType WrittenTy
3965 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00003966 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003967 TemplateArgs.size(),
3968 Context.getTypeDeclType(Specialization));
3969 Specialization->setTypeAsWritten(WrittenTy);
3970 TemplateArgsIn.release();
3971
3972 // Add the explicit instantiation into its lexical context. However,
3973 // since explicit instantiations are never found by name lookup, we
3974 // just put it into the declaration context directly.
3975 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003976 CurContext->addDecl(Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003977
3978 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003979 // A definition of a class template or class member template
3980 // shall be in scope at the point of the explicit instantiation of
3981 // the class template or class member template.
3982 //
3983 // This check comes when we actually try to perform the
3984 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003985 ClassTemplateSpecializationDecl *Def
3986 = cast_or_null<ClassTemplateSpecializationDecl>(
3987 Specialization->getDefinition(Context));
3988 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00003989 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor0d035142009-10-27 18:42:08 +00003990
3991 // Instantiate the members of this class template specialization.
3992 Def = cast_or_null<ClassTemplateSpecializationDecl>(
3993 Specialization->getDefinition(Context));
3994 if (Def)
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003995 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003996
3997 return DeclPtrTy::make(Specialization);
3998}
3999
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004000// Explicit instantiation of a member class of a class template.
4001Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004002Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004003 SourceLocation ExternLoc,
4004 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004005 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004006 SourceLocation KWLoc,
4007 const CXXScopeSpec &SS,
4008 IdentifierInfo *Name,
4009 SourceLocation NameLoc,
4010 AttributeList *Attr) {
4011
Douglas Gregor402abb52009-05-28 23:31:59 +00004012 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004013 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004014 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004015 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004016 MultiTemplateParamsArg(*this, 0, 0),
4017 Owned, IsDependent);
4018 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4019
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004020 if (!TagD)
4021 return true;
4022
4023 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4024 if (Tag->isEnum()) {
4025 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4026 << Context.getTypeDeclType(Tag);
4027 return true;
4028 }
4029
Douglas Gregord0c87372009-05-27 17:30:49 +00004030 if (Tag->isInvalidDecl())
4031 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004032
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004033 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4034 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4035 if (!Pattern) {
4036 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4037 << Context.getTypeDeclType(Record);
4038 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4039 return true;
4040 }
4041
Douglas Gregor558c0322009-10-14 23:41:34 +00004042 // C++0x [temp.explicit]p2:
4043 // If the explicit instantiation is for a class or member class, the
4044 // elaborated-type-specifier in the declaration shall include a
4045 // simple-template-id.
4046 //
4047 // C++98 has the same restriction, just worded differently.
4048 if (!ScopeSpecifierHasTemplateId(SS))
4049 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4050 << Record << SS.getRange();
4051
4052 // C++0x [temp.explicit]p2:
4053 // There are two forms of explicit instantiation: an explicit instantiation
4054 // definition and an explicit instantiation declaration. An explicit
4055 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004056 TemplateSpecializationKind TSK
4057 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4058 : TSK_ExplicitInstantiationDeclaration;
4059
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004060 // C++0x [temp.explicit]p2:
4061 // [...] An explicit instantiation shall appear in an enclosing
4062 // namespace of its template. [...]
4063 //
4064 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004065 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004066
4067 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004068 CXXRecordDecl *PrevDecl
4069 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4070 if (!PrevDecl && Record->getDefinition(Context))
4071 PrevDecl = Record;
4072 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004073 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4074 bool SuppressNew = false;
4075 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004076 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004077 PrevDecl,
4078 MSInfo->getTemplateSpecializationKind(),
4079 MSInfo->getPointOfInstantiation(),
4080 SuppressNew))
4081 return true;
4082 if (SuppressNew)
4083 return TagD;
4084 }
4085
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004086 CXXRecordDecl *RecordDef
4087 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4088 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004089 // C++ [temp.explicit]p3:
4090 // A definition of a member class of a class template shall be in scope
4091 // at the point of an explicit instantiation of the member class.
4092 CXXRecordDecl *Def
4093 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4094 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004095 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4096 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004097 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4098 << Pattern;
4099 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004100 } else {
4101 if (InstantiateClass(NameLoc, Record, Def,
4102 getTemplateInstantiationArgs(Record),
4103 TSK))
4104 return true;
4105
4106 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4107 if (!RecordDef)
4108 return true;
4109 }
4110 }
4111
4112 // Instantiate all of the members of the class.
4113 InstantiateClassMembers(NameLoc, RecordDef,
4114 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004115
Mike Stump390b4cc2009-05-16 07:39:55 +00004116 // FIXME: We don't have any representation for explicit instantiations of
4117 // member classes. Such a representation is not needed for compilation, but it
4118 // should be available for clients that want to see all of the declarations in
4119 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004120 return TagD;
4121}
4122
Douglas Gregord5a423b2009-09-25 18:43:00 +00004123Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4124 SourceLocation ExternLoc,
4125 SourceLocation TemplateLoc,
4126 Declarator &D) {
4127 // Explicit instantiations always require a name.
4128 DeclarationName Name = GetNameForDeclarator(D);
4129 if (!Name) {
4130 if (!D.isInvalidType())
4131 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4132 diag::err_explicit_instantiation_requires_name)
4133 << D.getDeclSpec().getSourceRange()
4134 << D.getSourceRange();
4135
4136 return true;
4137 }
4138
4139 // The scope passed in may not be a decl scope. Zip up the scope tree until
4140 // we find one that is.
4141 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4142 (S->getFlags() & Scope::TemplateParamScope) != 0)
4143 S = S->getParent();
4144
4145 // Determine the type of the declaration.
4146 QualType R = GetTypeForDeclarator(D, S, 0);
4147 if (R.isNull())
4148 return true;
4149
4150 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4151 // Cannot explicitly instantiate a typedef.
4152 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4153 << Name;
4154 return true;
4155 }
4156
Douglas Gregor663b5a02009-10-14 20:14:33 +00004157 // C++0x [temp.explicit]p1:
4158 // [...] An explicit instantiation of a function template shall not use the
4159 // inline or constexpr specifiers.
4160 // Presumably, this also applies to member functions of class templates as
4161 // well.
4162 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4163 Diag(D.getDeclSpec().getInlineSpecLoc(),
4164 diag::err_explicit_instantiation_inline)
4165 << CodeModificationHint::CreateRemoval(
4166 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
4167
4168 // FIXME: check for constexpr specifier.
4169
Douglas Gregor558c0322009-10-14 23:41:34 +00004170 // C++0x [temp.explicit]p2:
4171 // There are two forms of explicit instantiation: an explicit instantiation
4172 // definition and an explicit instantiation declaration. An explicit
4173 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004174 TemplateSpecializationKind TSK
4175 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4176 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004177
John McCallf36e02d2009-10-09 21:13:30 +00004178 LookupResult Previous;
4179 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
4180 Name, LookupOrdinaryName);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004181
4182 if (!R->isFunctionType()) {
4183 // C++ [temp.explicit]p1:
4184 // A [...] static data member of a class template can be explicitly
4185 // instantiated from the member definition associated with its class
4186 // template.
4187 if (Previous.isAmbiguous()) {
4188 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
4189 D.getSourceRange());
4190 }
4191
John McCallf36e02d2009-10-09 21:13:30 +00004192 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4193 Previous.getAsSingleDecl(Context));
Douglas Gregord5a423b2009-09-25 18:43:00 +00004194 if (!Prev || !Prev->isStaticDataMember()) {
4195 // We expect to see a data data member here.
4196 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4197 << Name;
4198 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4199 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004200 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004201 return true;
4202 }
4203
4204 if (!Prev->getInstantiatedFromStaticDataMember()) {
4205 // FIXME: Check for explicit specialization?
4206 Diag(D.getIdentifierLoc(),
4207 diag::err_explicit_instantiation_data_member_not_instantiated)
4208 << Prev;
4209 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4210 // FIXME: Can we provide a note showing where this was declared?
4211 return true;
4212 }
4213
Douglas Gregor558c0322009-10-14 23:41:34 +00004214 // C++0x [temp.explicit]p2:
4215 // If the explicit instantiation is for a member function, a member class
4216 // or a static data member of a class template specialization, the name of
4217 // the class template specialization in the qualified-id for the member
4218 // name shall be a simple-template-id.
4219 //
4220 // C++98 has the same restriction, just worded differently.
4221 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4222 Diag(D.getIdentifierLoc(),
4223 diag::err_explicit_instantiation_without_qualified_id)
4224 << Prev << D.getCXXScopeSpec().getRange();
4225
4226 // Check the scope of this explicit instantiation.
4227 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4228
Douglas Gregor454885e2009-10-15 15:54:05 +00004229 // Verify that it is okay to explicitly instantiate here.
4230 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4231 assert(MSInfo && "Missing static data member specialization info?");
4232 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004233 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00004234 MSInfo->getTemplateSpecializationKind(),
4235 MSInfo->getPointOfInstantiation(),
4236 SuppressNew))
4237 return true;
4238 if (SuppressNew)
4239 return DeclPtrTy();
4240
Douglas Gregord5a423b2009-09-25 18:43:00 +00004241 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004242 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004243 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004244 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4245 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004246
4247 // FIXME: Create an ExplicitInstantiation node?
4248 return DeclPtrTy();
4249 }
4250
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004251 // If the declarator is a template-id, translate the parser's template
4252 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00004253 bool HasExplicitTemplateArgs = false;
John McCall833ca992009-10-29 08:12:44 +00004254 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004255 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4256 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Douglas Gregordb422df2009-09-25 21:45:23 +00004257 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4258 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00004259 TemplateId->NumArgs);
4260 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregordb422df2009-09-25 21:45:23 +00004261 TemplateArgs);
4262 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00004263 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00004264 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004265
Douglas Gregord5a423b2009-09-25 18:43:00 +00004266 // C++ [temp.explicit]p1:
4267 // A [...] function [...] can be explicitly instantiated from its template.
4268 // A member function [...] of a class template can be explicitly
4269 // instantiated from the member definition associated with its class
4270 // template.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004271 llvm::SmallVector<FunctionDecl *, 8> Matches;
4272 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4273 P != PEnd; ++P) {
4274 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00004275 if (!HasExplicitTemplateArgs) {
4276 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4277 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4278 Matches.clear();
4279 Matches.push_back(Method);
4280 break;
4281 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00004282 }
4283 }
4284
4285 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4286 if (!FunTmpl)
4287 continue;
4288
4289 TemplateDeductionInfo Info(Context);
4290 FunctionDecl *Specialization = 0;
4291 if (TemplateDeductionResult TDK
Douglas Gregordb422df2009-09-25 21:45:23 +00004292 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
4293 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004294 R, Specialization, Info)) {
4295 // FIXME: Keep track of almost-matches?
4296 (void)TDK;
4297 continue;
4298 }
4299
4300 Matches.push_back(Specialization);
4301 }
4302
4303 // Find the most specialized function template specialization.
4304 FunctionDecl *Specialization
4305 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4306 D.getIdentifierLoc(),
4307 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4308 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4309 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4310
4311 if (!Specialization)
4312 return true;
4313
Douglas Gregor0a897e32009-10-15 17:21:20 +00004314 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00004315 Diag(D.getIdentifierLoc(),
4316 diag::err_explicit_instantiation_member_function_not_instantiated)
4317 << Specialization
4318 << (Specialization->getTemplateSpecializationKind() ==
4319 TSK_ExplicitSpecialization);
4320 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4321 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00004322 }
Douglas Gregor558c0322009-10-14 23:41:34 +00004323
Douglas Gregor0a897e32009-10-15 17:21:20 +00004324 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00004325 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4326 PrevDecl = Specialization;
4327
Douglas Gregor0a897e32009-10-15 17:21:20 +00004328 if (PrevDecl) {
4329 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004330 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00004331 PrevDecl,
4332 PrevDecl->getTemplateSpecializationKind(),
4333 PrevDecl->getPointOfInstantiation(),
4334 SuppressNew))
4335 return true;
4336
4337 // FIXME: We may still want to build some representation of this
4338 // explicit specialization.
4339 if (SuppressNew)
4340 return DeclPtrTy();
4341 }
4342
4343 if (TSK == TSK_ExplicitInstantiationDefinition)
4344 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4345 false, /*DefinitionRequired=*/true);
4346
4347 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4348
Douglas Gregor558c0322009-10-14 23:41:34 +00004349 // C++0x [temp.explicit]p2:
4350 // If the explicit instantiation is for a member function, a member class
4351 // or a static data member of a class template specialization, the name of
4352 // the class template specialization in the qualified-id for the member
4353 // name shall be a simple-template-id.
4354 //
4355 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004356 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004357 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00004358 D.getCXXScopeSpec().isSet() &&
4359 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4360 Diag(D.getIdentifierLoc(),
4361 diag::err_explicit_instantiation_without_qualified_id)
4362 << Specialization << D.getCXXScopeSpec().getRange();
4363
4364 CheckExplicitInstantiationScope(*this,
4365 FunTmpl? (NamedDecl *)FunTmpl
4366 : Specialization->getInstantiatedFromMemberFunction(),
4367 D.getIdentifierLoc(),
4368 D.getCXXScopeSpec().isSet());
4369
Douglas Gregord5a423b2009-09-25 18:43:00 +00004370 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4371 return DeclPtrTy();
4372}
4373
Douglas Gregord57959a2009-03-27 23:10:48 +00004374Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00004375Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4376 const CXXScopeSpec &SS, IdentifierInfo *Name,
4377 SourceLocation TagLoc, SourceLocation NameLoc) {
4378 // This has to hold, because SS is expected to be defined.
4379 assert(Name && "Expected a name in a dependent tag");
4380
4381 NestedNameSpecifier *NNS
4382 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4383 if (!NNS)
4384 return true;
4385
4386 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4387 if (T.isNull())
4388 return true;
4389
4390 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4391 QualType ElabType = Context.getElaboratedType(T, TagKind);
4392
4393 return ElabType.getAsOpaquePtr();
4394}
4395
4396Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00004397Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4398 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004399 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00004400 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4401 if (!NNS)
4402 return true;
4403
4404 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00004405 if (T.isNull())
4406 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00004407 return T.getAsOpaquePtr();
4408}
4409
Douglas Gregor17343172009-04-01 00:28:59 +00004410Sema::TypeResult
4411Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4412 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00004413 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004414 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00004415 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00004416 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00004417 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00004418 assert(TemplateId && "Expected a template specialization type");
4419
Douglas Gregor6946baf2009-09-02 13:05:45 +00004420 if (computeDeclContext(SS, false)) {
4421 // If we can compute a declaration context, then the "typename"
4422 // keyword was superfluous. Just build a QualifiedNameType to keep
4423 // track of the nested-name-specifier.
Mike Stump1eb44332009-09-09 15:08:12 +00004424
Douglas Gregor6946baf2009-09-02 13:05:45 +00004425 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4426 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4427 }
Mike Stump1eb44332009-09-09 15:08:12 +00004428
Douglas Gregor6946baf2009-09-02 13:05:45 +00004429 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00004430}
4431
Douglas Gregord57959a2009-03-27 23:10:48 +00004432/// \brief Build the type that describes a C++ typename specifier,
4433/// e.g., "typename T::type".
4434QualType
4435Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4436 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00004437 CXXRecordDecl *CurrentInstantiation = 0;
4438 if (NNS->isDependent()) {
4439 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00004440
Douglas Gregor42af25f2009-05-11 19:58:34 +00004441 // If the nested-name-specifier does not refer to the current
4442 // instantiation, then build a typename type.
4443 if (!CurrentInstantiation)
4444 return Context.getTypenameType(NNS, &II);
Mike Stump1eb44332009-09-09 15:08:12 +00004445
Douglas Gregorde18d122009-09-02 13:12:51 +00004446 // The nested-name-specifier refers to the current instantiation, so the
4447 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump1eb44332009-09-09 15:08:12 +00004448 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorde18d122009-09-02 13:12:51 +00004449 // extraneous "typename" keywords, and we retroactively apply this DR to
4450 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00004451 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004452
Douglas Gregor42af25f2009-05-11 19:58:34 +00004453 DeclContext *Ctx = 0;
4454
4455 if (CurrentInstantiation)
4456 Ctx = CurrentInstantiation;
4457 else {
4458 CXXScopeSpec SS;
4459 SS.setScopeRep(NNS);
4460 SS.setRange(Range);
4461 if (RequireCompleteDeclContext(SS))
4462 return QualType();
4463
4464 Ctx = computeDeclContext(SS);
4465 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004466 assert(Ctx && "No declaration context?");
4467
4468 DeclarationName Name(&II);
John McCallf36e02d2009-10-09 21:13:30 +00004469 LookupResult Result;
4470 LookupQualifiedName(Result, Ctx, Name, LookupOrdinaryName, false);
Douglas Gregord57959a2009-03-27 23:10:48 +00004471 unsigned DiagID = 0;
4472 Decl *Referenced = 0;
4473 switch (Result.getKind()) {
4474 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00004475 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00004476 break;
4477
4478 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00004479 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004480 // We found a type. Build a QualifiedNameType, since the
4481 // typename-specifier was just sugar. FIXME: Tell
4482 // QualifiedNameType that it has a "typename" prefix.
4483 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4484 }
4485
4486 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00004487 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00004488 break;
4489
4490 case LookupResult::FoundOverloaded:
4491 DiagID = diag::err_typename_nested_not_type;
4492 Referenced = *Result.begin();
4493 break;
4494
John McCall6e247262009-10-10 05:48:19 +00004495 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00004496 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
4497 return QualType();
4498 }
4499
4500 // If we get here, it's because name lookup did not find a
4501 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor3f093272009-10-13 21:16:44 +00004502 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00004503 if (Referenced)
4504 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4505 << Name;
4506 return QualType();
4507}
Douglas Gregor4a959d82009-08-06 16:20:37 +00004508
4509namespace {
4510 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump1eb44332009-09-09 15:08:12 +00004511 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4512 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00004513 SourceLocation Loc;
4514 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00004515
Douglas Gregor4a959d82009-08-06 16:20:37 +00004516 public:
Mike Stump1eb44332009-09-09 15:08:12 +00004517 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00004518 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004519 DeclarationName Entity)
4520 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00004521 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00004522
4523 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00004524 /// transformed.
4525 ///
4526 /// For the purposes of type reconstruction, a type has already been
4527 /// transformed if it is NULL or if it is not dependent.
4528 bool AlreadyTransformed(QualType T) {
4529 return T.isNull() || !T->isDependentType();
4530 }
Mike Stump1eb44332009-09-09 15:08:12 +00004531
4532 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00004533 /// rebuilt.
4534 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Douglas Gregor4a959d82009-08-06 16:20:37 +00004536 /// \brief Returns the name of the entity whose type is being rebuilt.
4537 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00004538
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004539 /// \brief Sets the "base" location and entity when that
4540 /// information is known based on another transformation.
4541 void setBase(SourceLocation Loc, DeclarationName Entity) {
4542 this->Loc = Loc;
4543 this->Entity = Entity;
4544 }
4545
Douglas Gregor4a959d82009-08-06 16:20:37 +00004546 /// \brief Transforms an expression by returning the expression itself
4547 /// (an identity function).
4548 ///
4549 /// FIXME: This is completely unsafe; we will need to actually clone the
4550 /// expressions.
4551 Sema::OwningExprResult TransformExpr(Expr *E) {
4552 return getSema().Owned(E);
4553 }
Mike Stump1eb44332009-09-09 15:08:12 +00004554
Douglas Gregor4a959d82009-08-06 16:20:37 +00004555 /// \brief Transforms a typename type by determining whether the type now
4556 /// refers to a member of the current instantiation, and then
4557 /// type-checking and building a QualifiedNameType (when possible).
John McCalla2becad2009-10-21 00:40:46 +00004558 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor4a959d82009-08-06 16:20:37 +00004559 };
4560}
4561
Mike Stump1eb44332009-09-09 15:08:12 +00004562QualType
John McCalla2becad2009-10-21 00:40:46 +00004563CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4564 TypenameTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00004565 TypenameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00004566
Douglas Gregor4a959d82009-08-06 16:20:37 +00004567 NestedNameSpecifier *NNS
4568 = TransformNestedNameSpecifier(T->getQualifier(),
4569 /*FIXME:*/SourceRange(getBaseLocation()));
4570 if (!NNS)
4571 return QualType();
4572
4573 // If the nested-name-specifier did not change, and we cannot compute the
4574 // context corresponding to the nested-name-specifier, then this
4575 // typename type will not change; exit early.
4576 CXXScopeSpec SS;
4577 SS.setRange(SourceRange(getBaseLocation()));
4578 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00004579
4580 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004581 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00004582 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004583
4584 // Rebuild the typename type, which will probably turn into a
Douglas Gregor4a959d82009-08-06 16:20:37 +00004585 // QualifiedNameType.
John McCall833ca992009-10-29 08:12:44 +00004586 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004587 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00004588 = TransformType(QualType(TemplateId, 0));
4589 if (NewTemplateId.isNull())
4590 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004591
Douglas Gregor4a959d82009-08-06 16:20:37 +00004592 if (NNS == T->getQualifier() &&
4593 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00004594 Result = QualType(T, 0);
4595 else
4596 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4597 } else
4598 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4599 SourceRange(TL.getNameLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +00004600
John McCall833ca992009-10-29 08:12:44 +00004601 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4602 NewTL.setNameLoc(TL.getNameLoc());
4603 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004604}
4605
4606/// \brief Rebuilds a type within the context of the current instantiation.
4607///
Mike Stump1eb44332009-09-09 15:08:12 +00004608/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00004609/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00004610/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00004611/// partial specialization thereof). This routine will rebuild that type now
4612/// that we have entered the declarator's scope, which may produce different
4613/// canonical types, e.g.,
4614///
4615/// \code
4616/// template<typename T>
4617/// struct X {
4618/// typedef T* pointer;
4619/// pointer data();
4620/// };
4621///
4622/// template<typename T>
4623/// typename X<T>::pointer X<T>::data() { ... }
4624/// \endcode
4625///
4626/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4627/// since we do not know that we can look into X<T> when we parsed the type.
4628/// This function will rebuild the type, performing the lookup of "pointer"
4629/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4630/// as the canonical type of T*, allowing the return types of the out-of-line
4631/// definition and the declaration to match.
4632QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4633 DeclarationName Name) {
4634 if (T.isNull() || !T->isDependentType())
4635 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00004636
Douglas Gregor4a959d82009-08-06 16:20:37 +00004637 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4638 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00004639}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004640
4641/// \brief Produces a formatted string that describes the binding of
4642/// template parameters to template arguments.
4643std::string
4644Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4645 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004646 // FIXME: For variadic templates, we'll need to get the structured list.
4647 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4648 Args.flat_size());
4649}
4650
4651std::string
4652Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4653 const TemplateArgument *Args,
4654 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004655 std::string Result;
4656
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004657 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004658 return Result;
4659
4660 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004661 if (I >= NumArgs)
4662 break;
4663
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004664 if (I == 0)
4665 Result += "[with ";
4666 else
4667 Result += ", ";
4668
4669 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4670 Result += Id->getName();
4671 } else {
4672 Result += '$';
4673 Result += llvm::utostr(I);
4674 }
4675
4676 Result += " = ";
4677
4678 switch (Args[I].getKind()) {
4679 case TemplateArgument::Null:
4680 Result += "<no value>";
4681 break;
4682
4683 case TemplateArgument::Type: {
4684 std::string TypeStr;
4685 Args[I].getAsType().getAsStringInternal(TypeStr,
4686 Context.PrintingPolicy);
4687 Result += TypeStr;
4688 break;
4689 }
4690
4691 case TemplateArgument::Declaration: {
4692 bool Unnamed = true;
4693 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4694 if (ND->getDeclName()) {
4695 Unnamed = false;
4696 Result += ND->getNameAsString();
4697 }
4698 }
4699
4700 if (Unnamed) {
4701 Result += "<anonymous>";
4702 }
4703 break;
4704 }
4705
Douglas Gregor788cd062009-11-11 01:00:40 +00004706 case TemplateArgument::Template: {
4707 std::string Str;
4708 llvm::raw_string_ostream OS(Str);
4709 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4710 Result += OS.str();
4711 break;
4712 }
4713
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004714 case TemplateArgument::Integral: {
4715 Result += Args[I].getAsIntegral()->toString(10);
4716 break;
4717 }
4718
4719 case TemplateArgument::Expression: {
4720 assert(false && "No expressions in deduced template arguments!");
4721 Result += "<expression>";
4722 break;
4723 }
4724
4725 case TemplateArgument::Pack:
4726 // FIXME: Format template argument packs
4727 Result += "<template argument pack>";
4728 break;
4729 }
4730 }
4731
4732 Result += ']';
4733 return Result;
4734}