blob: 8d77b1ff9b8518b6b795bf8f8dff1649a71f5aab [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"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000020#include "clang/Parse/Template.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000023#include "llvm/Support/Compiler.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregor2dd078a2009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
31 if (!D)
32 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000033
Douglas Gregor2dd078a2009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
Mike Stump1eb44332009-09-09 15:08:12 +000036
Douglas Gregor2dd078a2009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump1eb44332009-09-09 15:08:12 +000058
Douglas Gregor2dd078a2009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump1eb44332009-09-09 15:08:12 +000061
Douglas Gregor2dd078a2009-09-02 22:59:36 +000062 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
63 if (!Ovl)
64 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000065
Douglas Gregor2dd078a2009-09-02 22:59:36 +000066 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
67 FEnd = Ovl->function_end();
68 F != FEnd; ++F) {
69 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
70 // We've found a function template. Determine whether there are
71 // any other function templates we need to bundle together in an
72 // OverloadedFunctionDecl
73 for (++F; F != FEnd; ++F) {
74 if (isa<FunctionTemplateDecl>(*F))
75 break;
76 }
Mike Stump1eb44332009-09-09 15:08:12 +000077
Douglas Gregor2dd078a2009-09-02 22:59:36 +000078 if (F != FEnd) {
79 // Build an overloaded function decl containing only the
80 // function templates in Ovl.
Mike Stump1eb44332009-09-09 15:08:12 +000081 OverloadedFunctionDecl *OvlTemplate
Douglas Gregor2dd078a2009-09-02 22:59:36 +000082 = OverloadedFunctionDecl::Create(Context,
83 Ovl->getDeclContext(),
84 Ovl->getDeclName());
85 OvlTemplate->addOverload(FuncTmpl);
86 OvlTemplate->addOverload(*F);
87 for (++F; F != FEnd; ++F) {
88 if (isa<FunctionTemplateDecl>(*F))
89 OvlTemplate->addOverload(*F);
90 }
Mike Stump1eb44332009-09-09 15:08:12 +000091
Douglas Gregor2dd078a2009-09-02 22:59:36 +000092 return OvlTemplate;
93 }
94
95 return FuncTmpl;
96 }
97 }
Mike Stump1eb44332009-09-09 15:08:12 +000098
Douglas Gregor2dd078a2009-09-02 22:59:36 +000099 return 0;
100}
101
102TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000103 const CXXScopeSpec &SS,
104 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000105 TypeTy *ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000106 bool EnteringContext,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000107 TemplateTy &TemplateResult) {
Douglas Gregor014e88d2009-11-03 23:16:33 +0000108 DeclarationName TName;
109
110 switch (Name.getKind()) {
111 case UnqualifiedId::IK_Identifier:
112 TName = DeclarationName(Name.Identifier);
113 break;
114
115 case UnqualifiedId::IK_OperatorFunctionId:
116 TName = Context.DeclarationNames.getCXXOperatorName(
117 Name.OperatorFunctionId.Operator);
118 break;
119
120 default:
121 return TNK_Non_template;
122 }
123
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000124 // Determine where to perform name lookup
125 DeclContext *LookupCtx = 0;
126 bool isDependent = false;
127 if (ObjectTypePtr) {
128 // This nested-name-specifier occurs in a member access expression, e.g.,
129 // x->B::f, and we are looking into the type of the object.
Douglas Gregor014e88d2009-11-03 23:16:33 +0000130 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000131 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
132 LookupCtx = computeDeclContext(ObjectType);
133 isDependent = ObjectType->isDependentType();
Douglas Gregor03c57052009-11-17 05:17:33 +0000134 assert((isDependent || !ObjectType->isIncompleteType()) &&
135 "Caller should have completed object type");
Douglas Gregor014e88d2009-11-03 23:16:33 +0000136 } else if (SS.isSet()) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000137 // This nested-name-specifier occurs after another nested-name-specifier,
138 // so long into the context associated with the prior nested-name-specifier.
Douglas Gregor014e88d2009-11-03 23:16:33 +0000139 LookupCtx = computeDeclContext(SS, EnteringContext);
140 isDependent = isDependentScopeSpecifier(SS);
Douglas Gregor03c57052009-11-17 05:17:33 +0000141
142 // The declaration context must be complete.
143 if (LookupCtx && RequireCompleteDeclContext(SS))
144 return TNK_Non_template;
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000145 }
Mike Stump1eb44332009-09-09 15:08:12 +0000146
John McCalla24dc2e2009-11-17 02:14:36 +0000147 LookupResult Found(*this, TName, SourceLocation(), LookupOrdinaryName);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000148 bool ObjectTypeSearchedInScope = false;
149 if (LookupCtx) {
150 // Perform "qualified" name lookup into the declaration context we
151 // computed, which is either the type of the base of a member access
Mike Stump1eb44332009-09-09 15:08:12 +0000152 // expression or the declaration context associated with a prior
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000153 // nested-name-specifier.
John McCalla24dc2e2009-11-17 02:14:36 +0000154 LookupQualifiedName(Found, LookupCtx);
Mike Stump1eb44332009-09-09 15:08:12 +0000155
John McCalla24dc2e2009-11-17 02:14:36 +0000156 if (ObjectTypePtr && Found.empty()) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000157 // C++ [basic.lookup.classref]p1:
158 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump1eb44332009-09-09 15:08:12 +0000159 // immediately followed by an identifier followed by a <, the
160 // identifier must be looked up to determine whether the < is the
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000161 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump1eb44332009-09-09 15:08:12 +0000162 // The identifier is first looked up in the class of the object
163 // expression. If the identifier is not found, it is then looked up in
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000164 // the context of the entire postfix-expression and shall name a class
165 // or function template.
166 //
167 // FIXME: When we're instantiating a template, do we actually have to
168 // look in the scope of the template? Seems fishy...
John McCalla24dc2e2009-11-17 02:14:36 +0000169 LookupName(Found, S);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000170 ObjectTypeSearchedInScope = true;
171 }
172 } else if (isDependent) {
Mike Stump1eb44332009-09-09 15:08:12 +0000173 // We cannot look into a dependent object type or
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000174 return TNK_Non_template;
175 } else {
176 // Perform unqualified name lookup in the current scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000177 LookupName(Found, S);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000178 }
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Douglas Gregor495c35d2009-08-25 22:51:20 +0000180 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump1eb44332009-09-09 15:08:12 +0000181 assert(!Found.isAmbiguous() &&
Douglas Gregor495c35d2009-08-25 22:51:20 +0000182 "Cannot handle template name-lookup ambiguities");
Douglas Gregor7532dc62009-03-30 22:58:21 +0000183
John McCallf36e02d2009-10-09 21:13:30 +0000184 NamedDecl *Template
185 = isAcceptableTemplateName(Context, Found.getAsSingleDecl(Context));
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000186 if (!Template)
187 return TNK_Non_template;
188
189 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
190 // C++ [basic.lookup.classref]p1:
Mike Stump1eb44332009-09-09 15:08:12 +0000191 // [...] If the lookup in the class of the object expression finds a
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000192 // template, the name is also looked up in the context of the entire
193 // postfix-expression and [...]
194 //
John McCalla24dc2e2009-11-17 02:14:36 +0000195 LookupResult FoundOuter(*this, TName, SourceLocation(), LookupOrdinaryName);
196 LookupName(FoundOuter, S);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000197 // FIXME: Handle ambiguities in this lookup better
John McCallf36e02d2009-10-09 21:13:30 +0000198 NamedDecl *OuterTemplate
199 = isAcceptableTemplateName(Context, FoundOuter.getAsSingleDecl(Context));
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000201 if (!OuterTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +0000202 // - if the name is not found, the name found in the class of the
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000203 // object expression is used, otherwise
204 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000205 // - if the name is found in the context of the entire
206 // postfix-expression and does not name a class template, the name
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000207 // found in the class of the object expression is used, otherwise
208 } else {
209 // - if the name found is a class template, it must refer to the same
Mike Stump1eb44332009-09-09 15:08:12 +0000210 // entity as the one found in the class of the object expression,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000211 // otherwise the program is ill-formed.
212 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
Douglas Gregor014e88d2009-11-03 23:16:33 +0000213 Diag(Name.getSourceRange().getBegin(),
214 diag::err_nested_name_member_ref_lookup_ambiguous)
215 << TName
216 << Name.getSourceRange();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000217 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
218 << QualType::getFromOpaquePtr(ObjectTypePtr);
219 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump1eb44332009-09-09 15:08:12 +0000220
221 // Recover by taking the template that we found in the object
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000222 // expression's type.
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000223 }
Mike Stump1eb44332009-09-09 15:08:12 +0000224 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000225 }
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Douglas Gregor014e88d2009-11-03 23:16:33 +0000227 if (SS.isSet() && !SS.isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000228 NestedNameSpecifier *Qualifier
Douglas Gregor014e88d2009-11-03 23:16:33 +0000229 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +0000230 if (OverloadedFunctionDecl *Ovl
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000231 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump1eb44332009-09-09 15:08:12 +0000232 TemplateResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000233 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
234 Ovl));
235 else
Mike Stump1eb44332009-09-09 15:08:12 +0000236 TemplateResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000237 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump1eb44332009-09-09 15:08:12 +0000238 cast<TemplateDecl>(Template)));
239 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000240 = dyn_cast<OverloadedFunctionDecl>(Template)) {
241 TemplateResult = TemplateTy::make(TemplateName(Ovl));
242 } else {
243 TemplateResult = TemplateTy::make(
244 TemplateName(cast<TemplateDecl>(Template)));
245 }
Mike Stump1eb44332009-09-09 15:08:12 +0000246
247 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000248 isa<TemplateTemplateParmDecl>(Template))
249 return TNK_Type_template;
Mike Stump1eb44332009-09-09 15:08:12 +0000250
251 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000252 isa<OverloadedFunctionDecl>(Template)) &&
253 "Unhandled template kind in Sema::isTemplateName");
254 return TNK_Function_template;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000255}
256
Douglas Gregor72c3f312008-12-05 18:15:24 +0000257/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
258/// that the template parameter 'PrevDecl' is being shadowed by a new
259/// declaration at location Loc. Returns true to indicate that this is
260/// an error, and false otherwise.
261bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000262 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000263
264 // Microsoft Visual C++ permits template parameters to be shadowed.
265 if (getLangOptions().Microsoft)
266 return false;
267
268 // C++ [temp.local]p4:
269 // A template-parameter shall not be redeclared within its
270 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000271 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000272 << cast<NamedDecl>(PrevDecl)->getDeclName();
273 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
274 return true;
275}
276
Douglas Gregor2943aed2009-03-03 04:44:36 +0000277/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000278/// the parameter D to reference the templated declaration and return a pointer
279/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000280TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000281 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000282 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000283 return Temp;
284 }
285 return 0;
286}
287
Douglas Gregor788cd062009-11-11 01:00:40 +0000288static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
289 const ParsedTemplateArgument &Arg) {
290
291 switch (Arg.getKind()) {
292 case ParsedTemplateArgument::Type: {
293 DeclaratorInfo *DI;
294 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
295 if (!DI)
296 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation());
297 return TemplateArgumentLoc(TemplateArgument(T), DI);
298 }
299
300 case ParsedTemplateArgument::NonType: {
301 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
302 return TemplateArgumentLoc(TemplateArgument(E), E);
303 }
304
305 case ParsedTemplateArgument::Template: {
306 TemplateName Template
307 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
308 return TemplateArgumentLoc(TemplateArgument(Template),
309 Arg.getScopeSpec().getRange(),
310 Arg.getLocation());
311 }
312 }
313
314 llvm::llvm_unreachable("Unhandled parsed template argument");
315 return TemplateArgumentLoc();
316}
317
318/// \brief Translates template arguments as provided by the parser
319/// into template arguments used by semantic analysis.
320void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
321 llvm::SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs) {
322 TemplateArgs.reserve(TemplateArgsIn.size());
323
324 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
325 TemplateArgs.push_back(translateTemplateArgument(*this, TemplateArgsIn[I]));
326}
327
Douglas Gregor72c3f312008-12-05 18:15:24 +0000328/// ActOnTypeParameter - Called when a C++ template type parameter
329/// (e.g., "typename T") has been parsed. Typename specifies whether
330/// the keyword "typename" was used to declare the type parameter
331/// (otherwise, "class" was used), and KeyLoc is the location of the
332/// "class" or "typename" keyword. ParamName is the name of the
333/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump1eb44332009-09-09 15:08:12 +0000334/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000335/// If the type parameter has a default argument, it will be added
336/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000337Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000338 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000339 SourceLocation KeyLoc,
340 IdentifierInfo *ParamName,
341 SourceLocation ParamNameLoc,
342 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000343 assert(S->isTemplateParamScope() &&
344 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000345 bool Invalid = false;
346
347 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000348 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000349 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000350 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000351 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000352 }
353
Douglas Gregorddc29e12009-02-06 22:42:48 +0000354 SourceLocation Loc = ParamNameLoc;
355 if (!ParamName)
356 Loc = KeyLoc;
357
Douglas Gregor72c3f312008-12-05 18:15:24 +0000358 TemplateTypeParmDecl *Param
Mike Stump1eb44332009-09-09 15:08:12 +0000359 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
360 Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000361 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000362 if (Invalid)
363 Param->setInvalidDecl();
364
365 if (ParamName) {
366 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000367 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000368 IdResolver.AddDecl(Param);
369 }
370
Chris Lattnerb28317a2009-03-28 19:18:32 +0000371 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000372}
373
Douglas Gregord684b002009-02-10 19:49:53 +0000374/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000375/// Default) to the given template type parameter (TypeParam).
376void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000377 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000378 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000379 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000380 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000381 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000382
383 DeclaratorInfo *DefaultDInfo;
384 GetTypeFromParser(DefaultT, &DefaultDInfo);
385
386 assert(DefaultDInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000387
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000388 // C++0x [temp.param]p9:
389 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000390 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000391 if (Parm->isParameterPack()) {
392 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000393 return;
394 }
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Douglas Gregord684b002009-02-10 19:49:53 +0000396 // C++ [temp.param]p14:
397 // A template-parameter shall not be used in its own default argument.
398 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Douglas Gregord684b002009-02-10 19:49:53 +0000400 // Check the template argument itself.
John McCall833ca992009-10-29 08:12:44 +0000401 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000402 Parm->setInvalidDecl();
403 return;
404 }
405
John McCall833ca992009-10-29 08:12:44 +0000406 Parm->setDefaultArgument(DefaultDInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000407}
408
Douglas Gregor2943aed2009-03-03 04:44:36 +0000409/// \brief Check that the type of a non-type template parameter is
410/// well-formed.
411///
412/// \returns the (possibly-promoted) parameter type if valid;
413/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000414QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000415Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
416 // C++ [temp.param]p4:
417 //
418 // A non-type template-parameter shall have one of the following
419 // (optionally cv-qualified) types:
420 //
421 // -- integral or enumeration type,
422 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000423 // -- pointer to object or pointer to function,
424 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000425 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
426 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000427 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000428 T->isReferenceType() ||
429 // -- pointer to member.
430 T->isMemberPointerType() ||
431 // If T is a dependent type, we can't do the check now, so we
432 // assume that it is well-formed.
433 T->isDependentType())
434 return T;
435 // C++ [temp.param]p8:
436 //
437 // A non-type template-parameter of type "array of T" or
438 // "function returning T" is adjusted to be of type "pointer to
439 // T" or "pointer to function returning T", respectively.
440 else if (T->isArrayType())
441 // FIXME: Keep the type prior to promotion?
442 return Context.getArrayDecayedType(T);
443 else if (T->isFunctionType())
444 // FIXME: Keep the type prior to promotion?
445 return Context.getPointerType(T);
446
447 Diag(Loc, diag::err_template_nontype_parm_bad_type)
448 << T;
449
450 return QualType();
451}
452
Douglas Gregor72c3f312008-12-05 18:15:24 +0000453/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
454/// template parameter (e.g., "int Size" in "template<int Size>
455/// class Array") has been parsed. S is the current scope and D is
456/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000457Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000458 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000459 unsigned Position) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000460 DeclaratorInfo *DInfo = 0;
461 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000462
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000463 assert(S->isTemplateParamScope() &&
464 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000465 bool Invalid = false;
466
467 IdentifierInfo *ParamName = D.getIdentifier();
468 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000469 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000470 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000471 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000472 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000473 }
474
Douglas Gregor2943aed2009-03-03 04:44:36 +0000475 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000476 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000477 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000478 Invalid = true;
479 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000480
Douglas Gregor72c3f312008-12-05 18:15:24 +0000481 NonTypeTemplateParmDecl *Param
482 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000483 Depth, Position, ParamName, T, DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000484 if (Invalid)
485 Param->setInvalidDecl();
486
487 if (D.getIdentifier()) {
488 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000489 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000490 IdResolver.AddDecl(Param);
491 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000492 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000493}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000494
Douglas Gregord684b002009-02-10 19:49:53 +0000495/// \brief Adds a default argument to the given non-type template
496/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000497void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000498 SourceLocation EqualLoc,
499 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000500 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000501 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000502 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Douglas Gregord684b002009-02-10 19:49:53 +0000504 // C++ [temp.param]p14:
505 // A template-parameter shall not be used in its own default argument.
506 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Douglas Gregord684b002009-02-10 19:49:53 +0000508 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000509 TemplateArgument Converted;
510 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
511 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000512 TemplateParm->setInvalidDecl();
513 return;
514 }
515
Anders Carlssone9146f22009-05-01 19:49:17 +0000516 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000517}
518
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000519
520/// ActOnTemplateTemplateParameter - Called when a C++ template template
521/// parameter (e.g. T in template <template <typename> class T> class array)
522/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000523Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
524 SourceLocation TmpLoc,
525 TemplateParamsTy *Params,
526 IdentifierInfo *Name,
527 SourceLocation NameLoc,
528 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000529 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000530 assert(S->isTemplateParamScope() &&
531 "Template template parameter not in template parameter scope!");
532
533 // Construct the parameter object.
534 TemplateTemplateParmDecl *Param =
535 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
536 Position, Name,
537 (TemplateParameterList*)Params);
538
539 // Make sure the parameter is valid.
540 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
541 // do anything yet. However, if the template parameter list or (eventual)
542 // default value is ever invalidated, that will propagate here.
543 bool Invalid = false;
544 if (Invalid) {
545 Param->setInvalidDecl();
546 }
547
548 // If the tt-param has a name, then link the identifier into the scope
549 // and lookup mechanisms.
550 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000551 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000552 IdResolver.AddDecl(Param);
553 }
554
Chris Lattnerb28317a2009-03-28 19:18:32 +0000555 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000556}
557
Douglas Gregord684b002009-02-10 19:49:53 +0000558/// \brief Adds a default argument to the given template template
559/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000560void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000561 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000562 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000563 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000564 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000565
Douglas Gregord684b002009-02-10 19:49:53 +0000566 // C++ [temp.param]p14:
567 // A template-parameter shall not be used in its own default argument.
568 // FIXME: Implement this check! Needs a recursive walk over the types.
569
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000570 // Check only that we have a template template argument. We don't want to
571 // try to check well-formedness now, because our template template parameter
572 // might have dependent types in its template parameters, which we wouldn't
573 // be able to match now.
574 //
575 // If none of the template template parameter's template arguments mention
576 // other template parameters, we could actually perform more checking here.
577 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000578 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000579 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
580 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
581 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000582 return;
583 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000584
Douglas Gregor788cd062009-11-11 01:00:40 +0000585 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregord684b002009-02-10 19:49:53 +0000586}
587
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000588/// ActOnTemplateParameterList - Builds a TemplateParameterList that
589/// contains the template parameters in Params/NumParams.
590Sema::TemplateParamsTy *
591Sema::ActOnTemplateParameterList(unsigned Depth,
592 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000593 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000594 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000595 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000596 SourceLocation RAngleLoc) {
597 if (ExportLoc.isValid())
598 Diag(ExportLoc, diag::note_template_export_unsupported);
599
Douglas Gregorddc29e12009-02-06 22:42:48 +0000600 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000601 (NamedDecl**)Params, NumParams,
602 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000603}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000604
Douglas Gregor212e81c2009-03-25 00:13:59 +0000605Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000606Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000607 SourceLocation KWLoc, const CXXScopeSpec &SS,
608 IdentifierInfo *Name, SourceLocation NameLoc,
609 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000610 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000611 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000612 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000613 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000614 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000615 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000616
617 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000618 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000619 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000620
John McCall05b23ea2009-09-14 21:59:20 +0000621 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
622 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000623
624 // There is no such thing as an unnamed class template.
625 if (!Name) {
626 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000627 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000628 }
629
630 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000631 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000632 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000633 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000634 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregorf0510d42009-10-12 23:11:44 +0000635 if (RequireCompleteDeclContext(SS))
636 return true;
637
Douglas Gregor05396e22009-08-25 17:23:04 +0000638 SemanticContext = computeDeclContext(SS, true);
639 if (!SemanticContext) {
640 // FIXME: Produce a reasonable diagnostic here
641 return true;
642 }
Mike Stump1eb44332009-09-09 15:08:12 +0000643
John McCalla24dc2e2009-11-17 02:14:36 +0000644 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000645 } else {
646 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000647 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000648 }
Mike Stump1eb44332009-09-09 15:08:12 +0000649
Douglas Gregorddc29e12009-02-06 22:42:48 +0000650 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
651 NamedDecl *PrevDecl = 0;
652 if (Previous.begin() != Previous.end())
653 PrevDecl = *Previous.begin();
654
Douglas Gregor6102d982009-09-26 07:05:09 +0000655 if (PrevDecl && TUK == TUK_Friend) {
656 // C++ [namespace.memdef]p3:
657 // [...] When looking for a prior declaration of a class or a function
658 // declared as a friend, and when the name of the friend class or
659 // function is neither a qualified name nor a template-id, scopes outside
660 // the innermost enclosing namespace scope are not considered.
661 DeclContext *OutermostContext = CurContext;
662 while (!OutermostContext->isFileContext())
663 OutermostContext = OutermostContext->getLookupParent();
664
665 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
666 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
667 SemanticContext = PrevDecl->getDeclContext();
668 } else {
669 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregor259571e2009-10-30 22:42:42 +0000670 // context we computed is the semantic context for our new
Douglas Gregor6102d982009-09-26 07:05:09 +0000671 // declaration.
672 PrevDecl = 0;
673 SemanticContext = OutermostContext;
674 }
Douglas Gregor259571e2009-10-30 22:42:42 +0000675
676 if (CurContext->isDependentContext()) {
677 // If this is a dependent context, we don't want to link the friend
678 // class template to the template in scope, because that would perform
679 // checking of the template parameter lists that can't be performed
680 // until the outer context is instantiated.
681 PrevDecl = 0;
682 }
Douglas Gregor6102d982009-09-26 07:05:09 +0000683 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000684 PrevDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Douglas Gregorddc29e12009-02-06 22:42:48 +0000686 // If there is a previous declaration with the same name, check
687 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000688 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000689 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000690
691 // We may have found the injected-class-name of a class template,
692 // class template partial specialization, or class template specialization.
693 // In these cases, grab the template that is being defined or specialized.
694 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
695 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
696 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
697 PrevClassTemplate
698 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
699 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
700 PrevClassTemplate
701 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
702 ->getSpecializedTemplate();
703 }
704 }
705
Douglas Gregorddc29e12009-02-06 22:42:48 +0000706 if (PrevClassTemplate) {
707 // Ensure that the template parameter lists are compatible.
708 if (!TemplateParameterListsAreEqual(TemplateParams,
709 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000710 /*Complain=*/true,
711 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000712 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000713
714 // C++ [temp.class]p4:
715 // In a redeclaration, partial specialization, explicit
716 // specialization or explicit instantiation of a class template,
717 // the class-key shall agree in kind with the original class
718 // template declaration (7.1.5.3).
719 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000720 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000721 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000722 << Name
Mike Stump1eb44332009-09-09 15:08:12 +0000723 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +0000724 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000725 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000726 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000727 }
728
Douglas Gregorddc29e12009-02-06 22:42:48 +0000729 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000730 if (TUK == TUK_Definition) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000731 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
732 Diag(NameLoc, diag::err_redefinition) << Name;
733 Diag(Def->getLocation(), diag::note_previous_definition);
734 // FIXME: Would it make sense to try to "forget" the previous
735 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000736 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000737 }
738 }
739 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
740 // Maybe we will complain about the shadowed template parameter.
741 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
742 // Just pretend that we didn't see the previous declaration.
743 PrevDecl = 0;
744 } else if (PrevDecl) {
745 // C++ [temp]p5:
746 // A class template shall not have the same name as any other
747 // template, class, function, object, enumeration, enumerator,
748 // namespace, or type in the same scope (3.3), except as specified
749 // in (14.5.4).
750 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
751 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000752 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000753 }
754
Douglas Gregord684b002009-02-10 19:49:53 +0000755 // Check the template parameter list of this declaration, possibly
756 // merging in the template parameter list from the previous class
757 // template declaration.
758 if (CheckTemplateParameterList(TemplateParams,
759 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
760 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Douglas Gregor7da97d02009-05-10 22:57:19 +0000762 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000763 // declaration!
764
Mike Stump1eb44332009-09-09 15:08:12 +0000765 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000766 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000767 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000768 PrevClassTemplate->getTemplatedDecl() : 0,
769 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000770
771 ClassTemplateDecl *NewTemplate
772 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
773 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000774 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000775 NewClass->setDescribedClassTemplate(NewTemplate);
776
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000777 // Build the type for the class template declaration now.
Mike Stump1eb44332009-09-09 15:08:12 +0000778 QualType T =
779 Context.getTypeDeclType(NewClass,
780 PrevClassTemplate?
781 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000782 assert(T->isDependentType() && "Class template type is not dependent?");
783 (void)T;
784
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000785 // If we are providing an explicit specialization of a member that is a
786 // class template, make a note of that.
787 if (PrevClassTemplate &&
788 PrevClassTemplate->getInstantiatedFromMemberTemplate())
789 PrevClassTemplate->setMemberSpecialization();
790
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000791 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000792 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000793 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Douglas Gregorddc29e12009-02-06 22:42:48 +0000795 // Set the lexical context of these templates
796 NewClass->setLexicalDeclContext(CurContext);
797 NewTemplate->setLexicalDeclContext(CurContext);
798
John McCall0f434ec2009-07-31 02:45:11 +0000799 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000800 NewClass->startDefinition();
801
802 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000803 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000804
John McCall05b23ea2009-09-14 21:59:20 +0000805 if (TUK != TUK_Friend)
806 PushOnScopeChains(NewTemplate, S);
807 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000808 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000809 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000810 NewClass->setAccess(PrevClassTemplate->getAccess());
811 }
John McCall05b23ea2009-09-14 21:59:20 +0000812
Douglas Gregord85bea22009-09-26 06:47:28 +0000813 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
814 PrevClassTemplate != NULL);
815
John McCall05b23ea2009-09-14 21:59:20 +0000816 // Friend templates are visible in fairly strange ways.
817 if (!CurContext->isDependentContext()) {
818 DeclContext *DC = SemanticContext->getLookupContext();
819 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
820 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
821 PushOnScopeChains(NewTemplate, EnclosingScope,
822 /* AddToContext = */ false);
823 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000824
825 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
826 NewClass->getLocation(),
827 NewTemplate,
828 /*FIXME:*/NewClass->getLocation());
829 Friend->setAccess(AS_public);
830 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000831 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000832
Douglas Gregord684b002009-02-10 19:49:53 +0000833 if (Invalid) {
834 NewTemplate->setInvalidDecl();
835 NewClass->setInvalidDecl();
836 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000837 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000838}
839
Douglas Gregord684b002009-02-10 19:49:53 +0000840/// \brief Checks the validity of a template parameter list, possibly
841/// considering the template parameter list from a previous
842/// declaration.
843///
844/// If an "old" template parameter list is provided, it must be
845/// equivalent (per TemplateParameterListsAreEqual) to the "new"
846/// template parameter list.
847///
848/// \param NewParams Template parameter list for a new template
849/// declaration. This template parameter list will be updated with any
850/// default arguments that are carried through from the previous
851/// template parameter list.
852///
853/// \param OldParams If provided, template parameter list from a
854/// previous declaration of the same template. Default template
855/// arguments will be merged from the old template parameter list to
856/// the new template parameter list.
857///
858/// \returns true if an error occurred, false otherwise.
859bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
860 TemplateParameterList *OldParams) {
861 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Douglas Gregord684b002009-02-10 19:49:53 +0000863 // C++ [temp.param]p10:
864 // The set of default template-arguments available for use with a
865 // template declaration or definition is obtained by merging the
866 // default arguments from the definition (if in scope) and all
867 // declarations in scope in the same way default function
868 // arguments are (8.3.6).
869 bool SawDefaultArgument = false;
870 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000871
Anders Carlsson49d25572009-06-12 23:20:15 +0000872 bool SawParameterPack = false;
873 SourceLocation ParameterPackLoc;
874
Mike Stump1a35fde2009-02-11 23:03:27 +0000875 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000876 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000877 if (OldParams)
878 OldParam = OldParams->begin();
879
880 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
881 NewParamEnd = NewParams->end();
882 NewParam != NewParamEnd; ++NewParam) {
883 // Variables used to diagnose redundant default arguments
884 bool RedundantDefaultArg = false;
885 SourceLocation OldDefaultLoc;
886 SourceLocation NewDefaultLoc;
887
888 // Variables used to diagnose missing default arguments
889 bool MissingDefaultArg = false;
890
Anders Carlsson49d25572009-06-12 23:20:15 +0000891 // C++0x [temp.param]p11:
892 // If a template parameter of a class template is a template parameter pack,
893 // it must be the last template parameter.
894 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +0000895 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +0000896 diag::err_template_param_pack_must_be_last_template_parameter);
897 Invalid = true;
898 }
899
Douglas Gregord684b002009-02-10 19:49:53 +0000900 // Merge default arguments for template type parameters.
901 if (TemplateTypeParmDecl *NewTypeParm
902 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000903 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +0000904 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Anders Carlsson49d25572009-06-12 23:20:15 +0000906 if (NewTypeParm->isParameterPack()) {
907 assert(!NewTypeParm->hasDefaultArgument() &&
908 "Parameter packs can't have a default argument!");
909 SawParameterPack = true;
910 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000911 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +0000912 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +0000913 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
914 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
915 SawDefaultArgument = true;
916 RedundantDefaultArg = true;
917 PreviousDefaultArgLoc = NewDefaultLoc;
918 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
919 // Merge the default argument from the old declaration to the
920 // new declaration.
921 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +0000922 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +0000923 true);
924 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
925 } else if (NewTypeParm->hasDefaultArgument()) {
926 SawDefaultArgument = true;
927 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
928 } else if (SawDefaultArgument)
929 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000930 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +0000931 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000932 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000933 NonTypeTemplateParmDecl *OldNonTypeParm
934 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000935 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000936 NewNonTypeParm->hasDefaultArgument()) {
937 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
938 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
939 SawDefaultArgument = true;
940 RedundantDefaultArg = true;
941 PreviousDefaultArgLoc = NewDefaultLoc;
942 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
943 // Merge the default argument from the old declaration to the
944 // new declaration.
945 SawDefaultArgument = true;
946 // FIXME: We need to create a new kind of "default argument"
947 // expression that points to a previous template template
948 // parameter.
949 NewNonTypeParm->setDefaultArgument(
950 OldNonTypeParm->getDefaultArgument());
951 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
952 } else if (NewNonTypeParm->hasDefaultArgument()) {
953 SawDefaultArgument = true;
954 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
955 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000956 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000957 } else {
Douglas Gregord684b002009-02-10 19:49:53 +0000958 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000959 TemplateTemplateParmDecl *NewTemplateParm
960 = cast<TemplateTemplateParmDecl>(*NewParam);
961 TemplateTemplateParmDecl *OldTemplateParm
962 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000963 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000964 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000965 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
966 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +0000967 SawDefaultArgument = true;
968 RedundantDefaultArg = true;
969 PreviousDefaultArgLoc = NewDefaultLoc;
970 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
971 // Merge the default argument from the old declaration to the
972 // new declaration.
973 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000974 // FIXME: We need to create a new kind of "default argument" expression
975 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000976 NewTemplateParm->setDefaultArgument(
977 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +0000978 PreviousDefaultArgLoc
979 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +0000980 } else if (NewTemplateParm->hasDefaultArgument()) {
981 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +0000982 PreviousDefaultArgLoc
983 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +0000984 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000985 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +0000986 }
987
988 if (RedundantDefaultArg) {
989 // C++ [temp.param]p12:
990 // A template-parameter shall not be given default arguments
991 // by two different declarations in the same scope.
992 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
993 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
994 Invalid = true;
995 } else if (MissingDefaultArg) {
996 // C++ [temp.param]p11:
997 // If a template-parameter has a default template-argument,
998 // all subsequent template-parameters shall have a default
999 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001000 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001001 diag::err_template_param_default_arg_missing);
1002 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1003 Invalid = true;
1004 }
1005
1006 // If we have an old template parameter list that we're merging
1007 // in, move on to the next parameter.
1008 if (OldParams)
1009 ++OldParam;
1010 }
1011
1012 return Invalid;
1013}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001014
Mike Stump1eb44332009-09-09 15:08:12 +00001015/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001016/// specifier, returning the template parameter list that applies to the
1017/// name.
1018///
1019/// \param DeclStartLoc the start of the declaration that has a scope
1020/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001021///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001022/// \param SS the scope specifier that will be matched to the given template
1023/// parameter lists. This scope specifier precedes a qualified name that is
1024/// being declared.
1025///
1026/// \param ParamLists the template parameter lists, from the outermost to the
1027/// innermost template parameter lists.
1028///
1029/// \param NumParamLists the number of template parameter lists in ParamLists.
1030///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001031/// \param IsExplicitSpecialization will be set true if the entity being
1032/// declared is an explicit specialization, false otherwise.
1033///
Mike Stump1eb44332009-09-09 15:08:12 +00001034/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001035/// name that is preceded by the scope specifier @p SS. This template
1036/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001037/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001038/// template specialization), or may be NULL (if we were's declaring isn't
1039/// itself a template).
1040TemplateParameterList *
1041Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1042 const CXXScopeSpec &SS,
1043 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001044 unsigned NumParamLists,
1045 bool &IsExplicitSpecialization) {
1046 IsExplicitSpecialization = false;
1047
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001048 // Find the template-ids that occur within the nested-name-specifier. These
1049 // template-ids will match up with the template parameter lists.
1050 llvm::SmallVector<const TemplateSpecializationType *, 4>
1051 TemplateIdsInSpecifier;
1052 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1053 NNS; NNS = NNS->getPrefix()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001054 if (const TemplateSpecializationType *SpecType
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001055 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1056 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1057 if (!Template)
1058 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Ted Kremenek6217b802009-07-29 21:53:49 +00001060 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001061 ClassTemplateSpecializationDecl *SpecDecl
1062 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1063 // If the nested name specifier refers to an explicit specialization,
1064 // we don't need a template<> header.
Douglas Gregor861d0e82009-09-16 00:01:48 +00001065 // FIXME: revisit this approach once we cope with specializations
Douglas Gregorb88e8882009-07-30 17:40:51 +00001066 // properly.
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001067 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
1068 continue;
1069 }
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001071 TemplateIdsInSpecifier.push_back(SpecType);
1072 }
1073 }
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001075 // Reverse the list of template-ids in the scope specifier, so that we can
1076 // more easily match up the template-ids and the template parameter lists.
1077 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001079 SourceLocation FirstTemplateLoc = DeclStartLoc;
1080 if (NumParamLists)
1081 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001083 // Match the template-ids found in the specifier to the template parameter
1084 // lists.
1085 unsigned Idx = 0;
1086 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1087 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001088 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1089 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001090 if (Idx >= NumParamLists) {
1091 // We have a template-id without a corresponding template parameter
1092 // list.
1093 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001094 // FIXME: the location information here isn't great.
1095 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001096 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001097 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001098 << SS.getRange();
1099 } else {
1100 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1101 << SS.getRange()
1102 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1103 "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001104 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001105 }
1106 return 0;
1107 }
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001109 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001110 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001111 TemplateDecl *Template
Douglas Gregorb88e8882009-07-30 17:40:51 +00001112 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1113
Mike Stump1eb44332009-09-09 15:08:12 +00001114 if (ClassTemplateDecl *ClassTemplate
Douglas Gregorb88e8882009-07-30 17:40:51 +00001115 = dyn_cast<ClassTemplateDecl>(Template)) {
1116 TemplateParameterList *ExpectedTemplateParams = 0;
1117 // Is this template-id naming the primary template?
1118 if (Context.hasSameType(TemplateId,
1119 ClassTemplate->getInjectedClassNameType(Context)))
1120 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1121 // ... or a partial specialization?
1122 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1123 = ClassTemplate->findPartialSpecialization(TemplateId))
1124 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1125
1126 if (ExpectedTemplateParams)
Mike Stump1eb44332009-09-09 15:08:12 +00001127 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregorb88e8882009-07-30 17:40:51 +00001128 ExpectedTemplateParams,
Douglas Gregorfb898e12009-11-12 16:20:59 +00001129 true, TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00001130 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00001131 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001132 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001133 diag::err_template_param_list_matches_nontemplate)
1134 << TemplateId
1135 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001136 else
1137 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001138 }
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001140 // If there were at least as many template-ids as there were template
1141 // parameter lists, then there are no template parameter lists remaining for
1142 // the declaration itself.
1143 if (Idx >= NumParamLists)
1144 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001146 // If there were too many template parameter lists, complain about that now.
1147 if (Idx != NumParamLists - 1) {
1148 while (Idx < NumParamLists - 1) {
Mike Stump1eb44332009-09-09 15:08:12 +00001149 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001150 diag::err_template_spec_extra_headers)
1151 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1152 ParamLists[Idx]->getRAngleLoc());
1153 ++Idx;
1154 }
1155 }
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001157 // Return the last template parameter list, which corresponds to the
1158 // entity being declared.
1159 return ParamLists[NumParamLists - 1];
1160}
1161
Douglas Gregor7532dc62009-03-30 22:58:21 +00001162QualType Sema::CheckTemplateIdType(TemplateName Name,
1163 SourceLocation TemplateLoc,
1164 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001165 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001166 unsigned NumTemplateArgs,
1167 SourceLocation RAngleLoc) {
1168 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001169 if (!Template) {
1170 // The template name does not resolve to a template, so we just
1171 // build a dependent template-id type.
Douglas Gregorc45c2322009-03-31 00:43:58 +00001172 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001173 NumTemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001174 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001175
Douglas Gregor40808ce2009-03-09 23:48:35 +00001176 // Check that the template argument list is well-formed for this
1177 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001178 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1179 NumTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001180 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001181 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001182 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001183 return QualType();
1184
Mike Stump1eb44332009-09-09 15:08:12 +00001185 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001186 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001187 "Converted template argument list is too short!");
1188
1189 QualType CanonType;
1190
Douglas Gregorcaddba02009-11-12 18:38:13 +00001191 if (Name.isDependent() ||
1192 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +00001193 TemplateArgs,
Douglas Gregorcaddba02009-11-12 18:38:13 +00001194 NumTemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001195 // This class template specialization is a dependent
1196 // type. Therefore, its canonical type is another class template
1197 // specialization type that contains all of the converted
1198 // arguments in canonical form. This ensures that, e.g., A<T> and
1199 // A<T, T> have identical types when A is declared as:
1200 //
1201 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001202 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001203 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001204 Converted.getFlatArguments(),
1205 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Douglas Gregor1275ae02009-07-28 23:00:59 +00001207 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001208 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001209 // In the future, we need to teach getTemplateSpecializationType to only
1210 // build the canonical type and return that to us.
1211 CanonType = Context.getCanonicalType(CanonType);
Mike Stump1eb44332009-09-09 15:08:12 +00001212 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001213 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001214 // Find the class template specialization declaration that
1215 // corresponds to these arguments.
1216 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001217 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001218 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001219 Converted.flatSize(),
1220 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001221 void *InsertPos = 0;
1222 ClassTemplateSpecializationDecl *Decl
1223 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1224 if (!Decl) {
1225 // This is the first time we have referenced this class template
1226 // specialization. Create the canonical declaration and add it to
1227 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001228 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001229 ClassTemplate->getDeclContext(),
John McCall9cc78072009-09-11 07:25:08 +00001230 ClassTemplate->getLocation(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001231 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001232 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001233 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1234 Decl->setLexicalDeclContext(CurContext);
1235 }
1236
1237 CanonType = Context.getTypeDeclType(Decl);
1238 }
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Douglas Gregor40808ce2009-03-09 23:48:35 +00001240 // Build the fully-sugared type for this class template
1241 // specialization, which refers back to the class template
1242 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +00001243 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1244 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001245}
1246
Douglas Gregorcc636682009-02-17 23:15:12 +00001247Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001248Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001249 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001250 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001251 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001252 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001253
Douglas Gregor40808ce2009-03-09 23:48:35 +00001254 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00001255 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor314b97f2009-11-10 19:49:08 +00001256 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001257
Douglas Gregor7532dc62009-03-30 22:58:21 +00001258 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001259 TemplateArgs.data(),
1260 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00001261 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001262 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001263
1264 if (Result.isNull())
1265 return true;
1266
John McCall833ca992009-10-29 08:12:44 +00001267 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1268 TemplateSpecializationTypeLoc TL
1269 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1270 TL.setTemplateNameLoc(TemplateLoc);
1271 TL.setLAngleLoc(LAngleLoc);
1272 TL.setRAngleLoc(RAngleLoc);
1273 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1274 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1275
1276 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001277}
John McCallf1bbbb42009-09-04 01:14:41 +00001278
John McCall6b2becf2009-09-08 17:47:29 +00001279Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1280 TagUseKind TUK,
1281 DeclSpec::TST TagSpec,
1282 SourceLocation TagLoc) {
1283 if (TypeResult.isInvalid())
1284 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001285
John McCall833ca992009-10-29 08:12:44 +00001286 // FIXME: preserve source info, ideally without copying the DI.
1287 DeclaratorInfo *DI;
1288 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001289
John McCall6b2becf2009-09-08 17:47:29 +00001290 // Verify the tag specifier.
1291 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001292
John McCall6b2becf2009-09-08 17:47:29 +00001293 if (const RecordType *RT = Type->getAs<RecordType>()) {
1294 RecordDecl *D = RT->getDecl();
1295
1296 IdentifierInfo *Id = D->getIdentifier();
1297 assert(Id && "templated class must have an identifier");
1298
1299 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1300 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001301 << Type
John McCall6b2becf2009-09-08 17:47:29 +00001302 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1303 D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001304 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001305 }
1306 }
1307
John McCall6b2becf2009-09-08 17:47:29 +00001308 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1309
1310 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001311}
1312
Douglas Gregorf17bb742009-10-22 17:20:55 +00001313Sema::OwningExprResult Sema::BuildTemplateIdExpr(NestedNameSpecifier *Qualifier,
1314 SourceRange QualifierRange,
1315 TemplateName Template,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001316 SourceLocation TemplateNameLoc,
1317 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001318 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001319 unsigned NumTemplateArgs,
1320 SourceLocation RAngleLoc) {
1321 // FIXME: Can we do any checking at this point? I guess we could check the
1322 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001323 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001324 // though.
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001325
1326 // Cope with an implicit member access in a C++ non-static member function.
1327 NamedDecl *D = Template.getAsTemplateDecl();
1328 if (!D)
1329 D = Template.getAsOverloadedFunctionDecl();
1330
Douglas Gregorf17bb742009-10-22 17:20:55 +00001331 CXXScopeSpec SS;
1332 SS.setRange(QualifierRange);
1333 SS.setScopeRep(Qualifier);
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001334 QualType ThisType, MemberType;
Douglas Gregorf17bb742009-10-22 17:20:55 +00001335 if (D && isImplicitMemberReference(&SS, D, TemplateNameLoc,
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001336 ThisType, MemberType)) {
1337 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
1338 return Owned(MemberExpr::Create(Context, This, true,
Douglas Gregorf17bb742009-10-22 17:20:55 +00001339 Qualifier, QualifierRange,
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001340 D, TemplateNameLoc, true,
1341 LAngleLoc, TemplateArgs,
1342 NumTemplateArgs, RAngleLoc,
1343 Context.OverloadTy));
1344 }
1345
Douglas Gregorf17bb742009-10-22 17:20:55 +00001346 return Owned(TemplateIdRefExpr::Create(Context, Context.OverloadTy,
1347 Qualifier, QualifierRange,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001348 Template, TemplateNameLoc, LAngleLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001349 TemplateArgs,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001350 NumTemplateArgs, RAngleLoc));
1351}
1352
Douglas Gregorf17bb742009-10-22 17:20:55 +00001353Sema::OwningExprResult Sema::ActOnTemplateIdExpr(const CXXScopeSpec &SS,
1354 TemplateTy TemplateD,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001355 SourceLocation TemplateNameLoc,
1356 SourceLocation LAngleLoc,
1357 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001358 SourceLocation RAngleLoc) {
1359 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001361 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00001362 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor314b97f2009-11-10 19:49:08 +00001363 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001364 TemplateArgsIn.release();
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Douglas Gregorf17bb742009-10-22 17:20:55 +00001366 return BuildTemplateIdExpr((NestedNameSpecifier *)SS.getScopeRep(),
1367 SS.getRange(),
1368 Template, TemplateNameLoc, LAngleLoc,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001369 TemplateArgs.data(), TemplateArgs.size(),
1370 RAngleLoc);
1371}
1372
Douglas Gregorc45c2322009-03-31 00:43:58 +00001373/// \brief Form a dependent template name.
1374///
1375/// This action forms a dependent template name given the template
1376/// name and its (presumably dependent) scope specifier. For
1377/// example, given "MetaFun::template apply", the scope specifier \p
1378/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1379/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001380Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001381Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001382 const CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001383 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001384 TypeTy *ObjectType) {
Mike Stump1eb44332009-09-09 15:08:12 +00001385 if ((ObjectType &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001386 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1387 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001388 // C++0x [temp.names]p5:
1389 // If a name prefixed by the keyword template is not the name of
1390 // a template, the program is ill-formed. [Note: the keyword
1391 // template may not be applied to non-template members of class
1392 // templates. -end note ] [ Note: as is the case with the
1393 // typename prefix, the template prefix is allowed in cases
1394 // where it is not strictly necessary; i.e., when the
1395 // nested-name-specifier or the expression on the left of the ->
1396 // or . is not dependent on a template-parameter, or the use
1397 // does not appear in the scope of a template. -end note]
1398 //
1399 // Note: C++03 was more strict here, because it banned the use of
1400 // the "template" keyword prior to a template-name that was not a
1401 // dependent name. C++ DR468 relaxed this requirement (the
1402 // "template" keyword is now permitted). We follow the C++0x
1403 // rules, even in C++03 mode, retroactively applying the DR.
1404 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001405 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001406 false, Template);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001407 if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001408 Diag(Name.getSourceRange().getBegin(),
1409 diag::err_template_kw_refers_to_non_template)
1410 << GetNameFromUnqualifiedId(Name)
1411 << Name.getSourceRange();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001412 return TemplateTy();
1413 }
1414
1415 return Template;
1416 }
1417
Mike Stump1eb44332009-09-09 15:08:12 +00001418 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001419 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001420
1421 switch (Name.getKind()) {
1422 case UnqualifiedId::IK_Identifier:
1423 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1424 Name.Identifier));
1425
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001426 case UnqualifiedId::IK_OperatorFunctionId:
1427 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1428 Name.OperatorFunctionId.Operator));
1429
Douglas Gregor014e88d2009-11-03 23:16:33 +00001430 default:
1431 break;
1432 }
1433
1434 Diag(Name.getSourceRange().getBegin(),
1435 diag::err_template_kw_refers_to_non_template)
1436 << GetNameFromUnqualifiedId(Name)
1437 << Name.getSourceRange();
1438 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001439}
1440
Mike Stump1eb44332009-09-09 15:08:12 +00001441bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001442 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001443 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001444 const TemplateArgument &Arg = AL.getArgument();
1445
Anders Carlsson436b1562009-06-13 00:33:33 +00001446 // Check template type parameter.
1447 if (Arg.getKind() != TemplateArgument::Type) {
1448 // C++ [temp.arg.type]p1:
1449 // A template-argument for a template-parameter which is a
1450 // type shall be a type-id.
1451
1452 // We have a template type parameter but the template argument
1453 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001454 SourceRange SR = AL.getSourceRange();
1455 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001456 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Anders Carlsson436b1562009-06-13 00:33:33 +00001458 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001459 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001460
John McCall833ca992009-10-29 08:12:44 +00001461 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001462 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Anders Carlsson436b1562009-06-13 00:33:33 +00001464 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001465 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001466 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001467 return false;
1468}
1469
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001470/// \brief Substitute template arguments into the default template argument for
1471/// the given template type parameter.
1472///
1473/// \param SemaRef the semantic analysis object for which we are performing
1474/// the substitution.
1475///
1476/// \param Template the template that we are synthesizing template arguments
1477/// for.
1478///
1479/// \param TemplateLoc the location of the template name that started the
1480/// template-id we are checking.
1481///
1482/// \param RAngleLoc the location of the right angle bracket ('>') that
1483/// terminates the template-id.
1484///
1485/// \param Param the template template parameter whose default we are
1486/// substituting into.
1487///
1488/// \param Converted the list of template arguments provided for template
1489/// parameters that precede \p Param in the template parameter list.
1490///
1491/// \returns the substituted template argument, or NULL if an error occurred.
1492static DeclaratorInfo *
1493SubstDefaultTemplateArgument(Sema &SemaRef,
1494 TemplateDecl *Template,
1495 SourceLocation TemplateLoc,
1496 SourceLocation RAngleLoc,
1497 TemplateTypeParmDecl *Param,
1498 TemplateArgumentListBuilder &Converted) {
1499 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1500
1501 // If the argument type is dependent, instantiate it now based
1502 // on the previously-computed template arguments.
1503 if (ArgType->getType()->isDependentType()) {
1504 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1505 /*TakeArgs=*/false);
1506
1507 MultiLevelTemplateArgumentList AllTemplateArgs
1508 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1509
1510 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1511 Template, Converted.getFlatArguments(),
1512 Converted.flatSize(),
1513 SourceRange(TemplateLoc, RAngleLoc));
1514
1515 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1516 Param->getDefaultArgumentLoc(),
1517 Param->getDeclName());
1518 }
1519
1520 return ArgType;
1521}
1522
1523/// \brief Substitute template arguments into the default template argument for
1524/// the given non-type template parameter.
1525///
1526/// \param SemaRef the semantic analysis object for which we are performing
1527/// the substitution.
1528///
1529/// \param Template the template that we are synthesizing template arguments
1530/// for.
1531///
1532/// \param TemplateLoc the location of the template name that started the
1533/// template-id we are checking.
1534///
1535/// \param RAngleLoc the location of the right angle bracket ('>') that
1536/// terminates the template-id.
1537///
Douglas Gregor788cd062009-11-11 01:00:40 +00001538/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001539/// substituting into.
1540///
1541/// \param Converted the list of template arguments provided for template
1542/// parameters that precede \p Param in the template parameter list.
1543///
1544/// \returns the substituted template argument, or NULL if an error occurred.
1545static Sema::OwningExprResult
1546SubstDefaultTemplateArgument(Sema &SemaRef,
1547 TemplateDecl *Template,
1548 SourceLocation TemplateLoc,
1549 SourceLocation RAngleLoc,
1550 NonTypeTemplateParmDecl *Param,
1551 TemplateArgumentListBuilder &Converted) {
1552 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1553 /*TakeArgs=*/false);
1554
1555 MultiLevelTemplateArgumentList AllTemplateArgs
1556 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1557
1558 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1559 Template, Converted.getFlatArguments(),
1560 Converted.flatSize(),
1561 SourceRange(TemplateLoc, RAngleLoc));
1562
1563 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1564}
1565
Douglas Gregor788cd062009-11-11 01:00:40 +00001566/// \brief Substitute template arguments into the default template argument for
1567/// the given template template parameter.
1568///
1569/// \param SemaRef the semantic analysis object for which we are performing
1570/// the substitution.
1571///
1572/// \param Template the template that we are synthesizing template arguments
1573/// for.
1574///
1575/// \param TemplateLoc the location of the template name that started the
1576/// template-id we are checking.
1577///
1578/// \param RAngleLoc the location of the right angle bracket ('>') that
1579/// terminates the template-id.
1580///
1581/// \param Param the template template parameter whose default we are
1582/// substituting into.
1583///
1584/// \param Converted the list of template arguments provided for template
1585/// parameters that precede \p Param in the template parameter list.
1586///
1587/// \returns the substituted template argument, or NULL if an error occurred.
1588static TemplateName
1589SubstDefaultTemplateArgument(Sema &SemaRef,
1590 TemplateDecl *Template,
1591 SourceLocation TemplateLoc,
1592 SourceLocation RAngleLoc,
1593 TemplateTemplateParmDecl *Param,
1594 TemplateArgumentListBuilder &Converted) {
1595 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1596 /*TakeArgs=*/false);
1597
1598 MultiLevelTemplateArgumentList AllTemplateArgs
1599 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1600
1601 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1602 Template, Converted.getFlatArguments(),
1603 Converted.flatSize(),
1604 SourceRange(TemplateLoc, RAngleLoc));
1605
1606 return SemaRef.SubstTemplateName(
1607 Param->getDefaultArgument().getArgument().getAsTemplate(),
1608 Param->getDefaultArgument().getTemplateNameLoc(),
1609 AllTemplateArgs);
1610}
1611
Douglas Gregore7526412009-11-11 19:31:23 +00001612/// \brief Check that the given template argument corresponds to the given
1613/// template parameter.
1614bool Sema::CheckTemplateArgument(NamedDecl *Param,
1615 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00001616 TemplateDecl *Template,
1617 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001618 SourceLocation RAngleLoc,
1619 TemplateArgumentListBuilder &Converted) {
Douglas Gregord9e15302009-11-11 19:41:09 +00001620 // Check template type parameters.
1621 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00001622 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00001623
Douglas Gregord9e15302009-11-11 19:41:09 +00001624 // Check non-type template parameters.
1625 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00001626 // Do substitution on the type of the non-type template parameter
1627 // with the template arguments we've seen thus far.
1628 QualType NTTPType = NTTP->getType();
1629 if (NTTPType->isDependentType()) {
1630 // Do substitution on the type of the non-type template parameter.
1631 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1632 NTTP, Converted.getFlatArguments(),
1633 Converted.flatSize(),
1634 SourceRange(TemplateLoc, RAngleLoc));
1635
1636 TemplateArgumentList TemplateArgs(Context, Converted,
1637 /*TakeArgs=*/false);
1638 NTTPType = SubstType(NTTPType,
1639 MultiLevelTemplateArgumentList(TemplateArgs),
1640 NTTP->getLocation(),
1641 NTTP->getDeclName());
1642 // If that worked, check the non-type template parameter type
1643 // for validity.
1644 if (!NTTPType.isNull())
1645 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1646 NTTP->getLocation());
1647 if (NTTPType.isNull())
1648 return true;
1649 }
1650
1651 switch (Arg.getArgument().getKind()) {
1652 case TemplateArgument::Null:
1653 assert(false && "Should never see a NULL template argument here");
1654 return true;
1655
1656 case TemplateArgument::Expression: {
1657 Expr *E = Arg.getArgument().getAsExpr();
1658 TemplateArgument Result;
1659 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1660 return true;
1661
1662 Converted.Append(Result);
1663 break;
1664 }
1665
1666 case TemplateArgument::Declaration:
1667 case TemplateArgument::Integral:
1668 // We've already checked this template argument, so just copy
1669 // it to the list of converted arguments.
1670 Converted.Append(Arg.getArgument());
1671 break;
1672
1673 case TemplateArgument::Template:
1674 // We were given a template template argument. It may not be ill-formed;
1675 // see below.
1676 if (DependentTemplateName *DTN
1677 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1678 // We have a template argument such as \c T::template X, which we
1679 // parsed as a template template argument. However, since we now
1680 // know that we need a non-type template argument, convert this
1681 // template name into an expression.
John McCall865d4472009-11-19 22:55:06 +00001682 Expr *E = new (Context) DependentScopeDeclRefExpr(DTN->getIdentifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00001683 Context.DependentTy,
1684 Arg.getTemplateNameLoc(),
1685 Arg.getTemplateQualifierRange(),
1686 DTN->getQualifier(),
1687 /*isAddressOfOperand=*/false);
1688
1689 TemplateArgument Result;
1690 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1691 return true;
1692
1693 Converted.Append(Result);
1694 break;
1695 }
1696
1697 // We have a template argument that actually does refer to a class
1698 // template, template alias, or template template parameter, and
1699 // therefore cannot be a non-type template argument.
1700 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1701 << Arg.getSourceRange();
1702
1703 Diag(Param->getLocation(), diag::note_template_param_here);
1704 return true;
1705
1706 case TemplateArgument::Type: {
1707 // We have a non-type template parameter but the template
1708 // argument is a type.
1709
1710 // C++ [temp.arg]p2:
1711 // In a template-argument, an ambiguity between a type-id and
1712 // an expression is resolved to a type-id, regardless of the
1713 // form of the corresponding template-parameter.
1714 //
1715 // We warn specifically about this case, since it can be rather
1716 // confusing for users.
1717 QualType T = Arg.getArgument().getAsType();
1718 SourceRange SR = Arg.getSourceRange();
1719 if (T->isFunctionType())
1720 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1721 else
1722 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1723 Diag(Param->getLocation(), diag::note_template_param_here);
1724 return true;
1725 }
1726
1727 case TemplateArgument::Pack:
Douglas Gregord9e15302009-11-11 19:41:09 +00001728 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00001729 break;
1730 }
1731
1732 return false;
1733 }
1734
1735
1736 // Check template template parameters.
1737 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1738
1739 // Substitute into the template parameter list of the template
1740 // template parameter, since previously-supplied template arguments
1741 // may appear within the template template parameter.
1742 {
1743 // Set up a template instantiation context.
1744 LocalInstantiationScope Scope(*this);
1745 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1746 TempParm, Converted.getFlatArguments(),
1747 Converted.flatSize(),
1748 SourceRange(TemplateLoc, RAngleLoc));
1749
1750 TemplateArgumentList TemplateArgs(Context, Converted,
1751 /*TakeArgs=*/false);
1752 TempParm = cast_or_null<TemplateTemplateParmDecl>(
1753 SubstDecl(TempParm, CurContext,
1754 MultiLevelTemplateArgumentList(TemplateArgs)));
1755 if (!TempParm)
1756 return true;
1757
1758 // FIXME: TempParam is leaked.
1759 }
1760
1761 switch (Arg.getArgument().getKind()) {
1762 case TemplateArgument::Null:
1763 assert(false && "Should never see a NULL template argument here");
1764 return true;
1765
1766 case TemplateArgument::Template:
1767 if (CheckTemplateArgument(TempParm, Arg))
1768 return true;
1769
1770 Converted.Append(Arg.getArgument());
1771 break;
1772
1773 case TemplateArgument::Expression:
1774 case TemplateArgument::Type:
1775 // We have a template template parameter but the template
1776 // argument does not refer to a template.
1777 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1778 return true;
1779
1780 case TemplateArgument::Declaration:
1781 llvm::llvm_unreachable(
1782 "Declaration argument with template template parameter");
1783 break;
1784 case TemplateArgument::Integral:
1785 llvm::llvm_unreachable(
1786 "Integral argument with template template parameter");
1787 break;
1788
1789 case TemplateArgument::Pack:
Douglas Gregord9e15302009-11-11 19:41:09 +00001790 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00001791 break;
1792 }
1793
1794 return false;
1795}
1796
Douglas Gregorc15cb382009-02-09 23:23:08 +00001797/// \brief Check that the given template argument list is well-formed
1798/// for specializing the given template.
1799bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1800 SourceLocation TemplateLoc,
1801 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001802 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001803 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001804 SourceLocation RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001805 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001806 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001807 TemplateParameterList *Params = Template->getTemplateParameters();
1808 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001809 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001810 bool Invalid = false;
1811
Mike Stump1eb44332009-09-09 15:08:12 +00001812 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001813 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001815 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00001816 (NumArgs < Params->getMinRequiredArguments() &&
1817 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001818 // FIXME: point at either the first arg beyond what we can handle,
1819 // or the '>', depending on whether we have too many or too few
1820 // arguments.
1821 SourceRange Range;
1822 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001823 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001824 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1825 << (NumArgs > NumParams)
1826 << (isa<ClassTemplateDecl>(Template)? 0 :
1827 isa<FunctionTemplateDecl>(Template)? 1 :
1828 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1829 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001830 Diag(Template->getLocation(), diag::note_template_decl_here)
1831 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001832 Invalid = true;
1833 }
Mike Stump1eb44332009-09-09 15:08:12 +00001834
1835 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00001836 // [...] The type and form of each template-argument specified in
1837 // a template-id shall match the type and form specified for the
1838 // corresponding parameter declared by the template in its
1839 // template-parameter-list.
1840 unsigned ArgIdx = 0;
1841 for (TemplateParameterList::iterator Param = Params->begin(),
1842 ParamEnd = Params->end();
1843 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00001844 if (ArgIdx > NumArgs && PartialTemplateArgs)
1845 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Douglas Gregord9e15302009-11-11 19:41:09 +00001847 // If we have a template parameter pack, check every remaining template
1848 // argument against that template parameter pack.
1849 if ((*Param)->isTemplateParameterPack()) {
1850 Converted.BeginPack();
1851 for (; ArgIdx < NumArgs; ++ArgIdx) {
1852 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
1853 TemplateLoc, RAngleLoc, Converted)) {
1854 Invalid = true;
1855 break;
1856 }
1857 }
1858 Converted.EndPack();
1859 continue;
1860 }
1861
Douglas Gregorf35f8282009-11-11 21:54:23 +00001862 if (ArgIdx < NumArgs) {
1863 // Check the template argument we were given.
1864 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
1865 TemplateLoc, RAngleLoc, Converted))
1866 return true;
1867
1868 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001869 }
Douglas Gregore7526412009-11-11 19:31:23 +00001870
Douglas Gregorf35f8282009-11-11 21:54:23 +00001871 // We have a default template argument that we will use.
1872 TemplateArgumentLoc Arg;
1873
1874 // Retrieve the default template argument from the template
1875 // parameter. For each kind of template parameter, we substitute the
1876 // template arguments provided thus far and any "outer" template arguments
1877 // (when the template parameter was part of a nested template) into
1878 // the default argument.
1879 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1880 if (!TTP->hasDefaultArgument()) {
1881 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1882 break;
1883 }
1884
1885 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
1886 Template,
1887 TemplateLoc,
1888 RAngleLoc,
1889 TTP,
1890 Converted);
1891 if (!ArgType)
1892 return true;
1893
1894 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
1895 ArgType);
1896 } else if (NonTypeTemplateParmDecl *NTTP
1897 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1898 if (!NTTP->hasDefaultArgument()) {
1899 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1900 break;
1901 }
1902
1903 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
1904 TemplateLoc,
1905 RAngleLoc,
1906 NTTP,
1907 Converted);
1908 if (E.isInvalid())
1909 return true;
1910
1911 Expr *Ex = E.takeAs<Expr>();
1912 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
1913 } else {
1914 TemplateTemplateParmDecl *TempParm
1915 = cast<TemplateTemplateParmDecl>(*Param);
1916
1917 if (!TempParm->hasDefaultArgument()) {
1918 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1919 break;
1920 }
1921
1922 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
1923 TemplateLoc,
1924 RAngleLoc,
1925 TempParm,
1926 Converted);
1927 if (Name.isNull())
1928 return true;
1929
1930 Arg = TemplateArgumentLoc(TemplateArgument(Name),
1931 TempParm->getDefaultArgument().getTemplateQualifierRange(),
1932 TempParm->getDefaultArgument().getTemplateNameLoc());
1933 }
1934
1935 // Introduce an instantiation record that describes where we are using
1936 // the default template argument.
1937 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
1938 Converted.getFlatArguments(),
1939 Converted.flatSize(),
1940 SourceRange(TemplateLoc, RAngleLoc));
1941
1942 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00001943 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001944 RAngleLoc, Converted))
1945 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001946 }
1947
1948 return Invalid;
1949}
1950
1951/// \brief Check a template argument against its corresponding
1952/// template type parameter.
1953///
1954/// This routine implements the semantics of C++ [temp.arg.type]. It
1955/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001956bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001957 DeclaratorInfo *ArgInfo) {
1958 assert(ArgInfo && "invalid DeclaratorInfo");
1959 QualType Arg = ArgInfo->getType();
1960
Douglas Gregorc15cb382009-02-09 23:23:08 +00001961 // C++ [temp.arg.type]p2:
1962 // A local type, a type with no linkage, an unnamed type or a type
1963 // compounded from any of these types shall not be used as a
1964 // template-argument for a template type-parameter.
1965 //
1966 // FIXME: Perform the recursive and no-linkage type checks.
1967 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00001968 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001969 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00001970 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001971 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00001972 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
1973 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1974 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
1975 << QualType(Tag, 0) << SR;
1976 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00001977 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00001978 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1979 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001980 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1981 return true;
1982 }
1983
1984 return false;
1985}
1986
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001987/// \brief Checks whether the given template argument is the address
1988/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001989bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1990 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001991 bool Invalid = false;
1992
1993 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00001994 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001995 Arg = Cast->getSubExpr();
1996
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001997 // C++0x allows nullptr, and there's no further checking to be done for that.
1998 if (Arg->getType()->isNullPtrType())
1999 return false;
2000
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002001 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002002 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002003 // A template-argument for a non-type, non-template
2004 // template-parameter shall be one of: [...]
2005 //
2006 // -- the address of an object or function with external
2007 // linkage, including function templates and function
2008 // template-ids but excluding non-static class members,
2009 // expressed as & id-expression where the & is optional if
2010 // the name refers to a function or array, or if the
2011 // corresponding template-parameter is a reference; or
2012 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002014 // Ignore (and complain about) any excess parentheses.
2015 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2016 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002017 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002018 diag::err_template_arg_extra_parens)
2019 << Arg->getSourceRange();
2020 Invalid = true;
2021 }
2022
2023 Arg = Parens->getSubExpr();
2024 }
2025
2026 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2027 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2028 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2029 } else
2030 DRE = dyn_cast<DeclRefExpr>(Arg);
2031
2032 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00002033 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002034 diag::err_template_arg_not_object_or_func_form)
2035 << Arg->getSourceRange();
2036
2037 // Cannot refer to non-static data members
2038 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2039 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2040 << Field << Arg->getSourceRange();
2041
2042 // Cannot refer to non-static member functions
2043 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2044 if (!Method->isStatic())
Mike Stump1eb44332009-09-09 15:08:12 +00002045 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002046 diag::err_template_arg_method)
2047 << Method << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002049 // Functions must have external linkage.
2050 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2051 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump1eb44332009-09-09 15:08:12 +00002052 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002053 diag::err_template_arg_function_not_extern)
2054 << Func << Arg->getSourceRange();
2055 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2056 << true;
2057 return true;
2058 }
2059
2060 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002061 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002062 return Invalid;
2063 }
2064
2065 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2066 if (!Var->hasGlobalStorage()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002067 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002068 diag::err_template_arg_object_not_extern)
2069 << Var << Arg->getSourceRange();
2070 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2071 << true;
2072 return true;
2073 }
2074
2075 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002076 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002077 return Invalid;
2078 }
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002080 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002081 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002082 diag::err_template_arg_not_object_or_func)
2083 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002084 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002085 diag::note_template_arg_refers_here);
2086 return true;
2087}
2088
2089/// \brief Checks whether the given template argument is a pointer to
2090/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002091bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2092 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002093 bool Invalid = false;
2094
2095 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002096 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002097 Arg = Cast->getSubExpr();
2098
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002099 // C++0x allows nullptr, and there's no further checking to be done for that.
2100 if (Arg->getType()->isNullPtrType())
2101 return false;
2102
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002103 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002104 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002105 // A template-argument for a non-type, non-template
2106 // template-parameter shall be one of: [...]
2107 //
2108 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002109 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002110
2111 // Ignore (and complain about) any excess parentheses.
2112 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2113 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002114 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002115 diag::err_template_arg_extra_parens)
2116 << Arg->getSourceRange();
2117 Invalid = true;
2118 }
2119
2120 Arg = Parens->getSubExpr();
2121 }
2122
Douglas Gregorcaddba02009-11-12 18:38:13 +00002123 // A pointer-to-member constant written &Class::member.
2124 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002125 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2126 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2127 if (DRE && !DRE->getQualifier())
2128 DRE = 0;
2129 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002130 }
2131 // A constant of pointer-to-member type.
2132 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2133 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2134 if (VD->getType()->isMemberPointerType()) {
2135 if (isa<NonTypeTemplateParmDecl>(VD) ||
2136 (isa<VarDecl>(VD) &&
2137 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2138 if (Arg->isTypeDependent() || Arg->isValueDependent())
2139 Converted = TemplateArgument(Arg->Retain());
2140 else
2141 Converted = TemplateArgument(VD->getCanonicalDecl());
2142 return Invalid;
2143 }
2144 }
2145 }
2146
2147 DRE = 0;
2148 }
2149
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002150 if (!DRE)
2151 return Diag(Arg->getSourceRange().getBegin(),
2152 diag::err_template_arg_not_pointer_to_member_form)
2153 << Arg->getSourceRange();
2154
2155 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2156 assert((isa<FieldDecl>(DRE->getDecl()) ||
2157 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2158 "Only non-static member pointers can make it here");
2159
2160 // Okay: this is the address of a non-static member, and therefore
2161 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002162 if (Arg->isTypeDependent() || Arg->isValueDependent())
2163 Converted = TemplateArgument(Arg->Retain());
2164 else
2165 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002166 return Invalid;
2167 }
2168
2169 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002170 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002171 diag::err_template_arg_not_pointer_to_member_form)
2172 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002173 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002174 diag::note_template_arg_refers_here);
2175 return true;
2176}
2177
Douglas Gregorc15cb382009-02-09 23:23:08 +00002178/// \brief Check a template argument against its corresponding
2179/// non-type template parameter.
2180///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002181/// This routine implements the semantics of C++ [temp.arg.nontype].
2182/// It returns true if an error occurred, and false otherwise. \p
2183/// InstantiatedParamType is the type of the non-type template
2184/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002185///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002186/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002187bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002188 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002189 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002190 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2191
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002192 // If either the parameter has a dependent type or the argument is
2193 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002194 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00002195 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2196 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002197 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002198 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002199 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002200
2201 // C++ [temp.arg.nontype]p5:
2202 // The following conversions are performed on each expression used
2203 // as a non-type template-argument. If a non-type
2204 // template-argument cannot be converted to the type of the
2205 // corresponding template-parameter then the program is
2206 // ill-formed.
2207 //
2208 // -- for a non-type template-parameter of integral or
2209 // enumeration type, integral promotions (4.5) and integral
2210 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002211 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002212 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002213 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002214 // C++ [temp.arg.nontype]p1:
2215 // A template-argument for a non-type, non-template
2216 // template-parameter shall be one of:
2217 //
2218 // -- an integral constant-expression of integral or enumeration
2219 // type; or
2220 // -- the name of a non-type template-parameter; or
2221 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002222 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002223 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002224 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002225 diag::err_template_arg_not_integral_or_enumeral)
2226 << ArgType << Arg->getSourceRange();
2227 Diag(Param->getLocation(), diag::note_template_param_here);
2228 return true;
2229 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002230 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002231 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2232 << ArgType << Arg->getSourceRange();
2233 return true;
2234 }
2235
2236 // FIXME: We need some way to more easily get the unqualified form
2237 // of the types without going all the way to the
2238 // canonical type.
2239 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2240 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2241 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2242 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2243
2244 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002245 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002246 // Okay: no conversion necessary
2247 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2248 !ParamType->isEnumeralType()) {
2249 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002250 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002251 } else {
2252 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002253 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002254 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002255 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002256 Diag(Param->getLocation(), diag::note_template_param_here);
2257 return true;
2258 }
2259
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002260 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002261 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002262 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002263
2264 if (!Arg->isValueDependent()) {
2265 // Check that an unsigned parameter does not receive a negative
2266 // value.
2267 if (IntegerType->isUnsignedIntegerType()
2268 && (Value.isSigned() && Value.isNegative())) {
2269 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2270 << Value.toString(10) << Param->getType()
2271 << Arg->getSourceRange();
2272 Diag(Param->getLocation(), diag::note_template_param_here);
2273 return true;
2274 }
2275
2276 // Check that we don't overflow the template parameter type.
2277 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2278 if (Value.getActiveBits() > AllowedBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00002279 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002280 diag::err_template_arg_too_large)
2281 << Value.toString(10) << Param->getType()
2282 << Arg->getSourceRange();
2283 Diag(Param->getLocation(), diag::note_template_param_here);
2284 return true;
2285 }
2286
2287 if (Value.getBitWidth() != AllowedBits)
2288 Value.extOrTrunc(AllowedBits);
2289 Value.setIsSigned(IntegerType->isSignedIntegerType());
2290 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002291
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002292 // Add the value of this argument to the list of converted
2293 // arguments. We use the bitwidth and signedness of the template
2294 // parameter.
2295 if (Arg->isValueDependent()) {
2296 // The argument is value-dependent. Create a new
2297 // TemplateArgument with the converted expression.
2298 Converted = TemplateArgument(Arg);
2299 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002300 }
2301
John McCall833ca992009-10-29 08:12:44 +00002302 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002303 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002304 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002305 return false;
2306 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002307
Douglas Gregorb86b0572009-02-11 01:18:59 +00002308 // Handle pointer-to-function, reference-to-function, and
2309 // pointer-to-member-function all in (roughly) the same way.
2310 if (// -- For a non-type template-parameter of type pointer to
2311 // function, only the function-to-pointer conversion (4.3) is
2312 // applied. If the template-argument represents a set of
2313 // overloaded functions (or a pointer to such), the matching
2314 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002315 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002316 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002317 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002318 // -- For a non-type template-parameter of type reference to
2319 // function, no conversions apply. If the template-argument
2320 // represents a set of overloaded functions, the matching
2321 // function is selected from the set (13.4).
2322 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002323 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002324 // -- For a non-type template-parameter of type pointer to
2325 // member function, no conversions apply. If the
2326 // template-argument represents a set of overloaded member
2327 // functions, the matching member function is selected from
2328 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002329 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002330 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002331 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002332 ->isFunctionType())) {
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 don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002336 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2337 ParamType->isMemberPointerType())) {
2338 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002339 if (ParamType->isMemberPointerType())
2340 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2341 else
2342 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002343 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002344 ArgType = Context.getPointerType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002345 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump1eb44332009-09-09 15:08:12 +00002346 } else if (FunctionDecl *Fn
Douglas Gregora35284b2009-02-11 00:19:33 +00002347 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002348 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2349 return true;
2350
Anders Carlsson96ad5332009-10-21 17:16:23 +00002351 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00002352 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002353 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002354 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman73c39ab2009-10-20 08:27:19 +00002355 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregora35284b2009-02-11 00:19:33 +00002356 }
2357 }
2358
Mike Stump1eb44332009-09-09 15:08:12 +00002359 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002360 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002361 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002362 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002363 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002364 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002365 Diag(Param->getLocation(), diag::note_template_param_here);
2366 return true;
2367 }
Mike Stump1eb44332009-09-09 15:08:12 +00002368
Douglas Gregorcaddba02009-11-12 18:38:13 +00002369 if (ParamType->isMemberPointerType())
2370 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump1eb44332009-09-09 15:08:12 +00002371
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002372 NamedDecl *Entity = 0;
2373 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2374 return true;
2375
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002376 if (Entity)
2377 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002378 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002379 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00002380 }
2381
Chris Lattnerfe90de72009-02-20 21:37:53 +00002382 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002383 // -- for a non-type template-parameter of type pointer to
2384 // object, qualification conversions (4.4) and the
2385 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002386 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002387 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002388 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002389
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002390 if (ArgType->isNullPtrType()) {
2391 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002392 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002393 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002394 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002395 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002396 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002397
Douglas Gregorb86b0572009-02-11 01:18:59 +00002398 if (IsQualificationConversion(ArgType, ParamType)) {
2399 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002400 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002401 }
Mike Stump1eb44332009-09-09 15:08:12 +00002402
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002403 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002404 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002405 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002406 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002407 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002408 Diag(Param->getLocation(), diag::note_template_param_here);
2409 return true;
2410 }
Mike Stump1eb44332009-09-09 15:08:12 +00002411
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002412 NamedDecl *Entity = 0;
2413 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2414 return true;
2415
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002416 if (Entity)
2417 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002418 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002419 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002420 }
Mike Stump1eb44332009-09-09 15:08:12 +00002421
Ted Kremenek6217b802009-07-29 21:53:49 +00002422 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002423 // -- For a non-type template-parameter of type reference to
2424 // object, no conversions apply. The type referred to by the
2425 // reference may be more cv-qualified than the (otherwise
2426 // identical) type of the template-argument. The
2427 // template-parameter is bound directly to the
2428 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002429 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002430 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002431
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002432 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002433 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002434 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002435 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002436 << Arg->getSourceRange();
2437 Diag(Param->getLocation(), diag::note_template_param_here);
2438 return true;
2439 }
2440
Mike Stump1eb44332009-09-09 15:08:12 +00002441 unsigned ParamQuals
Douglas Gregorb86b0572009-02-11 01:18:59 +00002442 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2443 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00002444
Douglas Gregorb86b0572009-02-11 01:18:59 +00002445 if ((ParamQuals | ArgQuals) != ParamQuals) {
2446 Diag(Arg->getSourceRange().getBegin(),
2447 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002448 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002449 << Arg->getSourceRange();
2450 Diag(Param->getLocation(), diag::note_template_param_here);
2451 return true;
2452 }
Mike Stump1eb44332009-09-09 15:08:12 +00002453
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002454 NamedDecl *Entity = 0;
2455 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2456 return true;
2457
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002458 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002459 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002460 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002461 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002462
2463 // -- For a non-type template-parameter of type pointer to data
2464 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002465 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00002466 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2467
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002468 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002469 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002470 } else if (ArgType->isNullPtrType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002471 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002472 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002473 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002474 } else {
2475 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002476 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002477 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002478 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002479 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002480 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002481 }
2482
Douglas Gregorcaddba02009-11-12 18:38:13 +00002483 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002484}
2485
2486/// \brief Check a template argument against its corresponding
2487/// template template parameter.
2488///
2489/// This routine implements the semantics of C++ [temp.arg.template].
2490/// It returns true if an error occurred, and false otherwise.
2491bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00002492 const TemplateArgumentLoc &Arg) {
2493 TemplateName Name = Arg.getArgument().getAsTemplate();
2494 TemplateDecl *Template = Name.getAsTemplateDecl();
2495 if (!Template) {
2496 // Any dependent template name is fine.
2497 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2498 return false;
2499 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002500
2501 // C++ [temp.arg.template]p1:
2502 // A template-argument for a template template-parameter shall be
2503 // the name of a class template, expressed as id-expression. Only
2504 // primary class templates are considered when matching the
2505 // template template argument with the corresponding parameter;
2506 // partial specializations are not considered even if their
2507 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002508 //
2509 // Note that we also allow template template parameters here, which
2510 // will happen when we are dealing with, e.g., class template
2511 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002512 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002513 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002514 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00002515 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00002516 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00002517 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002518 << Template;
2519 }
2520
2521 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2522 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00002523 true,
2524 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00002525 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002526}
2527
Douglas Gregorddc29e12009-02-06 22:42:48 +00002528/// \brief Determine whether the given template parameter lists are
2529/// equivalent.
2530///
Mike Stump1eb44332009-09-09 15:08:12 +00002531/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00002532/// source code as part of a new template declaration.
2533///
2534/// \param Old The old template parameter list, typically found via
2535/// name lookup of the template declared with this template parameter
2536/// list.
2537///
2538/// \param Complain If true, this routine will produce a diagnostic if
2539/// the template parameter lists are not equivalent.
2540///
Douglas Gregorfb898e12009-11-12 16:20:59 +00002541/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00002542///
2543/// \param TemplateArgLoc If this source location is valid, then we
2544/// are actually checking the template parameter list of a template
2545/// argument (New) against the template parameter list of its
2546/// corresponding template template parameter (Old). We produce
2547/// slightly different diagnostics in this scenario.
2548///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002549/// \returns True if the template parameter lists are equal, false
2550/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002551bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00002552Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2553 TemplateParameterList *Old,
2554 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002555 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002556 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002557 if (Old->size() != New->size()) {
2558 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002559 unsigned NextDiag = diag::err_template_param_list_different_arity;
2560 if (TemplateArgLoc.isValid()) {
2561 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2562 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00002563 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002564 Diag(New->getTemplateLoc(), NextDiag)
2565 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00002566 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002567 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002568 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002569 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002570 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2571 }
2572
2573 return false;
2574 }
2575
2576 for (TemplateParameterList::iterator OldParm = Old->begin(),
2577 OldParmEnd = Old->end(), NewParm = New->begin();
2578 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2579 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002580 if (Complain) {
2581 unsigned NextDiag = diag::err_template_param_different_kind;
2582 if (TemplateArgLoc.isValid()) {
2583 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2584 NextDiag = diag::note_template_param_different_kind;
2585 }
2586 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002587 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002588 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002589 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00002590 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002591 return false;
2592 }
2593
2594 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2595 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002596 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00002597 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002598 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2599 // The types of non-type template parameters must agree.
2600 NonTypeTemplateParmDecl *NewNTTP
2601 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00002602
2603 // If we are matching a template template argument to a template
2604 // template parameter and one of the non-type template parameter types
2605 // is dependent, then we must wait until template instantiation time
2606 // to actually compare the arguments.
2607 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2608 (OldNTTP->getType()->isDependentType() ||
2609 NewNTTP->getType()->isDependentType()))
2610 continue;
2611
Douglas Gregorddc29e12009-02-06 22:42:48 +00002612 if (Context.getCanonicalType(OldNTTP->getType()) !=
2613 Context.getCanonicalType(NewNTTP->getType())) {
2614 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002615 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2616 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002617 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002618 diag::err_template_arg_template_params_mismatch);
2619 NextDiag = diag::note_template_nontype_parm_different_type;
2620 }
2621 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002622 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00002623 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00002624 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00002625 diag::note_template_nontype_parm_prev_declaration)
2626 << OldNTTP->getType();
2627 }
2628 return false;
2629 }
2630 } else {
2631 // The template parameter lists of template template
2632 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00002633 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00002634 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00002635 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002636 = cast<TemplateTemplateParmDecl>(*OldParm);
2637 TemplateTemplateParmDecl *NewTTP
2638 = cast<TemplateTemplateParmDecl>(*NewParm);
2639 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2640 OldTTP->getTemplateParameters(),
2641 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002642 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00002643 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002644 return false;
2645 }
2646 }
2647
2648 return true;
2649}
2650
2651/// \brief Check whether a template can be declared within this scope.
2652///
2653/// If the template declaration is valid in this scope, returns
2654/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00002655bool
Douglas Gregor05396e22009-08-25 17:23:04 +00002656Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002657 // Find the nearest enclosing declaration scope.
2658 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2659 (S->getFlags() & Scope::TemplateParamScope) != 0)
2660 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002661
Douglas Gregorddc29e12009-02-06 22:42:48 +00002662 // C++ [temp]p2:
2663 // A template-declaration can appear only as a namespace scope or
2664 // class scope declaration.
2665 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002666 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2667 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00002668 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00002669 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002670
Eli Friedman1503f772009-07-31 01:43:05 +00002671 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002672 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002673
2674 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2675 return false;
2676
Mike Stump1eb44332009-09-09 15:08:12 +00002677 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002678 diag::err_template_outside_namespace_or_class_scope)
2679 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002680}
Douglas Gregorcc636682009-02-17 23:15:12 +00002681
Douglas Gregord5cb8762009-10-07 00:13:32 +00002682/// \brief Determine what kind of template specialization the given declaration
2683/// is.
2684static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2685 if (!D)
2686 return TSK_Undeclared;
2687
Douglas Gregorf6b11852009-10-08 15:14:33 +00002688 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2689 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00002690 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2691 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002692 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2693 return Var->getTemplateSpecializationKind();
2694
Douglas Gregord5cb8762009-10-07 00:13:32 +00002695 return TSK_Undeclared;
2696}
2697
Douglas Gregor9302da62009-10-14 23:50:59 +00002698/// \brief Check whether a specialization is well-formed in the current
2699/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00002700///
Douglas Gregor9302da62009-10-14 23:50:59 +00002701/// This routine determines whether a template specialization can be declared
2702/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002703///
2704/// \param S the semantic analysis object for which this check is being
2705/// performed.
2706///
2707/// \param Specialized the entity being specialized or instantiated, which
2708/// may be a kind of template (class template, function template, etc.) or
2709/// a member of a class template (member function, static data member,
2710/// member class).
2711///
2712/// \param PrevDecl the previous declaration of this entity, if any.
2713///
2714/// \param Loc the location of the explicit specialization or instantiation of
2715/// this entity.
2716///
2717/// \param IsPartialSpecialization whether this is a partial specialization of
2718/// a class template.
2719///
Douglas Gregord5cb8762009-10-07 00:13:32 +00002720/// \returns true if there was an error that we cannot recover from, false
2721/// otherwise.
2722static bool CheckTemplateSpecializationScope(Sema &S,
2723 NamedDecl *Specialized,
2724 NamedDecl *PrevDecl,
2725 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00002726 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002727 // Keep these "kind" numbers in sync with the %select statements in the
2728 // various diagnostics emitted by this routine.
2729 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002730 bool isTemplateSpecialization = false;
2731 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002732 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002733 isTemplateSpecialization = true;
2734 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002735 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002736 isTemplateSpecialization = true;
2737 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00002738 EntityKind = 3;
2739 else if (isa<VarDecl>(Specialized))
2740 EntityKind = 4;
2741 else if (isa<RecordDecl>(Specialized))
2742 EntityKind = 5;
2743 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00002744 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2745 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00002746 return true;
2747 }
2748
Douglas Gregor88b70942009-02-25 22:02:03 +00002749 // C++ [temp.expl.spec]p2:
2750 // An explicit specialization shall be declared in the namespace
2751 // of which the template is a member, or, for member templates, in
2752 // the namespace of which the enclosing class or enclosing class
2753 // template is a member. An explicit specialization of a member
2754 // function, member class or static data member of a class
2755 // template shall be declared in the namespace of which the class
2756 // template is a member. Such a declaration may also be a
2757 // definition. If the declaration is not a definition, the
2758 // specialization may be defined later in the name- space in which
2759 // the explicit specialization was declared, or in a namespace
2760 // that encloses the one in which the explicit specialization was
2761 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00002762 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2763 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00002764 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00002765 return true;
2766 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002767
Douglas Gregor0a407472009-10-07 17:30:37 +00002768 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2769 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00002770 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00002771 return true;
2772 }
2773
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002774 // C++ [temp.class.spec]p6:
2775 // A class template partial specialization may be declared or redeclared
2776 // in any namespace scope in which its definition may be defined (14.5.1
2777 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002778 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002779 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00002780 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002781 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00002782 if ((!PrevDecl ||
2783 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2784 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2785 // There is no prior declaration of this entity, so this
2786 // specialization must be in the same context as the template
2787 // itself.
2788 if (!DC->Equals(SpecializedContext)) {
2789 if (isa<TranslationUnitDecl>(SpecializedContext))
2790 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2791 << EntityKind << Specialized;
2792 else if (isa<NamespaceDecl>(SpecializedContext))
2793 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2794 << EntityKind << Specialized
2795 << cast<NamedDecl>(SpecializedContext);
2796
2797 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2798 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002799 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002800 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00002801
2802 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00002803 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00002804 // Note that HandleDeclarator() performs this check for explicit
2805 // specializations of function templates, static data members, and member
2806 // functions, so we skip the check here for those kinds of entities.
2807 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002808 // Should we refactor that check, so that it occurs later?
2809 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00002810 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2811 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002812 if (isa<TranslationUnitDecl>(SpecializedContext))
2813 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2814 << EntityKind << Specialized;
2815 else if (isa<NamespaceDecl>(SpecializedContext))
2816 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2817 << EntityKind << Specialized
2818 << cast<NamedDecl>(SpecializedContext);
2819
Douglas Gregor9302da62009-10-14 23:50:59 +00002820 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00002821 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00002822
2823 // FIXME: check for specialization-after-instantiation errors and such.
2824
Douglas Gregor88b70942009-02-25 22:02:03 +00002825 return false;
2826}
Douglas Gregord5cb8762009-10-07 00:13:32 +00002827
Douglas Gregore94866f2009-06-12 21:21:02 +00002828/// \brief Check the non-type template arguments of a class template
2829/// partial specialization according to C++ [temp.class.spec]p9.
2830///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002831/// \param TemplateParams the template parameters of the primary class
2832/// template.
2833///
2834/// \param TemplateArg the template arguments of the class template
2835/// partial specialization.
2836///
2837/// \param MirrorsPrimaryTemplate will be set true if the class
2838/// template partial specialization arguments are identical to the
2839/// implicit template arguments of the primary template. This is not
2840/// necessarily an error (C++0x), and it is left to the caller to diagnose
2841/// this condition when it is an error.
2842///
Douglas Gregore94866f2009-06-12 21:21:02 +00002843/// \returns true if there was an error, false otherwise.
2844bool Sema::CheckClassTemplatePartialSpecializationArgs(
2845 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002846 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002847 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002848 // FIXME: the interface to this function will have to change to
2849 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002850 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Anders Carlssonfb250522009-06-23 01:26:57 +00002852 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00002853
Douglas Gregore94866f2009-06-12 21:21:02 +00002854 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002855 // Determine whether the template argument list of the partial
2856 // specialization is identical to the implicit argument list of
2857 // the primary template. The caller may need to diagnostic this as
2858 // an error per C++ [temp.class.spec]p9b3.
2859 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00002860 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002861 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2862 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002863 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002864 MirrorsPrimaryTemplate = false;
2865 } else if (TemplateTemplateParmDecl *TTP
2866 = dyn_cast<TemplateTemplateParmDecl>(
2867 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00002868 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00002869 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00002870 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002871 if (!ArgDecl ||
2872 ArgDecl->getIndex() != TTP->getIndex() ||
2873 ArgDecl->getDepth() != TTP->getDepth())
2874 MirrorsPrimaryTemplate = false;
2875 }
2876 }
2877
Mike Stump1eb44332009-09-09 15:08:12 +00002878 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00002879 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002880 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002881 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002882 }
2883
Anders Carlsson6360be72009-06-13 18:20:51 +00002884 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002885 if (!ArgExpr) {
2886 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002887 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002888 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002889
2890 // C++ [temp.class.spec]p8:
2891 // A non-type argument is non-specialized if it is the name of a
2892 // non-type parameter. All other non-type arguments are
2893 // specialized.
2894 //
2895 // Below, we check the two conditions that only apply to
2896 // specialized non-type arguments, so skip any non-specialized
2897 // arguments.
2898 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00002899 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002900 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002901 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002902 (Param->getIndex() != NTTP->getIndex() ||
2903 Param->getDepth() != NTTP->getDepth()))
2904 MirrorsPrimaryTemplate = false;
2905
Douglas Gregore94866f2009-06-12 21:21:02 +00002906 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002907 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002908
2909 // C++ [temp.class.spec]p9:
2910 // Within the argument list of a class template partial
2911 // specialization, the following restrictions apply:
2912 // -- A partially specialized non-type argument expression
2913 // shall not involve a template parameter of the partial
2914 // specialization except when the argument expression is a
2915 // simple identifier.
2916 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002917 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00002918 diag::err_dependent_non_type_arg_in_partial_spec)
2919 << ArgExpr->getSourceRange();
2920 return true;
2921 }
2922
2923 // -- The type of a template parameter corresponding to a
2924 // specialized non-type argument shall not be dependent on a
2925 // parameter of the specialization.
2926 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002927 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00002928 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2929 << Param->getType()
2930 << ArgExpr->getSourceRange();
2931 Diag(Param->getLocation(), diag::note_template_param_here);
2932 return true;
2933 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002934
2935 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002936 }
2937
2938 return false;
2939}
2940
Douglas Gregor212e81c2009-03-25 00:13:59 +00002941Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00002942Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2943 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00002944 SourceLocation KWLoc,
Douglas Gregorcc636682009-02-17 23:15:12 +00002945 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002946 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002947 SourceLocation TemplateNameLoc,
2948 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002949 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002950 SourceLocation RAngleLoc,
2951 AttributeList *Attr,
2952 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002953 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00002954
Douglas Gregorcc636682009-02-17 23:15:12 +00002955 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002956 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00002957 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00002958 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
2959
2960 if (!ClassTemplate) {
2961 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
2962 << (Name.getAsTemplateDecl() &&
2963 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
2964 return true;
2965 }
Douglas Gregorcc636682009-02-17 23:15:12 +00002966
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002967 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002968 bool isPartialSpecialization = false;
2969
Douglas Gregor88b70942009-02-25 22:02:03 +00002970 // Check the validity of the template headers that introduce this
2971 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002972 // FIXME: We probably shouldn't complain about these headers for
2973 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00002974 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00002975 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2976 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002977 TemplateParameterLists.size(),
2978 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00002979 if (TemplateParams && TemplateParams->size() > 0) {
2980 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002981
Douglas Gregor05396e22009-08-25 17:23:04 +00002982 // C++ [temp.class.spec]p10:
2983 // The template parameter list of a specialization shall not
2984 // contain default template argument values.
2985 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2986 Decl *Param = TemplateParams->getParam(I);
2987 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2988 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002989 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002990 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00002991 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00002992 }
2993 } else if (NonTypeTemplateParmDecl *NTTP
2994 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2995 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002996 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002997 diag::err_default_arg_in_partial_spec)
2998 << DefArg->getSourceRange();
2999 NTTP->setDefaultArgument(0);
3000 DefArg->Destroy(Context);
3001 }
3002 } else {
3003 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003004 if (TTP->hasDefaultArgument()) {
3005 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003006 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003007 << TTP->getDefaultArgument().getSourceRange();
3008 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003009 }
3010 }
3011 }
Douglas Gregora735b202009-10-13 14:39:41 +00003012 } else if (TemplateParams) {
3013 if (TUK == TUK_Friend)
3014 Diag(KWLoc, diag::err_template_spec_friend)
3015 << CodeModificationHint::CreateRemoval(
3016 SourceRange(TemplateParams->getTemplateLoc(),
3017 TemplateParams->getRAngleLoc()))
3018 << SourceRange(LAngleLoc, RAngleLoc);
3019 else
3020 isExplicitSpecialization = true;
3021 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003022 Diag(KWLoc, diag::err_template_spec_needs_header)
3023 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003024 isExplicitSpecialization = true;
3025 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003026
Douglas Gregorcc636682009-02-17 23:15:12 +00003027 // Check that the specialization uses the same tag kind as the
3028 // original template.
3029 TagDecl::TagKind Kind;
3030 switch (TagSpec) {
3031 default: assert(0 && "Unknown tag type!");
3032 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3033 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3034 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3035 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003036 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003037 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003038 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003039 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003040 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003041 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003042 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003043 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003044 diag::note_previous_use);
3045 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3046 }
3047
Douglas Gregor40808ce2009-03-09 23:48:35 +00003048 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00003049 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor314b97f2009-11-10 19:49:08 +00003050 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003051
Douglas Gregorcc636682009-02-17 23:15:12 +00003052 // Check that the template argument list is well-formed for this
3053 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003054 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3055 TemplateArgs.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003056 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00003057 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00003058 RAngleLoc, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003059 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003060
Mike Stump1eb44332009-09-09 15:08:12 +00003061 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003062 ClassTemplate->getTemplateParameters()->size()) &&
3063 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003064
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003065 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003066 // corresponds to these arguments.
3067 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003068 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003069 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003070 if (CheckClassTemplatePartialSpecializationArgs(
3071 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003072 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003073 return true;
3074
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003075 if (MirrorsPrimaryTemplate) {
3076 // C++ [temp.class.spec]p9b3:
3077 //
Mike Stump1eb44332009-09-09 15:08:12 +00003078 // -- The argument list of the specialization shall not be identical
3079 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003080 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003081 << (TUK == TUK_Definition)
Mike Stump1eb44332009-09-09 15:08:12 +00003082 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003083 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003084 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003085 ClassTemplate->getIdentifier(),
3086 TemplateNameLoc,
3087 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003088 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003089 AS_none);
3090 }
3091
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003092 // FIXME: Diagnose friend partial specializations
3093
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003094 // FIXME: Template parameter list matters, too
Mike Stump1eb44332009-09-09 15:08:12 +00003095 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003096 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003097 Converted.flatSize(),
3098 Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003099 } else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003100 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003101 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003102 Converted.flatSize(),
3103 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003104 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003105 ClassTemplateSpecializationDecl *PrevDecl = 0;
3106
3107 if (isPartialSpecialization)
3108 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003109 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003110 InsertPos);
3111 else
3112 PrevDecl
3113 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003114
3115 ClassTemplateSpecializationDecl *Specialization = 0;
3116
Douglas Gregor88b70942009-02-25 22:02:03 +00003117 // Check whether we can declare a class template specialization in
3118 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003119 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003120 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003121 TemplateNameLoc,
3122 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003123 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003124
Douglas Gregorb88e8882009-07-30 17:40:51 +00003125 // The canonical type
3126 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003127 if (PrevDecl &&
3128 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3129 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003130 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003131 // arguments was referenced but not declared, or we're only
3132 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003133 // declaration node as our own, updating its source location to
3134 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003135 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003136 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003137 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003138 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003139 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003140 // Build the canonical type that describes the converted template
3141 // arguments of the class template partial specialization.
3142 CanonType = Context.getTemplateSpecializationType(
3143 TemplateName(ClassTemplate),
3144 Converted.getFlatArguments(),
3145 Converted.flatSize());
3146
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003147 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003148 ClassTemplatePartialSpecializationDecl *PrevPartial
3149 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00003150 ClassTemplatePartialSpecializationDecl *Partial
3151 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003152 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003153 TemplateNameLoc,
3154 TemplateParams,
3155 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003156 Converted,
John McCall833ca992009-10-29 08:12:44 +00003157 TemplateArgs.data(),
3158 TemplateArgs.size(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003159 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003160
3161 if (PrevPartial) {
3162 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3163 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3164 } else {
3165 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3166 }
3167 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003168
Douglas Gregored9c0f92009-10-29 00:04:11 +00003169 // If we are providing an explicit specialization of a member class
3170 // template specialization, make a note of that.
3171 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3172 PrevPartial->setMemberSpecialization();
3173
Douglas Gregor031a5882009-06-13 00:26:55 +00003174 // Check that all of the template parameters of the class template
3175 // partial specialization are deducible from the template
3176 // arguments. If not, this class template partial specialization
3177 // will never be used.
3178 llvm::SmallVector<bool, 8> DeducibleParams;
3179 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003180 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003181 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003182 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003183 unsigned NumNonDeducible = 0;
3184 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3185 if (!DeducibleParams[I])
3186 ++NumNonDeducible;
3187
3188 if (NumNonDeducible) {
3189 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3190 << (NumNonDeducible > 1)
3191 << SourceRange(TemplateNameLoc, RAngleLoc);
3192 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3193 if (!DeducibleParams[I]) {
3194 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3195 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003196 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003197 diag::note_partial_spec_unused_parameter)
3198 << Param->getDeclName();
3199 else
Mike Stump1eb44332009-09-09 15:08:12 +00003200 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003201 diag::note_partial_spec_unused_parameter)
3202 << std::string("<anonymous>");
3203 }
3204 }
3205 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003206 } else {
3207 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003208 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003209 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003210 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorcc636682009-02-17 23:15:12 +00003211 ClassTemplate->getDeclContext(),
3212 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003213 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003214 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003215 PrevDecl);
3216
3217 if (PrevDecl) {
3218 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3219 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3220 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003221 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003222 InsertPos);
3223 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003224
3225 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003226 }
3227
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003228 // C++ [temp.expl.spec]p6:
3229 // If a template, a member template or the member of a class template is
3230 // explicitly specialized then that specialization shall be declared
3231 // before the first use of that specialization that would cause an implicit
3232 // instantiation to take place, in every translation unit in which such a
3233 // use occurs; no diagnostic is required.
3234 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3235 SourceRange Range(TemplateNameLoc, RAngleLoc);
3236 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3237 << Context.getTypeDeclType(Specialization) << Range;
3238
3239 Diag(PrevDecl->getPointOfInstantiation(),
3240 diag::note_instantiation_required_here)
3241 << (PrevDecl->getTemplateSpecializationKind()
3242 != TSK_ImplicitInstantiation);
3243 return true;
3244 }
3245
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003246 // If this is not a friend, note that this is an explicit specialization.
3247 if (TUK != TUK_Friend)
3248 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003249
3250 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003251 if (TUK == TUK_Definition) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003252 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003253 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003254 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003255 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003256 Diag(Def->getLocation(), diag::note_previous_definition);
3257 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003258 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003259 }
3260 }
3261
Douglas Gregorfc705b82009-02-26 22:19:44 +00003262 // Build the fully-sugared type for this class template
3263 // specialization as the user wrote in the specialization
3264 // itself. This means that we'll pretty-print the type retrieved
3265 // from the specialization's declaration the way that the user
3266 // actually wrote the specialization, rather than formatting the
3267 // name based on the "canonical" representation used to store the
3268 // template arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003269 QualType WrittenTy
3270 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00003271 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00003272 TemplateArgs.size(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00003273 CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003274 if (TUK != TUK_Friend)
3275 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003276 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003277
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003278 // C++ [temp.expl.spec]p9:
3279 // A template explicit specialization is in the scope of the
3280 // namespace in which the template was defined.
3281 //
3282 // We actually implement this paragraph where we set the semantic
3283 // context (in the creation of the ClassTemplateSpecializationDecl),
3284 // but we also maintain the lexical context where the actual
3285 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003286 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003287
Douglas Gregorcc636682009-02-17 23:15:12 +00003288 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003289 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003290 Specialization->startDefinition();
3291
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003292 if (TUK == TUK_Friend) {
3293 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3294 TemplateNameLoc,
3295 WrittenTy.getTypePtr(),
3296 /*FIXME:*/KWLoc);
3297 Friend->setAccess(AS_public);
3298 CurContext->addDecl(Friend);
3299 } else {
3300 // Add the specialization into its lexical context, so that it can
3301 // be seen when iterating through the list of declarations in that
3302 // context. However, specializations are not found by name lookup.
3303 CurContext->addDecl(Specialization);
3304 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003305 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003306}
Douglas Gregord57959a2009-03-27 23:10:48 +00003307
Mike Stump1eb44332009-09-09 15:08:12 +00003308Sema::DeclPtrTy
3309Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003310 MultiTemplateParamsArg TemplateParameterLists,
3311 Declarator &D) {
3312 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3313}
3314
Mike Stump1eb44332009-09-09 15:08:12 +00003315Sema::DeclPtrTy
3316Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003317 MultiTemplateParamsArg TemplateParameterLists,
3318 Declarator &D) {
3319 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3320 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3321 "Not a function declarator!");
3322 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003323
Douglas Gregor52591bf2009-06-24 00:54:41 +00003324 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003325 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003326 }
Mike Stump1eb44332009-09-09 15:08:12 +00003327
Douglas Gregor52591bf2009-06-24 00:54:41 +00003328 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003329
3330 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003331 move(TemplateParameterLists),
3332 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003333 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003334 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003335 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003336 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003337 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3338 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00003339 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00003340}
3341
Douglas Gregor454885e2009-10-15 15:54:05 +00003342/// \brief Diagnose cases where we have an explicit template specialization
3343/// before/after an explicit template instantiation, producing diagnostics
3344/// for those cases where they are required and determining whether the
3345/// new specialization/instantiation will have any effect.
3346///
Douglas Gregor454885e2009-10-15 15:54:05 +00003347/// \param NewLoc the location of the new explicit specialization or
3348/// instantiation.
3349///
3350/// \param NewTSK the kind of the new explicit specialization or instantiation.
3351///
3352/// \param PrevDecl the previous declaration of the entity.
3353///
3354/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3355///
3356/// \param PrevPointOfInstantiation if valid, indicates where the previus
3357/// declaration was instantiated (either implicitly or explicitly).
3358///
3359/// \param SuppressNew will be set to true to indicate that the new
3360/// specialization or instantiation has no effect and should be ignored.
3361///
3362/// \returns true if there was an error that should prevent the introduction of
3363/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00003364bool
3365Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3366 TemplateSpecializationKind NewTSK,
3367 NamedDecl *PrevDecl,
3368 TemplateSpecializationKind PrevTSK,
3369 SourceLocation PrevPointOfInstantiation,
3370 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003371 SuppressNew = false;
3372
3373 switch (NewTSK) {
3374 case TSK_Undeclared:
3375 case TSK_ImplicitInstantiation:
3376 assert(false && "Don't check implicit instantiations here");
3377 return false;
3378
3379 case TSK_ExplicitSpecialization:
3380 switch (PrevTSK) {
3381 case TSK_Undeclared:
3382 case TSK_ExplicitSpecialization:
3383 // Okay, we're just specializing something that is either already
3384 // explicitly specialized or has merely been mentioned without any
3385 // instantiation.
3386 return false;
3387
3388 case TSK_ImplicitInstantiation:
3389 if (PrevPointOfInstantiation.isInvalid()) {
3390 // The declaration itself has not actually been instantiated, so it is
3391 // still okay to specialize it.
3392 return false;
3393 }
3394 // Fall through
3395
3396 case TSK_ExplicitInstantiationDeclaration:
3397 case TSK_ExplicitInstantiationDefinition:
3398 assert((PrevTSK == TSK_ImplicitInstantiation ||
3399 PrevPointOfInstantiation.isValid()) &&
3400 "Explicit instantiation without point of instantiation?");
3401
3402 // C++ [temp.expl.spec]p6:
3403 // If a template, a member template or the member of a class template
3404 // is explicitly specialized then that specialization shall be declared
3405 // before the first use of that specialization that would cause an
3406 // implicit instantiation to take place, in every translation unit in
3407 // which such a use occurs; no diagnostic is required.
Douglas Gregor0d035142009-10-27 18:42:08 +00003408 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00003409 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003410 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00003411 << (PrevTSK != TSK_ImplicitInstantiation);
3412
3413 return true;
3414 }
3415 break;
3416
3417 case TSK_ExplicitInstantiationDeclaration:
3418 switch (PrevTSK) {
3419 case TSK_ExplicitInstantiationDeclaration:
3420 // This explicit instantiation declaration is redundant (that's okay).
3421 SuppressNew = true;
3422 return false;
3423
3424 case TSK_Undeclared:
3425 case TSK_ImplicitInstantiation:
3426 // We're explicitly instantiating something that may have already been
3427 // implicitly instantiated; that's fine.
3428 return false;
3429
3430 case TSK_ExplicitSpecialization:
3431 // C++0x [temp.explicit]p4:
3432 // For a given set of template parameters, if an explicit instantiation
3433 // of a template appears after a declaration of an explicit
3434 // specialization for that template, the explicit instantiation has no
3435 // effect.
3436 return false;
3437
3438 case TSK_ExplicitInstantiationDefinition:
3439 // C++0x [temp.explicit]p10:
3440 // If an entity is the subject of both an explicit instantiation
3441 // declaration and an explicit instantiation definition in the same
3442 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00003443 Diag(NewLoc,
3444 diag::err_explicit_instantiation_declaration_after_definition);
3445 Diag(PrevPointOfInstantiation,
3446 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00003447 assert(PrevPointOfInstantiation.isValid() &&
3448 "Explicit instantiation without point of instantiation?");
3449 SuppressNew = true;
3450 return false;
3451 }
3452 break;
3453
3454 case TSK_ExplicitInstantiationDefinition:
3455 switch (PrevTSK) {
3456 case TSK_Undeclared:
3457 case TSK_ImplicitInstantiation:
3458 // We're explicitly instantiating something that may have already been
3459 // implicitly instantiated; that's fine.
3460 return false;
3461
3462 case TSK_ExplicitSpecialization:
3463 // C++ DR 259, C++0x [temp.explicit]p4:
3464 // For a given set of template parameters, if an explicit
3465 // instantiation of a template appears after a declaration of
3466 // an explicit specialization for that template, the explicit
3467 // instantiation has no effect.
3468 //
3469 // In C++98/03 mode, we only give an extension warning here, because it
3470 // is not not harmful to try to explicitly instantiate something that
3471 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00003472 if (!getLangOptions().CPlusPlus0x) {
3473 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00003474 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003475 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00003476 diag::note_previous_template_specialization);
3477 }
3478 SuppressNew = true;
3479 return false;
3480
3481 case TSK_ExplicitInstantiationDeclaration:
3482 // We're explicity instantiating a definition for something for which we
3483 // were previously asked to suppress instantiations. That's fine.
3484 return false;
3485
3486 case TSK_ExplicitInstantiationDefinition:
3487 // C++0x [temp.spec]p5:
3488 // For a given template and a given set of template-arguments,
3489 // - an explicit instantiation definition shall appear at most once
3490 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00003491 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00003492 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003493 Diag(PrevPointOfInstantiation,
3494 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00003495 SuppressNew = true;
3496 return false;
3497 }
3498 break;
3499 }
3500
3501 assert(false && "Missing specialization/instantiation case?");
3502
3503 return false;
3504}
3505
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003506/// \brief Perform semantic analysis for the given function template
3507/// specialization.
3508///
3509/// This routine performs all of the semantic analysis required for an
3510/// explicit function template specialization. On successful completion,
3511/// the function declaration \p FD will become a function template
3512/// specialization.
3513///
3514/// \param FD the function declaration, which will be updated to become a
3515/// function template specialization.
3516///
3517/// \param HasExplicitTemplateArgs whether any template arguments were
3518/// explicitly provided.
3519///
3520/// \param LAngleLoc the location of the left angle bracket ('<'), if
3521/// template arguments were explicitly provided.
3522///
3523/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3524/// if any.
3525///
3526/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3527/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3528/// true as in, e.g., \c void sort<>(char*, char*);
3529///
3530/// \param RAngleLoc the location of the right angle bracket ('>'), if
3531/// template arguments were explicitly provided.
3532///
3533/// \param PrevDecl the set of declarations that
3534bool
3535Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3536 bool HasExplicitTemplateArgs,
3537 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00003538 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003539 unsigned NumExplicitTemplateArgs,
3540 SourceLocation RAngleLoc,
John McCall68263142009-11-18 22:49:29 +00003541 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003542 // The set of function template specializations that could match this
3543 // explicit function template specialization.
3544 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3545 CandidateSet Candidates;
3546
3547 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00003548 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3549 I != E; ++I) {
3550 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3551 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003552 // Only consider templates found within the same semantic lookup scope as
3553 // FD.
3554 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3555 continue;
3556
3557 // C++ [temp.expl.spec]p11:
3558 // A trailing template-argument can be left unspecified in the
3559 // template-id naming an explicit function template specialization
3560 // provided it can be deduced from the function argument type.
3561 // Perform template argument deduction to determine whether we may be
3562 // specializing this template.
3563 // FIXME: It is somewhat wasteful to build
3564 TemplateDeductionInfo Info(Context);
3565 FunctionDecl *Specialization = 0;
3566 if (TemplateDeductionResult TDK
3567 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3568 ExplicitTemplateArgs,
3569 NumExplicitTemplateArgs,
3570 FD->getType(),
3571 Specialization,
3572 Info)) {
3573 // FIXME: Template argument deduction failed; record why it failed, so
3574 // that we can provide nifty diagnostics.
3575 (void)TDK;
3576 continue;
3577 }
3578
3579 // Record this candidate.
3580 Candidates.push_back(Specialization);
3581 }
3582 }
3583
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003584 // Find the most specialized function template.
3585 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3586 Candidates.size(),
3587 TPOC_Other,
3588 FD->getLocation(),
3589 PartialDiagnostic(diag::err_function_template_spec_no_match)
3590 << FD->getDeclName(),
3591 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3592 << FD->getDeclName() << HasExplicitTemplateArgs,
3593 PartialDiagnostic(diag::note_function_template_spec_matched));
3594 if (!Specialization)
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003595 return true;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003596
3597 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003598 // If so, we have run afoul of .
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003599
Douglas Gregord5cb8762009-10-07 00:13:32 +00003600 // Check the scope of this explicit specialization.
3601 if (CheckTemplateSpecializationScope(*this,
3602 Specialization->getPrimaryTemplate(),
3603 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003604 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003605 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003606
3607 // C++ [temp.expl.spec]p6:
3608 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00003609 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003610 // before the first use of that specialization that would cause an implicit
3611 // instantiation to take place, in every translation unit in which such a
3612 // use occurs; no diagnostic is required.
3613 FunctionTemplateSpecializationInfo *SpecInfo
3614 = Specialization->getTemplateSpecializationInfo();
3615 assert(SpecInfo && "Function template specialization info missing?");
3616 if (SpecInfo->getPointOfInstantiation().isValid()) {
3617 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3618 << FD;
3619 Diag(SpecInfo->getPointOfInstantiation(),
3620 diag::note_instantiation_required_here)
3621 << (Specialization->getTemplateSpecializationKind()
3622 != TSK_ImplicitInstantiation);
3623 return true;
3624 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003625
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003626 // Mark the prior declaration as an explicit specialization, so that later
3627 // clients know that this is an explicit specialization.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003628 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003629
3630 // Turn the given function declaration into a function template
3631 // specialization, with the template arguments from the previous
3632 // specialization.
3633 FD->setFunctionTemplateSpecialization(Context,
3634 Specialization->getPrimaryTemplate(),
3635 new (Context) TemplateArgumentList(
3636 *Specialization->getTemplateSpecializationArgs()),
3637 /*InsertPos=*/0,
3638 TSK_ExplicitSpecialization);
3639
3640 // The "previous declaration" for this function template specialization is
3641 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00003642 Previous.clear();
3643 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003644 return false;
3645}
3646
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003647/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003648/// specialization.
3649///
3650/// This routine performs all of the semantic analysis required for an
3651/// explicit member function specialization. On successful completion,
3652/// the function declaration \p FD will become a member function
3653/// specialization.
3654///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003655/// \param Member the member declaration, which will be updated to become a
3656/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003657///
John McCall68263142009-11-18 22:49:29 +00003658/// \param Previous the set of declarations, one of which may be specialized
3659/// by this function specialization; the set will be modified to contain the
3660/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003661bool
John McCall68263142009-11-18 22:49:29 +00003662Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003663 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3664
3665 // Try to find the member we are instantiating.
3666 NamedDecl *Instantiation = 0;
3667 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003668 MemberSpecializationInfo *MSInfo = 0;
3669
John McCall68263142009-11-18 22:49:29 +00003670 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003671 // Nowhere to look anyway.
3672 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003673 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3674 I != E; ++I) {
3675 NamedDecl *D = (*I)->getUnderlyingDecl();
3676 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003677 if (Context.hasSameType(Function->getType(), Method->getType())) {
3678 Instantiation = Method;
3679 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003680 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003681 break;
3682 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003683 }
3684 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003685 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003686 VarDecl *PrevVar;
3687 if (Previous.isSingleResult() &&
3688 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003689 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00003690 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003691 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003692 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003693 }
3694 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003695 CXXRecordDecl *PrevRecord;
3696 if (Previous.isSingleResult() &&
3697 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3698 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003699 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003700 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003701 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003702 }
3703
3704 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003705 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003706 // specializations are always out-of-line, the caller will complain about
3707 // this mismatch later.
3708 return false;
3709 }
3710
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003711 // Make sure that this is a specialization of a member.
3712 if (!InstantiatedFrom) {
3713 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3714 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003715 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3716 return true;
3717 }
3718
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003719 // C++ [temp.expl.spec]p6:
3720 // If a template, a member template or the member of a class template is
3721 // explicitly specialized then that spe- cialization shall be declared
3722 // before the first use of that specialization that would cause an implicit
3723 // instantiation to take place, in every translation unit in which such a
3724 // use occurs; no diagnostic is required.
3725 assert(MSInfo && "Member specialization info missing?");
3726 if (MSInfo->getPointOfInstantiation().isValid()) {
3727 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3728 << Member;
3729 Diag(MSInfo->getPointOfInstantiation(),
3730 diag::note_instantiation_required_here)
3731 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3732 return true;
3733 }
3734
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003735 // Check the scope of this explicit specialization.
3736 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003737 InstantiatedFrom,
3738 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003739 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003740 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00003741
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003742 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00003743 // the original declaration to note that it is an explicit specialization
3744 // (if it was previously an implicit instantiation). This latter step
3745 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003746 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003747 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3748 if (InstantiationFunction->getTemplateSpecializationKind() ==
3749 TSK_ImplicitInstantiation) {
3750 InstantiationFunction->setTemplateSpecializationKind(
3751 TSK_ExplicitSpecialization);
3752 InstantiationFunction->setLocation(Member->getLocation());
3753 }
3754
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003755 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3756 cast<CXXMethodDecl>(InstantiatedFrom),
3757 TSK_ExplicitSpecialization);
3758 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003759 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3760 if (InstantiationVar->getTemplateSpecializationKind() ==
3761 TSK_ImplicitInstantiation) {
3762 InstantiationVar->setTemplateSpecializationKind(
3763 TSK_ExplicitSpecialization);
3764 InstantiationVar->setLocation(Member->getLocation());
3765 }
3766
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003767 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3768 cast<VarDecl>(InstantiatedFrom),
3769 TSK_ExplicitSpecialization);
3770 } else {
3771 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00003772 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3773 if (InstantiationClass->getTemplateSpecializationKind() ==
3774 TSK_ImplicitInstantiation) {
3775 InstantiationClass->setTemplateSpecializationKind(
3776 TSK_ExplicitSpecialization);
3777 InstantiationClass->setLocation(Member->getLocation());
3778 }
3779
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003780 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00003781 cast<CXXRecordDecl>(InstantiatedFrom),
3782 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003783 }
3784
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003785 // Save the caller the trouble of having to figure out which declaration
3786 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00003787 Previous.clear();
3788 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003789 return false;
3790}
3791
Douglas Gregor558c0322009-10-14 23:41:34 +00003792/// \brief Check the scope of an explicit instantiation.
3793static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3794 SourceLocation InstLoc,
3795 bool WasQualifiedName) {
3796 DeclContext *ExpectedContext
3797 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3798 DeclContext *CurContext = S.CurContext->getLookupContext();
3799
3800 // C++0x [temp.explicit]p2:
3801 // An explicit instantiation shall appear in an enclosing namespace of its
3802 // template.
3803 //
3804 // This is DR275, which we do not retroactively apply to C++98/03.
3805 if (S.getLangOptions().CPlusPlus0x &&
3806 !CurContext->Encloses(ExpectedContext)) {
3807 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3808 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3809 << D << NS;
3810 else
3811 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3812 << D;
3813 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3814 return;
3815 }
3816
3817 // C++0x [temp.explicit]p2:
3818 // If the name declared in the explicit instantiation is an unqualified
3819 // name, the explicit instantiation shall appear in the namespace where
3820 // its template is declared or, if that namespace is inline (7.3.1), any
3821 // namespace from its enclosing namespace set.
3822 if (WasQualifiedName)
3823 return;
3824
3825 if (CurContext->Equals(ExpectedContext))
3826 return;
3827
3828 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3829 << D << ExpectedContext;
3830 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3831}
3832
3833/// \brief Determine whether the given scope specifier has a template-id in it.
3834static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3835 if (!SS.isSet())
3836 return false;
3837
3838 // C++0x [temp.explicit]p2:
3839 // If the explicit instantiation is for a member function, a member class
3840 // or a static data member of a class template specialization, the name of
3841 // the class template specialization in the qualified-id for the member
3842 // name shall be a simple-template-id.
3843 //
3844 // C++98 has the same restriction, just worded differently.
3845 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3846 NNS; NNS = NNS->getPrefix())
3847 if (Type *T = NNS->getAsType())
3848 if (isa<TemplateSpecializationType>(T))
3849 return true;
3850
3851 return false;
3852}
3853
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003854// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00003855// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003856Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00003857Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00003858 SourceLocation ExternLoc,
3859 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003860 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003861 SourceLocation KWLoc,
3862 const CXXScopeSpec &SS,
3863 TemplateTy TemplateD,
3864 SourceLocation TemplateNameLoc,
3865 SourceLocation LAngleLoc,
3866 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003867 SourceLocation RAngleLoc,
3868 AttributeList *Attr) {
3869 // Find the class template we're specializing
3870 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003871 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003872 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3873
3874 // Check that the specialization uses the same tag kind as the
3875 // original template.
3876 TagDecl::TagKind Kind;
3877 switch (TagSpec) {
3878 default: assert(0 && "Unknown tag type!");
3879 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3880 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3881 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3882 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003883 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003884 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003885 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003886 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003887 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003888 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003889 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003890 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003891 diag::note_previous_use);
3892 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3893 }
3894
Douglas Gregor558c0322009-10-14 23:41:34 +00003895 // C++0x [temp.explicit]p2:
3896 // There are two forms of explicit instantiation: an explicit instantiation
3897 // definition and an explicit instantiation declaration. An explicit
3898 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00003899 TemplateSpecializationKind TSK
3900 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3901 : TSK_ExplicitInstantiationDeclaration;
3902
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003903 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00003904 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor314b97f2009-11-10 19:49:08 +00003905 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003906
3907 // Check that the template argument list is well-formed for this
3908 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003909 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3910 TemplateArgs.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003911 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00003912 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00003913 RAngleLoc, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003914 return true;
3915
Mike Stump1eb44332009-09-09 15:08:12 +00003916 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003917 ClassTemplate->getTemplateParameters()->size()) &&
3918 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003919
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003920 // Find the class template specialization declaration that
3921 // corresponds to these arguments.
3922 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00003923 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003924 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003925 Converted.flatSize(),
3926 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003927 void *InsertPos = 0;
3928 ClassTemplateSpecializationDecl *PrevDecl
3929 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3930
Douglas Gregord5cb8762009-10-07 00:13:32 +00003931 // C++0x [temp.explicit]p2:
3932 // [...] An explicit instantiation shall appear in an enclosing
3933 // namespace of its template. [...]
3934 //
3935 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00003936 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
3937 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00003938
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003939 ClassTemplateSpecializationDecl *Specialization = 0;
3940
3941 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003942 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00003943 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003944 PrevDecl,
3945 PrevDecl->getSpecializationKind(),
3946 PrevDecl->getPointOfInstantiation(),
3947 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003948 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003949
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003950 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00003951 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003952
Douglas Gregor52604ab2009-09-11 21:19:12 +00003953 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3954 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3955 // Since the only prior class template specialization with these
3956 // arguments was referenced but not declared, reuse that
3957 // declaration node as our own, updating its source location to
3958 // reflect our new declaration.
3959 Specialization = PrevDecl;
3960 Specialization->setLocation(TemplateNameLoc);
3961 PrevDecl = 0;
3962 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003963 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00003964
3965 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003966 // Create a new class template specialization declaration node for
3967 // this explicit specialization.
3968 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003969 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003970 ClassTemplate->getDeclContext(),
3971 TemplateNameLoc,
3972 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00003973 Converted, PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003974
Douglas Gregor52604ab2009-09-11 21:19:12 +00003975 if (PrevDecl) {
3976 // Remove the previous declaration from the folding set, since we want
3977 // to introduce a new declaration.
3978 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3979 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3980 }
3981
3982 // Insert the new specialization.
3983 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003984 }
3985
3986 // Build the fully-sugared type for this explicit instantiation as
3987 // the user wrote in the explicit instantiation itself. This means
3988 // that we'll pretty-print the type retrieved from the
3989 // specialization's declaration the way that the user actually wrote
3990 // the explicit instantiation, rather than formatting the name based
3991 // on the "canonical" representation used to store the template
3992 // arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003993 QualType WrittenTy
3994 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00003995 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003996 TemplateArgs.size(),
3997 Context.getTypeDeclType(Specialization));
3998 Specialization->setTypeAsWritten(WrittenTy);
3999 TemplateArgsIn.release();
4000
4001 // Add the explicit instantiation into its lexical context. However,
4002 // since explicit instantiations are never found by name lookup, we
4003 // just put it into the declaration context directly.
4004 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004005 CurContext->addDecl(Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004006
4007 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004008 // A definition of a class template or class member template
4009 // shall be in scope at the point of the explicit instantiation of
4010 // the class template or class member template.
4011 //
4012 // This check comes when we actually try to perform the
4013 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004014 ClassTemplateSpecializationDecl *Def
4015 = cast_or_null<ClassTemplateSpecializationDecl>(
4016 Specialization->getDefinition(Context));
4017 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004018 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor0d035142009-10-27 18:42:08 +00004019
4020 // Instantiate the members of this class template specialization.
4021 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4022 Specialization->getDefinition(Context));
4023 if (Def)
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004024 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004025
4026 return DeclPtrTy::make(Specialization);
4027}
4028
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004029// Explicit instantiation of a member class of a class template.
4030Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004031Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004032 SourceLocation ExternLoc,
4033 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004034 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004035 SourceLocation KWLoc,
4036 const CXXScopeSpec &SS,
4037 IdentifierInfo *Name,
4038 SourceLocation NameLoc,
4039 AttributeList *Attr) {
4040
Douglas Gregor402abb52009-05-28 23:31:59 +00004041 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004042 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004043 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004044 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004045 MultiTemplateParamsArg(*this, 0, 0),
4046 Owned, IsDependent);
4047 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4048
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004049 if (!TagD)
4050 return true;
4051
4052 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4053 if (Tag->isEnum()) {
4054 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4055 << Context.getTypeDeclType(Tag);
4056 return true;
4057 }
4058
Douglas Gregord0c87372009-05-27 17:30:49 +00004059 if (Tag->isInvalidDecl())
4060 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004061
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004062 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4063 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4064 if (!Pattern) {
4065 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4066 << Context.getTypeDeclType(Record);
4067 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4068 return true;
4069 }
4070
Douglas Gregor558c0322009-10-14 23:41:34 +00004071 // C++0x [temp.explicit]p2:
4072 // If the explicit instantiation is for a class or member class, the
4073 // elaborated-type-specifier in the declaration shall include a
4074 // simple-template-id.
4075 //
4076 // C++98 has the same restriction, just worded differently.
4077 if (!ScopeSpecifierHasTemplateId(SS))
4078 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4079 << Record << SS.getRange();
4080
4081 // C++0x [temp.explicit]p2:
4082 // There are two forms of explicit instantiation: an explicit instantiation
4083 // definition and an explicit instantiation declaration. An explicit
4084 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004085 TemplateSpecializationKind TSK
4086 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4087 : TSK_ExplicitInstantiationDeclaration;
4088
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004089 // C++0x [temp.explicit]p2:
4090 // [...] An explicit instantiation shall appear in an enclosing
4091 // namespace of its template. [...]
4092 //
4093 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004094 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004095
4096 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004097 CXXRecordDecl *PrevDecl
4098 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4099 if (!PrevDecl && Record->getDefinition(Context))
4100 PrevDecl = Record;
4101 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004102 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4103 bool SuppressNew = false;
4104 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004105 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004106 PrevDecl,
4107 MSInfo->getTemplateSpecializationKind(),
4108 MSInfo->getPointOfInstantiation(),
4109 SuppressNew))
4110 return true;
4111 if (SuppressNew)
4112 return TagD;
4113 }
4114
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004115 CXXRecordDecl *RecordDef
4116 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4117 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004118 // C++ [temp.explicit]p3:
4119 // A definition of a member class of a class template shall be in scope
4120 // at the point of an explicit instantiation of the member class.
4121 CXXRecordDecl *Def
4122 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4123 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004124 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4125 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004126 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4127 << Pattern;
4128 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004129 } else {
4130 if (InstantiateClass(NameLoc, Record, Def,
4131 getTemplateInstantiationArgs(Record),
4132 TSK))
4133 return true;
4134
4135 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4136 if (!RecordDef)
4137 return true;
4138 }
4139 }
4140
4141 // Instantiate all of the members of the class.
4142 InstantiateClassMembers(NameLoc, RecordDef,
4143 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004144
Mike Stump390b4cc2009-05-16 07:39:55 +00004145 // FIXME: We don't have any representation for explicit instantiations of
4146 // member classes. Such a representation is not needed for compilation, but it
4147 // should be available for clients that want to see all of the declarations in
4148 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004149 return TagD;
4150}
4151
Douglas Gregord5a423b2009-09-25 18:43:00 +00004152Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4153 SourceLocation ExternLoc,
4154 SourceLocation TemplateLoc,
4155 Declarator &D) {
4156 // Explicit instantiations always require a name.
4157 DeclarationName Name = GetNameForDeclarator(D);
4158 if (!Name) {
4159 if (!D.isInvalidType())
4160 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4161 diag::err_explicit_instantiation_requires_name)
4162 << D.getDeclSpec().getSourceRange()
4163 << D.getSourceRange();
4164
4165 return true;
4166 }
4167
4168 // The scope passed in may not be a decl scope. Zip up the scope tree until
4169 // we find one that is.
4170 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4171 (S->getFlags() & Scope::TemplateParamScope) != 0)
4172 S = S->getParent();
4173
4174 // Determine the type of the declaration.
4175 QualType R = GetTypeForDeclarator(D, S, 0);
4176 if (R.isNull())
4177 return true;
4178
4179 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4180 // Cannot explicitly instantiate a typedef.
4181 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4182 << Name;
4183 return true;
4184 }
4185
Douglas Gregor663b5a02009-10-14 20:14:33 +00004186 // C++0x [temp.explicit]p1:
4187 // [...] An explicit instantiation of a function template shall not use the
4188 // inline or constexpr specifiers.
4189 // Presumably, this also applies to member functions of class templates as
4190 // well.
4191 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4192 Diag(D.getDeclSpec().getInlineSpecLoc(),
4193 diag::err_explicit_instantiation_inline)
4194 << CodeModificationHint::CreateRemoval(
4195 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
4196
4197 // FIXME: check for constexpr specifier.
4198
Douglas Gregor558c0322009-10-14 23:41:34 +00004199 // C++0x [temp.explicit]p2:
4200 // There are two forms of explicit instantiation: an explicit instantiation
4201 // definition and an explicit instantiation declaration. An explicit
4202 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004203 TemplateSpecializationKind TSK
4204 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4205 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004206
John McCalla24dc2e2009-11-17 02:14:36 +00004207 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4208 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004209
4210 if (!R->isFunctionType()) {
4211 // C++ [temp.explicit]p1:
4212 // A [...] static data member of a class template can be explicitly
4213 // instantiated from the member definition associated with its class
4214 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00004215 if (Previous.isAmbiguous())
4216 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004217
John McCallf36e02d2009-10-09 21:13:30 +00004218 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4219 Previous.getAsSingleDecl(Context));
Douglas Gregord5a423b2009-09-25 18:43:00 +00004220 if (!Prev || !Prev->isStaticDataMember()) {
4221 // We expect to see a data data member here.
4222 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4223 << Name;
4224 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4225 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004226 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004227 return true;
4228 }
4229
4230 if (!Prev->getInstantiatedFromStaticDataMember()) {
4231 // FIXME: Check for explicit specialization?
4232 Diag(D.getIdentifierLoc(),
4233 diag::err_explicit_instantiation_data_member_not_instantiated)
4234 << Prev;
4235 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4236 // FIXME: Can we provide a note showing where this was declared?
4237 return true;
4238 }
4239
Douglas Gregor558c0322009-10-14 23:41:34 +00004240 // C++0x [temp.explicit]p2:
4241 // If the explicit instantiation is for a member function, a member class
4242 // or a static data member of a class template specialization, the name of
4243 // the class template specialization in the qualified-id for the member
4244 // name shall be a simple-template-id.
4245 //
4246 // C++98 has the same restriction, just worded differently.
4247 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4248 Diag(D.getIdentifierLoc(),
4249 diag::err_explicit_instantiation_without_qualified_id)
4250 << Prev << D.getCXXScopeSpec().getRange();
4251
4252 // Check the scope of this explicit instantiation.
4253 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4254
Douglas Gregor454885e2009-10-15 15:54:05 +00004255 // Verify that it is okay to explicitly instantiate here.
4256 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4257 assert(MSInfo && "Missing static data member specialization info?");
4258 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004259 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00004260 MSInfo->getTemplateSpecializationKind(),
4261 MSInfo->getPointOfInstantiation(),
4262 SuppressNew))
4263 return true;
4264 if (SuppressNew)
4265 return DeclPtrTy();
4266
Douglas Gregord5a423b2009-09-25 18:43:00 +00004267 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004268 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004269 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004270 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4271 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004272
4273 // FIXME: Create an ExplicitInstantiation node?
4274 return DeclPtrTy();
4275 }
4276
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004277 // If the declarator is a template-id, translate the parser's template
4278 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00004279 bool HasExplicitTemplateArgs = false;
John McCall833ca992009-10-29 08:12:44 +00004280 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004281 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4282 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Douglas Gregordb422df2009-09-25 21:45:23 +00004283 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4284 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00004285 TemplateId->NumArgs);
4286 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregordb422df2009-09-25 21:45:23 +00004287 TemplateArgs);
4288 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00004289 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00004290 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004291
Douglas Gregord5a423b2009-09-25 18:43:00 +00004292 // C++ [temp.explicit]p1:
4293 // A [...] function [...] can be explicitly instantiated from its template.
4294 // A member function [...] of a class template can be explicitly
4295 // instantiated from the member definition associated with its class
4296 // template.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004297 llvm::SmallVector<FunctionDecl *, 8> Matches;
4298 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4299 P != PEnd; ++P) {
4300 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00004301 if (!HasExplicitTemplateArgs) {
4302 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4303 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4304 Matches.clear();
4305 Matches.push_back(Method);
4306 break;
4307 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00004308 }
4309 }
4310
4311 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4312 if (!FunTmpl)
4313 continue;
4314
4315 TemplateDeductionInfo Info(Context);
4316 FunctionDecl *Specialization = 0;
4317 if (TemplateDeductionResult TDK
Douglas Gregordb422df2009-09-25 21:45:23 +00004318 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
4319 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004320 R, Specialization, Info)) {
4321 // FIXME: Keep track of almost-matches?
4322 (void)TDK;
4323 continue;
4324 }
4325
4326 Matches.push_back(Specialization);
4327 }
4328
4329 // Find the most specialized function template specialization.
4330 FunctionDecl *Specialization
4331 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4332 D.getIdentifierLoc(),
4333 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4334 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4335 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4336
4337 if (!Specialization)
4338 return true;
4339
Douglas Gregor0a897e32009-10-15 17:21:20 +00004340 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00004341 Diag(D.getIdentifierLoc(),
4342 diag::err_explicit_instantiation_member_function_not_instantiated)
4343 << Specialization
4344 << (Specialization->getTemplateSpecializationKind() ==
4345 TSK_ExplicitSpecialization);
4346 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4347 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00004348 }
Douglas Gregor558c0322009-10-14 23:41:34 +00004349
Douglas Gregor0a897e32009-10-15 17:21:20 +00004350 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00004351 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4352 PrevDecl = Specialization;
4353
Douglas Gregor0a897e32009-10-15 17:21:20 +00004354 if (PrevDecl) {
4355 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004356 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00004357 PrevDecl,
4358 PrevDecl->getTemplateSpecializationKind(),
4359 PrevDecl->getPointOfInstantiation(),
4360 SuppressNew))
4361 return true;
4362
4363 // FIXME: We may still want to build some representation of this
4364 // explicit specialization.
4365 if (SuppressNew)
4366 return DeclPtrTy();
4367 }
4368
4369 if (TSK == TSK_ExplicitInstantiationDefinition)
4370 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4371 false, /*DefinitionRequired=*/true);
4372
4373 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4374
Douglas Gregor558c0322009-10-14 23:41:34 +00004375 // C++0x [temp.explicit]p2:
4376 // If the explicit instantiation is for a member function, a member class
4377 // or a static data member of a class template specialization, the name of
4378 // the class template specialization in the qualified-id for the member
4379 // name shall be a simple-template-id.
4380 //
4381 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004382 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004383 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00004384 D.getCXXScopeSpec().isSet() &&
4385 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4386 Diag(D.getIdentifierLoc(),
4387 diag::err_explicit_instantiation_without_qualified_id)
4388 << Specialization << D.getCXXScopeSpec().getRange();
4389
4390 CheckExplicitInstantiationScope(*this,
4391 FunTmpl? (NamedDecl *)FunTmpl
4392 : Specialization->getInstantiatedFromMemberFunction(),
4393 D.getIdentifierLoc(),
4394 D.getCXXScopeSpec().isSet());
4395
Douglas Gregord5a423b2009-09-25 18:43:00 +00004396 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4397 return DeclPtrTy();
4398}
4399
Douglas Gregord57959a2009-03-27 23:10:48 +00004400Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00004401Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4402 const CXXScopeSpec &SS, IdentifierInfo *Name,
4403 SourceLocation TagLoc, SourceLocation NameLoc) {
4404 // This has to hold, because SS is expected to be defined.
4405 assert(Name && "Expected a name in a dependent tag");
4406
4407 NestedNameSpecifier *NNS
4408 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4409 if (!NNS)
4410 return true;
4411
4412 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4413 if (T.isNull())
4414 return true;
4415
4416 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4417 QualType ElabType = Context.getElaboratedType(T, TagKind);
4418
4419 return ElabType.getAsOpaquePtr();
4420}
4421
4422Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00004423Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4424 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004425 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00004426 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4427 if (!NNS)
4428 return true;
4429
4430 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00004431 if (T.isNull())
4432 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00004433 return T.getAsOpaquePtr();
4434}
4435
Douglas Gregor17343172009-04-01 00:28:59 +00004436Sema::TypeResult
4437Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4438 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00004439 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004440 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00004441 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00004442 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00004443 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00004444 assert(TemplateId && "Expected a template specialization type");
4445
Douglas Gregor6946baf2009-09-02 13:05:45 +00004446 if (computeDeclContext(SS, false)) {
4447 // If we can compute a declaration context, then the "typename"
4448 // keyword was superfluous. Just build a QualifiedNameType to keep
4449 // track of the nested-name-specifier.
Mike Stump1eb44332009-09-09 15:08:12 +00004450
Douglas Gregor6946baf2009-09-02 13:05:45 +00004451 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4452 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4453 }
Mike Stump1eb44332009-09-09 15:08:12 +00004454
Douglas Gregor6946baf2009-09-02 13:05:45 +00004455 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00004456}
4457
Douglas Gregord57959a2009-03-27 23:10:48 +00004458/// \brief Build the type that describes a C++ typename specifier,
4459/// e.g., "typename T::type".
4460QualType
4461Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4462 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00004463 CXXRecordDecl *CurrentInstantiation = 0;
4464 if (NNS->isDependent()) {
4465 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00004466
Douglas Gregor42af25f2009-05-11 19:58:34 +00004467 // If the nested-name-specifier does not refer to the current
4468 // instantiation, then build a typename type.
4469 if (!CurrentInstantiation)
4470 return Context.getTypenameType(NNS, &II);
Mike Stump1eb44332009-09-09 15:08:12 +00004471
Douglas Gregorde18d122009-09-02 13:12:51 +00004472 // The nested-name-specifier refers to the current instantiation, so the
4473 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump1eb44332009-09-09 15:08:12 +00004474 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorde18d122009-09-02 13:12:51 +00004475 // extraneous "typename" keywords, and we retroactively apply this DR to
4476 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00004477 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004478
Douglas Gregor42af25f2009-05-11 19:58:34 +00004479 DeclContext *Ctx = 0;
4480
4481 if (CurrentInstantiation)
4482 Ctx = CurrentInstantiation;
4483 else {
4484 CXXScopeSpec SS;
4485 SS.setScopeRep(NNS);
4486 SS.setRange(Range);
4487 if (RequireCompleteDeclContext(SS))
4488 return QualType();
4489
4490 Ctx = computeDeclContext(SS);
4491 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004492 assert(Ctx && "No declaration context?");
4493
4494 DeclarationName Name(&II);
John McCalla24dc2e2009-11-17 02:14:36 +00004495 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4496 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00004497 unsigned DiagID = 0;
4498 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00004499 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004500 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00004501 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00004502 break;
4503
4504 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00004505 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004506 // We found a type. Build a QualifiedNameType, since the
4507 // typename-specifier was just sugar. FIXME: Tell
4508 // QualifiedNameType that it has a "typename" prefix.
4509 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4510 }
4511
4512 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00004513 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00004514 break;
4515
John McCall7ba107a2009-11-18 02:36:19 +00004516 case LookupResult::FoundUnresolvedValue:
4517 llvm::llvm_unreachable("unresolved using decl in non-dependent context");
4518 return QualType();
4519
Douglas Gregord57959a2009-03-27 23:10:48 +00004520 case LookupResult::FoundOverloaded:
4521 DiagID = diag::err_typename_nested_not_type;
4522 Referenced = *Result.begin();
4523 break;
4524
John McCall6e247262009-10-10 05:48:19 +00004525 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00004526 return QualType();
4527 }
4528
4529 // If we get here, it's because name lookup did not find a
4530 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor3f093272009-10-13 21:16:44 +00004531 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00004532 if (Referenced)
4533 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4534 << Name;
4535 return QualType();
4536}
Douglas Gregor4a959d82009-08-06 16:20:37 +00004537
4538namespace {
4539 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump1eb44332009-09-09 15:08:12 +00004540 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4541 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00004542 SourceLocation Loc;
4543 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00004544
Douglas Gregor4a959d82009-08-06 16:20:37 +00004545 public:
Mike Stump1eb44332009-09-09 15:08:12 +00004546 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00004547 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004548 DeclarationName Entity)
4549 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00004550 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00004551
4552 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00004553 /// transformed.
4554 ///
4555 /// For the purposes of type reconstruction, a type has already been
4556 /// transformed if it is NULL or if it is not dependent.
4557 bool AlreadyTransformed(QualType T) {
4558 return T.isNull() || !T->isDependentType();
4559 }
Mike Stump1eb44332009-09-09 15:08:12 +00004560
4561 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00004562 /// rebuilt.
4563 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00004564
Douglas Gregor4a959d82009-08-06 16:20:37 +00004565 /// \brief Returns the name of the entity whose type is being rebuilt.
4566 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00004567
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004568 /// \brief Sets the "base" location and entity when that
4569 /// information is known based on another transformation.
4570 void setBase(SourceLocation Loc, DeclarationName Entity) {
4571 this->Loc = Loc;
4572 this->Entity = Entity;
4573 }
4574
Douglas Gregor4a959d82009-08-06 16:20:37 +00004575 /// \brief Transforms an expression by returning the expression itself
4576 /// (an identity function).
4577 ///
4578 /// FIXME: This is completely unsafe; we will need to actually clone the
4579 /// expressions.
4580 Sema::OwningExprResult TransformExpr(Expr *E) {
4581 return getSema().Owned(E);
4582 }
Mike Stump1eb44332009-09-09 15:08:12 +00004583
Douglas Gregor4a959d82009-08-06 16:20:37 +00004584 /// \brief Transforms a typename type by determining whether the type now
4585 /// refers to a member of the current instantiation, and then
4586 /// type-checking and building a QualifiedNameType (when possible).
John McCalla2becad2009-10-21 00:40:46 +00004587 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor4a959d82009-08-06 16:20:37 +00004588 };
4589}
4590
Mike Stump1eb44332009-09-09 15:08:12 +00004591QualType
John McCalla2becad2009-10-21 00:40:46 +00004592CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4593 TypenameTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00004594 TypenameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00004595
Douglas Gregor4a959d82009-08-06 16:20:37 +00004596 NestedNameSpecifier *NNS
4597 = TransformNestedNameSpecifier(T->getQualifier(),
4598 /*FIXME:*/SourceRange(getBaseLocation()));
4599 if (!NNS)
4600 return QualType();
4601
4602 // If the nested-name-specifier did not change, and we cannot compute the
4603 // context corresponding to the nested-name-specifier, then this
4604 // typename type will not change; exit early.
4605 CXXScopeSpec SS;
4606 SS.setRange(SourceRange(getBaseLocation()));
4607 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00004608
4609 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004610 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00004611 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004612
4613 // Rebuild the typename type, which will probably turn into a
Douglas Gregor4a959d82009-08-06 16:20:37 +00004614 // QualifiedNameType.
John McCall833ca992009-10-29 08:12:44 +00004615 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004616 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00004617 = TransformType(QualType(TemplateId, 0));
4618 if (NewTemplateId.isNull())
4619 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004620
Douglas Gregor4a959d82009-08-06 16:20:37 +00004621 if (NNS == T->getQualifier() &&
4622 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00004623 Result = QualType(T, 0);
4624 else
4625 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4626 } else
4627 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4628 SourceRange(TL.getNameLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +00004629
John McCall833ca992009-10-29 08:12:44 +00004630 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4631 NewTL.setNameLoc(TL.getNameLoc());
4632 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004633}
4634
4635/// \brief Rebuilds a type within the context of the current instantiation.
4636///
Mike Stump1eb44332009-09-09 15:08:12 +00004637/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00004638/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00004639/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00004640/// partial specialization thereof). This routine will rebuild that type now
4641/// that we have entered the declarator's scope, which may produce different
4642/// canonical types, e.g.,
4643///
4644/// \code
4645/// template<typename T>
4646/// struct X {
4647/// typedef T* pointer;
4648/// pointer data();
4649/// };
4650///
4651/// template<typename T>
4652/// typename X<T>::pointer X<T>::data() { ... }
4653/// \endcode
4654///
4655/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4656/// since we do not know that we can look into X<T> when we parsed the type.
4657/// This function will rebuild the type, performing the lookup of "pointer"
4658/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4659/// as the canonical type of T*, allowing the return types of the out-of-line
4660/// definition and the declaration to match.
4661QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4662 DeclarationName Name) {
4663 if (T.isNull() || !T->isDependentType())
4664 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Douglas Gregor4a959d82009-08-06 16:20:37 +00004666 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4667 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00004668}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004669
4670/// \brief Produces a formatted string that describes the binding of
4671/// template parameters to template arguments.
4672std::string
4673Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4674 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004675 // FIXME: For variadic templates, we'll need to get the structured list.
4676 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4677 Args.flat_size());
4678}
4679
4680std::string
4681Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4682 const TemplateArgument *Args,
4683 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004684 std::string Result;
4685
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004686 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004687 return Result;
4688
4689 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004690 if (I >= NumArgs)
4691 break;
4692
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004693 if (I == 0)
4694 Result += "[with ";
4695 else
4696 Result += ", ";
4697
4698 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4699 Result += Id->getName();
4700 } else {
4701 Result += '$';
4702 Result += llvm::utostr(I);
4703 }
4704
4705 Result += " = ";
4706
4707 switch (Args[I].getKind()) {
4708 case TemplateArgument::Null:
4709 Result += "<no value>";
4710 break;
4711
4712 case TemplateArgument::Type: {
4713 std::string TypeStr;
4714 Args[I].getAsType().getAsStringInternal(TypeStr,
4715 Context.PrintingPolicy);
4716 Result += TypeStr;
4717 break;
4718 }
4719
4720 case TemplateArgument::Declaration: {
4721 bool Unnamed = true;
4722 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4723 if (ND->getDeclName()) {
4724 Unnamed = false;
4725 Result += ND->getNameAsString();
4726 }
4727 }
4728
4729 if (Unnamed) {
4730 Result += "<anonymous>";
4731 }
4732 break;
4733 }
4734
Douglas Gregor788cd062009-11-11 01:00:40 +00004735 case TemplateArgument::Template: {
4736 std::string Str;
4737 llvm::raw_string_ostream OS(Str);
4738 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4739 Result += OS.str();
4740 break;
4741 }
4742
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004743 case TemplateArgument::Integral: {
4744 Result += Args[I].getAsIntegral()->toString(10);
4745 break;
4746 }
4747
4748 case TemplateArgument::Expression: {
4749 assert(false && "No expressions in deduced template arguments!");
4750 Result += "<expression>";
4751 break;
4752 }
4753
4754 case TemplateArgument::Pack:
4755 // FIXME: Format template argument packs
4756 Result += "<template argument pack>";
4757 break;
4758 }
4759 }
4760
4761 Result += ']';
4762 return Result;
4763}