blob: 07d7839455f0b646e0dd0076a185f25e70ba0b23 [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000019#include "clang/Parse/Template.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000020#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000021#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000022#include "llvm/Support/Compiler.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000023#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000024using namespace clang;
25
Douglas Gregor2dd078a2009-09-02 22:59:36 +000026/// \brief Determine whether the declaration found is acceptable as the name
27/// of a template and, if so, return that template declaration. Otherwise,
28/// returns NULL.
29static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
30 if (!D)
31 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000032
Douglas Gregor2dd078a2009-09-02 22:59:36 +000033 if (isa<TemplateDecl>(D))
34 return D;
Mike Stump1eb44332009-09-09 15:08:12 +000035
Douglas Gregor2dd078a2009-09-02 22:59:36 +000036 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
37 // C++ [temp.local]p1:
38 // Like normal (non-template) classes, class templates have an
39 // injected-class-name (Clause 9). The injected-class-name
40 // can be used with or without a template-argument-list. When
41 // it is used without a template-argument-list, it is
42 // equivalent to the injected-class-name followed by the
43 // template-parameters of the class template enclosed in
44 // <>. When it is used with a template-argument-list, it
45 // refers to the specified class template specialization,
46 // which could be the current specialization or another
47 // specialization.
48 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000049 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000050 if (Record->getDescribedClassTemplate())
51 return Record->getDescribedClassTemplate();
52
53 if (ClassTemplateSpecializationDecl *Spec
54 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
55 return Spec->getSpecializedTemplate();
56 }
Mike Stump1eb44332009-09-09 15:08:12 +000057
Douglas Gregor2dd078a2009-09-02 22:59:36 +000058 return 0;
59 }
Mike Stump1eb44332009-09-09 15:08:12 +000060
Douglas Gregor2dd078a2009-09-02 22:59:36 +000061 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
62 if (!Ovl)
63 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000064
Douglas Gregor2dd078a2009-09-02 22:59:36 +000065 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
66 FEnd = Ovl->function_end();
67 F != FEnd; ++F) {
68 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
69 // We've found a function template. Determine whether there are
70 // any other function templates we need to bundle together in an
71 // OverloadedFunctionDecl
72 for (++F; F != FEnd; ++F) {
73 if (isa<FunctionTemplateDecl>(*F))
74 break;
75 }
Mike Stump1eb44332009-09-09 15:08:12 +000076
Douglas Gregor2dd078a2009-09-02 22:59:36 +000077 if (F != FEnd) {
78 // Build an overloaded function decl containing only the
79 // function templates in Ovl.
Mike Stump1eb44332009-09-09 15:08:12 +000080 OverloadedFunctionDecl *OvlTemplate
Douglas Gregor2dd078a2009-09-02 22:59:36 +000081 = OverloadedFunctionDecl::Create(Context,
82 Ovl->getDeclContext(),
83 Ovl->getDeclName());
84 OvlTemplate->addOverload(FuncTmpl);
85 OvlTemplate->addOverload(*F);
86 for (++F; F != FEnd; ++F) {
87 if (isa<FunctionTemplateDecl>(*F))
88 OvlTemplate->addOverload(*F);
89 }
Mike Stump1eb44332009-09-09 15:08:12 +000090
Douglas Gregor2dd078a2009-09-02 22:59:36 +000091 return OvlTemplate;
92 }
93
94 return FuncTmpl;
95 }
96 }
Mike Stump1eb44332009-09-09 15:08:12 +000097
Douglas Gregor2dd078a2009-09-02 22:59:36 +000098 return 0;
99}
100
101TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000102 const CXXScopeSpec &SS,
103 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000104 TypeTy *ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000105 bool EnteringContext,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000106 TemplateTy &TemplateResult) {
Douglas Gregor014e88d2009-11-03 23:16:33 +0000107 DeclarationName TName;
108
109 switch (Name.getKind()) {
110 case UnqualifiedId::IK_Identifier:
111 TName = DeclarationName(Name.Identifier);
112 break;
113
114 case UnqualifiedId::IK_OperatorFunctionId:
115 TName = Context.DeclarationNames.getCXXOperatorName(
116 Name.OperatorFunctionId.Operator);
117 break;
118
119 default:
120 return TNK_Non_template;
121 }
122
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000123 // Determine where to perform name lookup
124 DeclContext *LookupCtx = 0;
125 bool isDependent = false;
126 if (ObjectTypePtr) {
127 // This nested-name-specifier occurs in a member access expression, e.g.,
128 // x->B::f, and we are looking into the type of the object.
Douglas Gregor014e88d2009-11-03 23:16:33 +0000129 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000130 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
131 LookupCtx = computeDeclContext(ObjectType);
132 isDependent = ObjectType->isDependentType();
Douglas Gregor014e88d2009-11-03 23:16:33 +0000133 } else if (SS.isSet()) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000134 // This nested-name-specifier occurs after another nested-name-specifier,
135 // so long into the context associated with the prior nested-name-specifier.
136
Douglas Gregor014e88d2009-11-03 23:16:33 +0000137 LookupCtx = computeDeclContext(SS, EnteringContext);
138 isDependent = isDependentScopeSpecifier(SS);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000139 }
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000141 LookupResult Found;
142 bool ObjectTypeSearchedInScope = false;
143 if (LookupCtx) {
144 // Perform "qualified" name lookup into the declaration context we
145 // computed, which is either the type of the base of a member access
Mike Stump1eb44332009-09-09 15:08:12 +0000146 // expression or the declaration context associated with a prior
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000147 // nested-name-specifier.
148
149 // The declaration context must be complete.
Douglas Gregor014e88d2009-11-03 23:16:33 +0000150 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(SS))
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000151 return TNK_Non_template;
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Douglas Gregor014e88d2009-11-03 23:16:33 +0000153 LookupQualifiedName(Found, LookupCtx, TName, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000155 if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
156 // C++ [basic.lookup.classref]p1:
157 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump1eb44332009-09-09 15:08:12 +0000158 // immediately followed by an identifier followed by a <, the
159 // identifier must be looked up to determine whether the < is the
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000160 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump1eb44332009-09-09 15:08:12 +0000161 // The identifier is first looked up in the class of the object
162 // expression. If the identifier is not found, it is then looked up in
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000163 // the context of the entire postfix-expression and shall name a class
164 // or function template.
165 //
166 // FIXME: When we're instantiating a template, do we actually have to
167 // look in the scope of the template? Seems fishy...
Douglas Gregor014e88d2009-11-03 23:16:33 +0000168 LookupName(Found, S, TName, LookupOrdinaryName);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000169 ObjectTypeSearchedInScope = true;
170 }
171 } else if (isDependent) {
Mike Stump1eb44332009-09-09 15:08:12 +0000172 // We cannot look into a dependent object type or
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000173 return TNK_Non_template;
174 } else {
175 // Perform unqualified name lookup in the current scope.
Douglas Gregor014e88d2009-11-03 23:16:33 +0000176 LookupName(Found, S, TName, LookupOrdinaryName);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000177 }
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Douglas Gregor495c35d2009-08-25 22:51:20 +0000179 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump1eb44332009-09-09 15:08:12 +0000180 assert(!Found.isAmbiguous() &&
Douglas Gregor495c35d2009-08-25 22:51:20 +0000181 "Cannot handle template name-lookup ambiguities");
Douglas Gregor7532dc62009-03-30 22:58:21 +0000182
John McCallf36e02d2009-10-09 21:13:30 +0000183 NamedDecl *Template
184 = isAcceptableTemplateName(Context, Found.getAsSingleDecl(Context));
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000185 if (!Template)
186 return TNK_Non_template;
187
188 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
189 // C++ [basic.lookup.classref]p1:
Mike Stump1eb44332009-09-09 15:08:12 +0000190 // [...] If the lookup in the class of the object expression finds a
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000191 // template, the name is also looked up in the context of the entire
192 // postfix-expression and [...]
193 //
John McCallf36e02d2009-10-09 21:13:30 +0000194 LookupResult FoundOuter;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000195 LookupName(FoundOuter, S, TName, LookupOrdinaryName);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000196 // FIXME: Handle ambiguities in this lookup better
John McCallf36e02d2009-10-09 21:13:30 +0000197 NamedDecl *OuterTemplate
198 = isAcceptableTemplateName(Context, FoundOuter.getAsSingleDecl(Context));
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000200 if (!OuterTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +0000201 // - if the name is not found, the name found in the class of the
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000202 // object expression is used, otherwise
203 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000204 // - if the name is found in the context of the entire
205 // postfix-expression and does not name a class template, the name
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000206 // found in the class of the object expression is used, otherwise
207 } else {
208 // - if the name found is a class template, it must refer to the same
Mike Stump1eb44332009-09-09 15:08:12 +0000209 // entity as the one found in the class of the object expression,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000210 // otherwise the program is ill-formed.
211 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
Douglas Gregor014e88d2009-11-03 23:16:33 +0000212 Diag(Name.getSourceRange().getBegin(),
213 diag::err_nested_name_member_ref_lookup_ambiguous)
214 << TName
215 << Name.getSourceRange();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000216 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
217 << QualType::getFromOpaquePtr(ObjectTypePtr);
218 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump1eb44332009-09-09 15:08:12 +0000219
220 // Recover by taking the template that we found in the object
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000221 // expression's type.
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000222 }
Mike Stump1eb44332009-09-09 15:08:12 +0000223 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000224 }
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Douglas Gregor014e88d2009-11-03 23:16:33 +0000226 if (SS.isSet() && !SS.isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000227 NestedNameSpecifier *Qualifier
Douglas Gregor014e88d2009-11-03 23:16:33 +0000228 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +0000229 if (OverloadedFunctionDecl *Ovl
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000230 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump1eb44332009-09-09 15:08:12 +0000231 TemplateResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000232 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
233 Ovl));
234 else
Mike Stump1eb44332009-09-09 15:08:12 +0000235 TemplateResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000236 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump1eb44332009-09-09 15:08:12 +0000237 cast<TemplateDecl>(Template)));
238 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000239 = dyn_cast<OverloadedFunctionDecl>(Template)) {
240 TemplateResult = TemplateTy::make(TemplateName(Ovl));
241 } else {
242 TemplateResult = TemplateTy::make(
243 TemplateName(cast<TemplateDecl>(Template)));
244 }
Mike Stump1eb44332009-09-09 15:08:12 +0000245
246 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000247 isa<TemplateTemplateParmDecl>(Template))
248 return TNK_Type_template;
Mike Stump1eb44332009-09-09 15:08:12 +0000249
250 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000251 isa<OverloadedFunctionDecl>(Template)) &&
252 "Unhandled template kind in Sema::isTemplateName");
253 return TNK_Function_template;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000254}
255
Douglas Gregor72c3f312008-12-05 18:15:24 +0000256/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
257/// that the template parameter 'PrevDecl' is being shadowed by a new
258/// declaration at location Loc. Returns true to indicate that this is
259/// an error, and false otherwise.
260bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000261 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000262
263 // Microsoft Visual C++ permits template parameters to be shadowed.
264 if (getLangOptions().Microsoft)
265 return false;
266
267 // C++ [temp.local]p4:
268 // A template-parameter shall not be redeclared within its
269 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000270 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000271 << cast<NamedDecl>(PrevDecl)->getDeclName();
272 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
273 return true;
274}
275
Douglas Gregor2943aed2009-03-03 04:44:36 +0000276/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000277/// the parameter D to reference the templated declaration and return a pointer
278/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000279TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000280 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000281 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000282 return Temp;
283 }
284 return 0;
285}
286
Douglas Gregor788cd062009-11-11 01:00:40 +0000287static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
288 const ParsedTemplateArgument &Arg) {
289
290 switch (Arg.getKind()) {
291 case ParsedTemplateArgument::Type: {
292 DeclaratorInfo *DI;
293 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
294 if (!DI)
295 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation());
296 return TemplateArgumentLoc(TemplateArgument(T), DI);
297 }
298
299 case ParsedTemplateArgument::NonType: {
300 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
301 return TemplateArgumentLoc(TemplateArgument(E), E);
302 }
303
304 case ParsedTemplateArgument::Template: {
305 TemplateName Template
306 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
307 return TemplateArgumentLoc(TemplateArgument(Template),
308 Arg.getScopeSpec().getRange(),
309 Arg.getLocation());
310 }
311 }
312
313 llvm::llvm_unreachable("Unhandled parsed template argument");
314 return TemplateArgumentLoc();
315}
316
317/// \brief Translates template arguments as provided by the parser
318/// into template arguments used by semantic analysis.
319void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
320 llvm::SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs) {
321 TemplateArgs.reserve(TemplateArgsIn.size());
322
323 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
324 TemplateArgs.push_back(translateTemplateArgument(*this, TemplateArgsIn[I]));
325}
326
Douglas Gregor72c3f312008-12-05 18:15:24 +0000327/// ActOnTypeParameter - Called when a C++ template type parameter
328/// (e.g., "typename T") has been parsed. Typename specifies whether
329/// the keyword "typename" was used to declare the type parameter
330/// (otherwise, "class" was used), and KeyLoc is the location of the
331/// "class" or "typename" keyword. ParamName is the name of the
332/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump1eb44332009-09-09 15:08:12 +0000333/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000334/// If the type parameter has a default argument, it will be added
335/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000336Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000337 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000338 SourceLocation KeyLoc,
339 IdentifierInfo *ParamName,
340 SourceLocation ParamNameLoc,
341 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000342 assert(S->isTemplateParamScope() &&
343 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000344 bool Invalid = false;
345
346 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000347 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000348 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000349 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000350 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000351 }
352
Douglas Gregorddc29e12009-02-06 22:42:48 +0000353 SourceLocation Loc = ParamNameLoc;
354 if (!ParamName)
355 Loc = KeyLoc;
356
Douglas Gregor72c3f312008-12-05 18:15:24 +0000357 TemplateTypeParmDecl *Param
Mike Stump1eb44332009-09-09 15:08:12 +0000358 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
359 Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000360 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000361 if (Invalid)
362 Param->setInvalidDecl();
363
364 if (ParamName) {
365 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000366 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000367 IdResolver.AddDecl(Param);
368 }
369
Chris Lattnerb28317a2009-03-28 19:18:32 +0000370 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000371}
372
Douglas Gregord684b002009-02-10 19:49:53 +0000373/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000374/// Default) to the given template type parameter (TypeParam).
375void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000376 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000377 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000378 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000379 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000380 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000381
382 DeclaratorInfo *DefaultDInfo;
383 GetTypeFromParser(DefaultT, &DefaultDInfo);
384
385 assert(DefaultDInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000386
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000387 // C++0x [temp.param]p9:
388 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000389 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000390 if (Parm->isParameterPack()) {
391 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000392 return;
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Douglas Gregord684b002009-02-10 19:49:53 +0000395 // C++ [temp.param]p14:
396 // A template-parameter shall not be used in its own default argument.
397 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Douglas Gregord684b002009-02-10 19:49:53 +0000399 // Check the template argument itself.
John McCall833ca992009-10-29 08:12:44 +0000400 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000401 Parm->setInvalidDecl();
402 return;
403 }
404
John McCall833ca992009-10-29 08:12:44 +0000405 Parm->setDefaultArgument(DefaultDInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000406}
407
Douglas Gregor2943aed2009-03-03 04:44:36 +0000408/// \brief Check that the type of a non-type template parameter is
409/// well-formed.
410///
411/// \returns the (possibly-promoted) parameter type if valid;
412/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000413QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000414Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
415 // C++ [temp.param]p4:
416 //
417 // A non-type template-parameter shall have one of the following
418 // (optionally cv-qualified) types:
419 //
420 // -- integral or enumeration type,
421 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000422 // -- pointer to object or pointer to function,
423 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000424 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
425 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000426 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000427 T->isReferenceType() ||
428 // -- pointer to member.
429 T->isMemberPointerType() ||
430 // If T is a dependent type, we can't do the check now, so we
431 // assume that it is well-formed.
432 T->isDependentType())
433 return T;
434 // C++ [temp.param]p8:
435 //
436 // A non-type template-parameter of type "array of T" or
437 // "function returning T" is adjusted to be of type "pointer to
438 // T" or "pointer to function returning T", respectively.
439 else if (T->isArrayType())
440 // FIXME: Keep the type prior to promotion?
441 return Context.getArrayDecayedType(T);
442 else if (T->isFunctionType())
443 // FIXME: Keep the type prior to promotion?
444 return Context.getPointerType(T);
445
446 Diag(Loc, diag::err_template_nontype_parm_bad_type)
447 << T;
448
449 return QualType();
450}
451
Douglas Gregor72c3f312008-12-05 18:15:24 +0000452/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
453/// template parameter (e.g., "int Size" in "template<int Size>
454/// class Array") has been parsed. S is the current scope and D is
455/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000456Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000457 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000458 unsigned Position) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000459 DeclaratorInfo *DInfo = 0;
460 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000461
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000462 assert(S->isTemplateParamScope() &&
463 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000464 bool Invalid = false;
465
466 IdentifierInfo *ParamName = D.getIdentifier();
467 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000468 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000469 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000470 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000471 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000472 }
473
Douglas Gregor2943aed2009-03-03 04:44:36 +0000474 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000475 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000476 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000477 Invalid = true;
478 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000479
Douglas Gregor72c3f312008-12-05 18:15:24 +0000480 NonTypeTemplateParmDecl *Param
481 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000482 Depth, Position, ParamName, T, DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000483 if (Invalid)
484 Param->setInvalidDecl();
485
486 if (D.getIdentifier()) {
487 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000488 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000489 IdResolver.AddDecl(Param);
490 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000491 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000492}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000493
Douglas Gregord684b002009-02-10 19:49:53 +0000494/// \brief Adds a default argument to the given non-type template
495/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000496void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000497 SourceLocation EqualLoc,
498 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000499 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000500 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000501 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Douglas Gregord684b002009-02-10 19:49:53 +0000503 // C++ [temp.param]p14:
504 // A template-parameter shall not be used in its own default argument.
505 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Douglas Gregord684b002009-02-10 19:49:53 +0000507 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000508 TemplateArgument Converted;
509 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
510 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000511 TemplateParm->setInvalidDecl();
512 return;
513 }
514
Anders Carlssone9146f22009-05-01 19:49:17 +0000515 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000516}
517
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000518
519/// ActOnTemplateTemplateParameter - Called when a C++ template template
520/// parameter (e.g. T in template <template <typename> class T> class array)
521/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000522Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
523 SourceLocation TmpLoc,
524 TemplateParamsTy *Params,
525 IdentifierInfo *Name,
526 SourceLocation NameLoc,
527 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000528 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000529 assert(S->isTemplateParamScope() &&
530 "Template template parameter not in template parameter scope!");
531
532 // Construct the parameter object.
533 TemplateTemplateParmDecl *Param =
534 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
535 Position, Name,
536 (TemplateParameterList*)Params);
537
538 // Make sure the parameter is valid.
539 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
540 // do anything yet. However, if the template parameter list or (eventual)
541 // default value is ever invalidated, that will propagate here.
542 bool Invalid = false;
543 if (Invalid) {
544 Param->setInvalidDecl();
545 }
546
547 // If the tt-param has a name, then link the identifier into the scope
548 // and lookup mechanisms.
549 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000550 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000551 IdResolver.AddDecl(Param);
552 }
553
Chris Lattnerb28317a2009-03-28 19:18:32 +0000554 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000555}
556
Douglas Gregord684b002009-02-10 19:49:53 +0000557/// \brief Adds a default argument to the given template template
558/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000559void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000560 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000561 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000562 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000563 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000564
Douglas Gregord684b002009-02-10 19:49:53 +0000565 // C++ [temp.param]p14:
566 // A template-parameter shall not be used in its own default argument.
567 // FIXME: Implement this check! Needs a recursive walk over the types.
568
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000569 // Check only that we have a template template argument. We don't want to
570 // try to check well-formedness now, because our template template parameter
571 // might have dependent types in its template parameters, which we wouldn't
572 // be able to match now.
573 //
574 // If none of the template template parameter's template arguments mention
575 // other template parameters, we could actually perform more checking here.
576 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000577 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000578 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
579 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
580 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000581 return;
582 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000583
Douglas Gregor788cd062009-11-11 01:00:40 +0000584 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregord684b002009-02-10 19:49:53 +0000585}
586
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000587/// ActOnTemplateParameterList - Builds a TemplateParameterList that
588/// contains the template parameters in Params/NumParams.
589Sema::TemplateParamsTy *
590Sema::ActOnTemplateParameterList(unsigned Depth,
591 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000592 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000593 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000594 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000595 SourceLocation RAngleLoc) {
596 if (ExportLoc.isValid())
597 Diag(ExportLoc, diag::note_template_export_unsupported);
598
Douglas Gregorddc29e12009-02-06 22:42:48 +0000599 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000600 (NamedDecl**)Params, NumParams,
601 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000602}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000603
Douglas Gregor212e81c2009-03-25 00:13:59 +0000604Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000605Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000606 SourceLocation KWLoc, const CXXScopeSpec &SS,
607 IdentifierInfo *Name, SourceLocation NameLoc,
608 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000609 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000610 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000611 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000612 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000613 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000614 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000615
616 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000617 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000618 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000619
John McCall05b23ea2009-09-14 21:59:20 +0000620 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
621 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000622
623 // There is no such thing as an unnamed class template.
624 if (!Name) {
625 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000626 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000627 }
628
629 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000630 DeclContext *SemanticContext;
631 LookupResult Previous;
632 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregorf0510d42009-10-12 23:11:44 +0000633 if (RequireCompleteDeclContext(SS))
634 return true;
635
Douglas Gregor05396e22009-08-25 17:23:04 +0000636 SemanticContext = computeDeclContext(SS, true);
637 if (!SemanticContext) {
638 // FIXME: Produce a reasonable diagnostic here
639 return true;
640 }
Mike Stump1eb44332009-09-09 15:08:12 +0000641
John McCallf36e02d2009-10-09 21:13:30 +0000642 LookupQualifiedName(Previous, SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor05396e22009-08-25 17:23:04 +0000643 true);
644 } else {
645 SemanticContext = CurContext;
John McCallf36e02d2009-10-09 21:13:30 +0000646 LookupName(Previous, S, Name, LookupOrdinaryName, true);
Douglas Gregor05396e22009-08-25 17:23:04 +0000647 }
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Douglas Gregorddc29e12009-02-06 22:42:48 +0000649 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
650 NamedDecl *PrevDecl = 0;
651 if (Previous.begin() != Previous.end())
652 PrevDecl = *Previous.begin();
653
Douglas Gregor6102d982009-09-26 07:05:09 +0000654 if (PrevDecl && TUK == TUK_Friend) {
655 // C++ [namespace.memdef]p3:
656 // [...] When looking for a prior declaration of a class or a function
657 // declared as a friend, and when the name of the friend class or
658 // function is neither a qualified name nor a template-id, scopes outside
659 // the innermost enclosing namespace scope are not considered.
660 DeclContext *OutermostContext = CurContext;
661 while (!OutermostContext->isFileContext())
662 OutermostContext = OutermostContext->getLookupParent();
663
664 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
665 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
666 SemanticContext = PrevDecl->getDeclContext();
667 } else {
668 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregor259571e2009-10-30 22:42:42 +0000669 // context we computed is the semantic context for our new
Douglas Gregor6102d982009-09-26 07:05:09 +0000670 // declaration.
671 PrevDecl = 0;
672 SemanticContext = OutermostContext;
673 }
Douglas Gregor259571e2009-10-30 22:42:42 +0000674
675 if (CurContext->isDependentContext()) {
676 // If this is a dependent context, we don't want to link the friend
677 // class template to the template in scope, because that would perform
678 // checking of the template parameter lists that can't be performed
679 // until the outer context is instantiated.
680 PrevDecl = 0;
681 }
Douglas Gregor6102d982009-09-26 07:05:09 +0000682 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000683 PrevDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Douglas Gregorddc29e12009-02-06 22:42:48 +0000685 // If there is a previous declaration with the same name, check
686 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000687 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000688 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000689
690 // We may have found the injected-class-name of a class template,
691 // class template partial specialization, or class template specialization.
692 // In these cases, grab the template that is being defined or specialized.
693 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
694 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
695 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
696 PrevClassTemplate
697 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
698 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
699 PrevClassTemplate
700 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
701 ->getSpecializedTemplate();
702 }
703 }
704
Douglas Gregorddc29e12009-02-06 22:42:48 +0000705 if (PrevClassTemplate) {
706 // Ensure that the template parameter lists are compatible.
707 if (!TemplateParameterListsAreEqual(TemplateParams,
708 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000709 /*Complain=*/true,
710 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000711 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000712
713 // C++ [temp.class]p4:
714 // In a redeclaration, partial specialization, explicit
715 // specialization or explicit instantiation of a class template,
716 // the class-key shall agree in kind with the original class
717 // template declaration (7.1.5.3).
718 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000719 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000720 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000721 << Name
Mike Stump1eb44332009-09-09 15:08:12 +0000722 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +0000723 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000724 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000725 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000726 }
727
Douglas Gregorddc29e12009-02-06 22:42:48 +0000728 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000729 if (TUK == TUK_Definition) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000730 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
731 Diag(NameLoc, diag::err_redefinition) << Name;
732 Diag(Def->getLocation(), diag::note_previous_definition);
733 // FIXME: Would it make sense to try to "forget" the previous
734 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000735 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000736 }
737 }
738 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
739 // Maybe we will complain about the shadowed template parameter.
740 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
741 // Just pretend that we didn't see the previous declaration.
742 PrevDecl = 0;
743 } else if (PrevDecl) {
744 // C++ [temp]p5:
745 // A class template shall not have the same name as any other
746 // template, class, function, object, enumeration, enumerator,
747 // namespace, or type in the same scope (3.3), except as specified
748 // in (14.5.4).
749 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
750 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000751 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000752 }
753
Douglas Gregord684b002009-02-10 19:49:53 +0000754 // Check the template parameter list of this declaration, possibly
755 // merging in the template parameter list from the previous class
756 // template declaration.
757 if (CheckTemplateParameterList(TemplateParams,
758 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
759 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Douglas Gregor7da97d02009-05-10 22:57:19 +0000761 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000762 // declaration!
763
Mike Stump1eb44332009-09-09 15:08:12 +0000764 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000765 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000766 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000767 PrevClassTemplate->getTemplatedDecl() : 0,
768 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000769
770 ClassTemplateDecl *NewTemplate
771 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
772 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000773 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000774 NewClass->setDescribedClassTemplate(NewTemplate);
775
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000776 // Build the type for the class template declaration now.
Mike Stump1eb44332009-09-09 15:08:12 +0000777 QualType T =
778 Context.getTypeDeclType(NewClass,
779 PrevClassTemplate?
780 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000781 assert(T->isDependentType() && "Class template type is not dependent?");
782 (void)T;
783
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000784 // If we are providing an explicit specialization of a member that is a
785 // class template, make a note of that.
786 if (PrevClassTemplate &&
787 PrevClassTemplate->getInstantiatedFromMemberTemplate())
788 PrevClassTemplate->setMemberSpecialization();
789
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000790 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000791 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000792 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Douglas Gregorddc29e12009-02-06 22:42:48 +0000794 // Set the lexical context of these templates
795 NewClass->setLexicalDeclContext(CurContext);
796 NewTemplate->setLexicalDeclContext(CurContext);
797
John McCall0f434ec2009-07-31 02:45:11 +0000798 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000799 NewClass->startDefinition();
800
801 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000802 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000803
John McCall05b23ea2009-09-14 21:59:20 +0000804 if (TUK != TUK_Friend)
805 PushOnScopeChains(NewTemplate, S);
806 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000807 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000808 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000809 NewClass->setAccess(PrevClassTemplate->getAccess());
810 }
John McCall05b23ea2009-09-14 21:59:20 +0000811
Douglas Gregord85bea22009-09-26 06:47:28 +0000812 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
813 PrevClassTemplate != NULL);
814
John McCall05b23ea2009-09-14 21:59:20 +0000815 // Friend templates are visible in fairly strange ways.
816 if (!CurContext->isDependentContext()) {
817 DeclContext *DC = SemanticContext->getLookupContext();
818 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
819 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
820 PushOnScopeChains(NewTemplate, EnclosingScope,
821 /* AddToContext = */ false);
822 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000823
824 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
825 NewClass->getLocation(),
826 NewTemplate,
827 /*FIXME:*/NewClass->getLocation());
828 Friend->setAccess(AS_public);
829 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000830 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000831
Douglas Gregord684b002009-02-10 19:49:53 +0000832 if (Invalid) {
833 NewTemplate->setInvalidDecl();
834 NewClass->setInvalidDecl();
835 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000836 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000837}
838
Douglas Gregord684b002009-02-10 19:49:53 +0000839/// \brief Checks the validity of a template parameter list, possibly
840/// considering the template parameter list from a previous
841/// declaration.
842///
843/// If an "old" template parameter list is provided, it must be
844/// equivalent (per TemplateParameterListsAreEqual) to the "new"
845/// template parameter list.
846///
847/// \param NewParams Template parameter list for a new template
848/// declaration. This template parameter list will be updated with any
849/// default arguments that are carried through from the previous
850/// template parameter list.
851///
852/// \param OldParams If provided, template parameter list from a
853/// previous declaration of the same template. Default template
854/// arguments will be merged from the old template parameter list to
855/// the new template parameter list.
856///
857/// \returns true if an error occurred, false otherwise.
858bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
859 TemplateParameterList *OldParams) {
860 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000861
Douglas Gregord684b002009-02-10 19:49:53 +0000862 // C++ [temp.param]p10:
863 // The set of default template-arguments available for use with a
864 // template declaration or definition is obtained by merging the
865 // default arguments from the definition (if in scope) and all
866 // declarations in scope in the same way default function
867 // arguments are (8.3.6).
868 bool SawDefaultArgument = false;
869 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000870
Anders Carlsson49d25572009-06-12 23:20:15 +0000871 bool SawParameterPack = false;
872 SourceLocation ParameterPackLoc;
873
Mike Stump1a35fde2009-02-11 23:03:27 +0000874 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000875 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000876 if (OldParams)
877 OldParam = OldParams->begin();
878
879 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
880 NewParamEnd = NewParams->end();
881 NewParam != NewParamEnd; ++NewParam) {
882 // Variables used to diagnose redundant default arguments
883 bool RedundantDefaultArg = false;
884 SourceLocation OldDefaultLoc;
885 SourceLocation NewDefaultLoc;
886
887 // Variables used to diagnose missing default arguments
888 bool MissingDefaultArg = false;
889
Anders Carlsson49d25572009-06-12 23:20:15 +0000890 // C++0x [temp.param]p11:
891 // If a template parameter of a class template is a template parameter pack,
892 // it must be the last template parameter.
893 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +0000894 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +0000895 diag::err_template_param_pack_must_be_last_template_parameter);
896 Invalid = true;
897 }
898
Douglas Gregord684b002009-02-10 19:49:53 +0000899 // Merge default arguments for template type parameters.
900 if (TemplateTypeParmDecl *NewTypeParm
901 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000902 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +0000903 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Anders Carlsson49d25572009-06-12 23:20:15 +0000905 if (NewTypeParm->isParameterPack()) {
906 assert(!NewTypeParm->hasDefaultArgument() &&
907 "Parameter packs can't have a default argument!");
908 SawParameterPack = true;
909 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000910 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +0000911 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +0000912 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
913 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
914 SawDefaultArgument = true;
915 RedundantDefaultArg = true;
916 PreviousDefaultArgLoc = NewDefaultLoc;
917 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
918 // Merge the default argument from the old declaration to the
919 // new declaration.
920 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +0000921 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +0000922 true);
923 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
924 } else if (NewTypeParm->hasDefaultArgument()) {
925 SawDefaultArgument = true;
926 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
927 } else if (SawDefaultArgument)
928 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000929 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +0000930 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000931 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000932 NonTypeTemplateParmDecl *OldNonTypeParm
933 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000934 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000935 NewNonTypeParm->hasDefaultArgument()) {
936 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
937 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
938 SawDefaultArgument = true;
939 RedundantDefaultArg = true;
940 PreviousDefaultArgLoc = NewDefaultLoc;
941 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
942 // Merge the default argument from the old declaration to the
943 // new declaration.
944 SawDefaultArgument = true;
945 // FIXME: We need to create a new kind of "default argument"
946 // expression that points to a previous template template
947 // parameter.
948 NewNonTypeParm->setDefaultArgument(
949 OldNonTypeParm->getDefaultArgument());
950 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
951 } else if (NewNonTypeParm->hasDefaultArgument()) {
952 SawDefaultArgument = true;
953 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
954 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000955 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000956 } else {
Douglas Gregord684b002009-02-10 19:49:53 +0000957 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000958 TemplateTemplateParmDecl *NewTemplateParm
959 = cast<TemplateTemplateParmDecl>(*NewParam);
960 TemplateTemplateParmDecl *OldTemplateParm
961 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000962 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000963 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000964 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
965 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +0000966 SawDefaultArgument = true;
967 RedundantDefaultArg = true;
968 PreviousDefaultArgLoc = NewDefaultLoc;
969 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
970 // Merge the default argument from the old declaration to the
971 // new declaration.
972 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000973 // FIXME: We need to create a new kind of "default argument" expression
974 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000975 NewTemplateParm->setDefaultArgument(
976 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +0000977 PreviousDefaultArgLoc
978 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +0000979 } else if (NewTemplateParm->hasDefaultArgument()) {
980 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +0000981 PreviousDefaultArgLoc
982 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +0000983 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000984 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +0000985 }
986
987 if (RedundantDefaultArg) {
988 // C++ [temp.param]p12:
989 // A template-parameter shall not be given default arguments
990 // by two different declarations in the same scope.
991 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
992 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
993 Invalid = true;
994 } else if (MissingDefaultArg) {
995 // C++ [temp.param]p11:
996 // If a template-parameter has a default template-argument,
997 // all subsequent template-parameters shall have a default
998 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +0000999 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001000 diag::err_template_param_default_arg_missing);
1001 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1002 Invalid = true;
1003 }
1004
1005 // If we have an old template parameter list that we're merging
1006 // in, move on to the next parameter.
1007 if (OldParams)
1008 ++OldParam;
1009 }
1010
1011 return Invalid;
1012}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001013
Mike Stump1eb44332009-09-09 15:08:12 +00001014/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001015/// specifier, returning the template parameter list that applies to the
1016/// name.
1017///
1018/// \param DeclStartLoc the start of the declaration that has a scope
1019/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001020///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001021/// \param SS the scope specifier that will be matched to the given template
1022/// parameter lists. This scope specifier precedes a qualified name that is
1023/// being declared.
1024///
1025/// \param ParamLists the template parameter lists, from the outermost to the
1026/// innermost template parameter lists.
1027///
1028/// \param NumParamLists the number of template parameter lists in ParamLists.
1029///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001030/// \param IsExplicitSpecialization will be set true if the entity being
1031/// declared is an explicit specialization, false otherwise.
1032///
Mike Stump1eb44332009-09-09 15:08:12 +00001033/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001034/// name that is preceded by the scope specifier @p SS. This template
1035/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001036/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001037/// template specialization), or may be NULL (if we were's declaring isn't
1038/// itself a template).
1039TemplateParameterList *
1040Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1041 const CXXScopeSpec &SS,
1042 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001043 unsigned NumParamLists,
1044 bool &IsExplicitSpecialization) {
1045 IsExplicitSpecialization = false;
1046
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001047 // Find the template-ids that occur within the nested-name-specifier. These
1048 // template-ids will match up with the template parameter lists.
1049 llvm::SmallVector<const TemplateSpecializationType *, 4>
1050 TemplateIdsInSpecifier;
1051 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1052 NNS; NNS = NNS->getPrefix()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001053 if (const TemplateSpecializationType *SpecType
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001054 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1055 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1056 if (!Template)
1057 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Ted Kremenek6217b802009-07-29 21:53:49 +00001059 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001060 ClassTemplateSpecializationDecl *SpecDecl
1061 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1062 // If the nested name specifier refers to an explicit specialization,
1063 // we don't need a template<> header.
Douglas Gregor861d0e82009-09-16 00:01:48 +00001064 // FIXME: revisit this approach once we cope with specializations
Douglas Gregorb88e8882009-07-30 17:40:51 +00001065 // properly.
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001066 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
1067 continue;
1068 }
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001070 TemplateIdsInSpecifier.push_back(SpecType);
1071 }
1072 }
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001074 // Reverse the list of template-ids in the scope specifier, so that we can
1075 // more easily match up the template-ids and the template parameter lists.
1076 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001078 SourceLocation FirstTemplateLoc = DeclStartLoc;
1079 if (NumParamLists)
1080 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001082 // Match the template-ids found in the specifier to the template parameter
1083 // lists.
1084 unsigned Idx = 0;
1085 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1086 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001087 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1088 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001089 if (Idx >= NumParamLists) {
1090 // We have a template-id without a corresponding template parameter
1091 // list.
1092 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001093 // FIXME: the location information here isn't great.
1094 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001095 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001096 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001097 << SS.getRange();
1098 } else {
1099 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1100 << SS.getRange()
1101 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1102 "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001103 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001104 }
1105 return 0;
1106 }
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001108 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001109 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001110 TemplateDecl *Template
Douglas Gregorb88e8882009-07-30 17:40:51 +00001111 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1112
Mike Stump1eb44332009-09-09 15:08:12 +00001113 if (ClassTemplateDecl *ClassTemplate
Douglas Gregorb88e8882009-07-30 17:40:51 +00001114 = dyn_cast<ClassTemplateDecl>(Template)) {
1115 TemplateParameterList *ExpectedTemplateParams = 0;
1116 // Is this template-id naming the primary template?
1117 if (Context.hasSameType(TemplateId,
1118 ClassTemplate->getInjectedClassNameType(Context)))
1119 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1120 // ... or a partial specialization?
1121 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1122 = ClassTemplate->findPartialSpecialization(TemplateId))
1123 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1124
1125 if (ExpectedTemplateParams)
Mike Stump1eb44332009-09-09 15:08:12 +00001126 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregorb88e8882009-07-30 17:40:51 +00001127 ExpectedTemplateParams,
Douglas Gregorfb898e12009-11-12 16:20:59 +00001128 true, TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00001129 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00001130 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001131 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001132 diag::err_template_param_list_matches_nontemplate)
1133 << TemplateId
1134 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001135 else
1136 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001137 }
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001139 // If there were at least as many template-ids as there were template
1140 // parameter lists, then there are no template parameter lists remaining for
1141 // the declaration itself.
1142 if (Idx >= NumParamLists)
1143 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001145 // If there were too many template parameter lists, complain about that now.
1146 if (Idx != NumParamLists - 1) {
1147 while (Idx < NumParamLists - 1) {
Mike Stump1eb44332009-09-09 15:08:12 +00001148 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001149 diag::err_template_spec_extra_headers)
1150 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1151 ParamLists[Idx]->getRAngleLoc());
1152 ++Idx;
1153 }
1154 }
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001156 // Return the last template parameter list, which corresponds to the
1157 // entity being declared.
1158 return ParamLists[NumParamLists - 1];
1159}
1160
Douglas Gregor7532dc62009-03-30 22:58:21 +00001161QualType Sema::CheckTemplateIdType(TemplateName Name,
1162 SourceLocation TemplateLoc,
1163 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001164 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001165 unsigned NumTemplateArgs,
1166 SourceLocation RAngleLoc) {
1167 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001168 if (!Template) {
1169 // The template name does not resolve to a template, so we just
1170 // build a dependent template-id type.
Douglas Gregorc45c2322009-03-31 00:43:58 +00001171 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001172 NumTemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001173 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001174
Douglas Gregor40808ce2009-03-09 23:48:35 +00001175 // Check that the template argument list is well-formed for this
1176 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001177 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1178 NumTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001179 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001180 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001181 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001182 return QualType();
1183
Mike Stump1eb44332009-09-09 15:08:12 +00001184 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001185 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001186 "Converted template argument list is too short!");
1187
1188 QualType CanonType;
1189
Douglas Gregorcaddba02009-11-12 18:38:13 +00001190 if (Name.isDependent() ||
1191 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +00001192 TemplateArgs,
Douglas Gregorcaddba02009-11-12 18:38:13 +00001193 NumTemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001194 // This class template specialization is a dependent
1195 // type. Therefore, its canonical type is another class template
1196 // specialization type that contains all of the converted
1197 // arguments in canonical form. This ensures that, e.g., A<T> and
1198 // A<T, T> have identical types when A is declared as:
1199 //
1200 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001201 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001202 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001203 Converted.getFlatArguments(),
1204 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Douglas Gregor1275ae02009-07-28 23:00:59 +00001206 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001207 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001208 // In the future, we need to teach getTemplateSpecializationType to only
1209 // build the canonical type and return that to us.
1210 CanonType = Context.getCanonicalType(CanonType);
Mike Stump1eb44332009-09-09 15:08:12 +00001211 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001212 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001213 // Find the class template specialization declaration that
1214 // corresponds to these arguments.
1215 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001216 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001217 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001218 Converted.flatSize(),
1219 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001220 void *InsertPos = 0;
1221 ClassTemplateSpecializationDecl *Decl
1222 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1223 if (!Decl) {
1224 // This is the first time we have referenced this class template
1225 // specialization. Create the canonical declaration and add it to
1226 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001227 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001228 ClassTemplate->getDeclContext(),
John McCall9cc78072009-09-11 07:25:08 +00001229 ClassTemplate->getLocation(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001230 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001231 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001232 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1233 Decl->setLexicalDeclContext(CurContext);
1234 }
1235
1236 CanonType = Context.getTypeDeclType(Decl);
1237 }
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Douglas Gregor40808ce2009-03-09 23:48:35 +00001239 // Build the fully-sugared type for this class template
1240 // specialization, which refers back to the class template
1241 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +00001242 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1243 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001244}
1245
Douglas Gregorcc636682009-02-17 23:15:12 +00001246Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001247Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001248 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001249 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001250 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001251 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001252
Douglas Gregor40808ce2009-03-09 23:48:35 +00001253 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00001254 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor314b97f2009-11-10 19:49:08 +00001255 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001256
Douglas Gregor7532dc62009-03-30 22:58:21 +00001257 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001258 TemplateArgs.data(),
1259 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00001260 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001261 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001262
1263 if (Result.isNull())
1264 return true;
1265
John McCall833ca992009-10-29 08:12:44 +00001266 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1267 TemplateSpecializationTypeLoc TL
1268 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1269 TL.setTemplateNameLoc(TemplateLoc);
1270 TL.setLAngleLoc(LAngleLoc);
1271 TL.setRAngleLoc(RAngleLoc);
1272 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1273 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1274
1275 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001276}
John McCallf1bbbb42009-09-04 01:14:41 +00001277
John McCall6b2becf2009-09-08 17:47:29 +00001278Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1279 TagUseKind TUK,
1280 DeclSpec::TST TagSpec,
1281 SourceLocation TagLoc) {
1282 if (TypeResult.isInvalid())
1283 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001284
John McCall833ca992009-10-29 08:12:44 +00001285 // FIXME: preserve source info, ideally without copying the DI.
1286 DeclaratorInfo *DI;
1287 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001288
John McCall6b2becf2009-09-08 17:47:29 +00001289 // Verify the tag specifier.
1290 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001291
John McCall6b2becf2009-09-08 17:47:29 +00001292 if (const RecordType *RT = Type->getAs<RecordType>()) {
1293 RecordDecl *D = RT->getDecl();
1294
1295 IdentifierInfo *Id = D->getIdentifier();
1296 assert(Id && "templated class must have an identifier");
1297
1298 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1299 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001300 << Type
John McCall6b2becf2009-09-08 17:47:29 +00001301 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1302 D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001303 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001304 }
1305 }
1306
John McCall6b2becf2009-09-08 17:47:29 +00001307 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1308
1309 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001310}
1311
Douglas Gregorf17bb742009-10-22 17:20:55 +00001312Sema::OwningExprResult Sema::BuildTemplateIdExpr(NestedNameSpecifier *Qualifier,
1313 SourceRange QualifierRange,
1314 TemplateName Template,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001315 SourceLocation TemplateNameLoc,
1316 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001317 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001318 unsigned NumTemplateArgs,
1319 SourceLocation RAngleLoc) {
1320 // FIXME: Can we do any checking at this point? I guess we could check the
1321 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001322 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001323 // though.
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001324
1325 // Cope with an implicit member access in a C++ non-static member function.
1326 NamedDecl *D = Template.getAsTemplateDecl();
1327 if (!D)
1328 D = Template.getAsOverloadedFunctionDecl();
1329
Douglas Gregorf17bb742009-10-22 17:20:55 +00001330 CXXScopeSpec SS;
1331 SS.setRange(QualifierRange);
1332 SS.setScopeRep(Qualifier);
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001333 QualType ThisType, MemberType;
Douglas Gregorf17bb742009-10-22 17:20:55 +00001334 if (D && isImplicitMemberReference(&SS, D, TemplateNameLoc,
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001335 ThisType, MemberType)) {
1336 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
1337 return Owned(MemberExpr::Create(Context, This, true,
Douglas Gregorf17bb742009-10-22 17:20:55 +00001338 Qualifier, QualifierRange,
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001339 D, TemplateNameLoc, true,
1340 LAngleLoc, TemplateArgs,
1341 NumTemplateArgs, RAngleLoc,
1342 Context.OverloadTy));
1343 }
1344
Douglas Gregorf17bb742009-10-22 17:20:55 +00001345 return Owned(TemplateIdRefExpr::Create(Context, Context.OverloadTy,
1346 Qualifier, QualifierRange,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001347 Template, TemplateNameLoc, LAngleLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001348 TemplateArgs,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001349 NumTemplateArgs, RAngleLoc));
1350}
1351
Douglas Gregorf17bb742009-10-22 17:20:55 +00001352Sema::OwningExprResult Sema::ActOnTemplateIdExpr(const CXXScopeSpec &SS,
1353 TemplateTy TemplateD,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001354 SourceLocation TemplateNameLoc,
1355 SourceLocation LAngleLoc,
1356 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001357 SourceLocation RAngleLoc) {
1358 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001360 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00001361 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor314b97f2009-11-10 19:49:08 +00001362 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001363 TemplateArgsIn.release();
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Douglas Gregorf17bb742009-10-22 17:20:55 +00001365 return BuildTemplateIdExpr((NestedNameSpecifier *)SS.getScopeRep(),
1366 SS.getRange(),
1367 Template, TemplateNameLoc, LAngleLoc,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001368 TemplateArgs.data(), TemplateArgs.size(),
1369 RAngleLoc);
1370}
1371
Douglas Gregorc45c2322009-03-31 00:43:58 +00001372/// \brief Form a dependent template name.
1373///
1374/// This action forms a dependent template name given the template
1375/// name and its (presumably dependent) scope specifier. For
1376/// example, given "MetaFun::template apply", the scope specifier \p
1377/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1378/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001379Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001380Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001381 const CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001382 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001383 TypeTy *ObjectType) {
Mike Stump1eb44332009-09-09 15:08:12 +00001384 if ((ObjectType &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001385 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1386 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001387 // C++0x [temp.names]p5:
1388 // If a name prefixed by the keyword template is not the name of
1389 // a template, the program is ill-formed. [Note: the keyword
1390 // template may not be applied to non-template members of class
1391 // templates. -end note ] [ Note: as is the case with the
1392 // typename prefix, the template prefix is allowed in cases
1393 // where it is not strictly necessary; i.e., when the
1394 // nested-name-specifier or the expression on the left of the ->
1395 // or . is not dependent on a template-parameter, or the use
1396 // does not appear in the scope of a template. -end note]
1397 //
1398 // Note: C++03 was more strict here, because it banned the use of
1399 // the "template" keyword prior to a template-name that was not a
1400 // dependent name. C++ DR468 relaxed this requirement (the
1401 // "template" keyword is now permitted). We follow the C++0x
1402 // rules, even in C++03 mode, retroactively applying the DR.
1403 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001404 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001405 false, Template);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001406 if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001407 Diag(Name.getSourceRange().getBegin(),
1408 diag::err_template_kw_refers_to_non_template)
1409 << GetNameFromUnqualifiedId(Name)
1410 << Name.getSourceRange();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001411 return TemplateTy();
1412 }
1413
1414 return Template;
1415 }
1416
Mike Stump1eb44332009-09-09 15:08:12 +00001417 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001418 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001419
1420 switch (Name.getKind()) {
1421 case UnqualifiedId::IK_Identifier:
1422 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1423 Name.Identifier));
1424
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001425 case UnqualifiedId::IK_OperatorFunctionId:
1426 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1427 Name.OperatorFunctionId.Operator));
1428
Douglas Gregor014e88d2009-11-03 23:16:33 +00001429 default:
1430 break;
1431 }
1432
1433 Diag(Name.getSourceRange().getBegin(),
1434 diag::err_template_kw_refers_to_non_template)
1435 << GetNameFromUnqualifiedId(Name)
1436 << Name.getSourceRange();
1437 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001438}
1439
Mike Stump1eb44332009-09-09 15:08:12 +00001440bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001441 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001442 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001443 const TemplateArgument &Arg = AL.getArgument();
1444
Anders Carlsson436b1562009-06-13 00:33:33 +00001445 // Check template type parameter.
1446 if (Arg.getKind() != TemplateArgument::Type) {
1447 // C++ [temp.arg.type]p1:
1448 // A template-argument for a template-parameter which is a
1449 // type shall be a type-id.
1450
1451 // We have a template type parameter but the template argument
1452 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001453 SourceRange SR = AL.getSourceRange();
1454 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001455 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Anders Carlsson436b1562009-06-13 00:33:33 +00001457 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001458 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001459
John McCall833ca992009-10-29 08:12:44 +00001460 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001461 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Anders Carlsson436b1562009-06-13 00:33:33 +00001463 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001464 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001465 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001466 return false;
1467}
1468
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001469/// \brief Substitute template arguments into the default template argument for
1470/// the given template type parameter.
1471///
1472/// \param SemaRef the semantic analysis object for which we are performing
1473/// the substitution.
1474///
1475/// \param Template the template that we are synthesizing template arguments
1476/// for.
1477///
1478/// \param TemplateLoc the location of the template name that started the
1479/// template-id we are checking.
1480///
1481/// \param RAngleLoc the location of the right angle bracket ('>') that
1482/// terminates the template-id.
1483///
1484/// \param Param the template template parameter whose default we are
1485/// substituting into.
1486///
1487/// \param Converted the list of template arguments provided for template
1488/// parameters that precede \p Param in the template parameter list.
1489///
1490/// \returns the substituted template argument, or NULL if an error occurred.
1491static DeclaratorInfo *
1492SubstDefaultTemplateArgument(Sema &SemaRef,
1493 TemplateDecl *Template,
1494 SourceLocation TemplateLoc,
1495 SourceLocation RAngleLoc,
1496 TemplateTypeParmDecl *Param,
1497 TemplateArgumentListBuilder &Converted) {
1498 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1499
1500 // If the argument type is dependent, instantiate it now based
1501 // on the previously-computed template arguments.
1502 if (ArgType->getType()->isDependentType()) {
1503 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1504 /*TakeArgs=*/false);
1505
1506 MultiLevelTemplateArgumentList AllTemplateArgs
1507 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1508
1509 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1510 Template, Converted.getFlatArguments(),
1511 Converted.flatSize(),
1512 SourceRange(TemplateLoc, RAngleLoc));
1513
1514 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1515 Param->getDefaultArgumentLoc(),
1516 Param->getDeclName());
1517 }
1518
1519 return ArgType;
1520}
1521
1522/// \brief Substitute template arguments into the default template argument for
1523/// the given non-type template parameter.
1524///
1525/// \param SemaRef the semantic analysis object for which we are performing
1526/// the substitution.
1527///
1528/// \param Template the template that we are synthesizing template arguments
1529/// for.
1530///
1531/// \param TemplateLoc the location of the template name that started the
1532/// template-id we are checking.
1533///
1534/// \param RAngleLoc the location of the right angle bracket ('>') that
1535/// terminates the template-id.
1536///
Douglas Gregor788cd062009-11-11 01:00:40 +00001537/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001538/// substituting into.
1539///
1540/// \param Converted the list of template arguments provided for template
1541/// parameters that precede \p Param in the template parameter list.
1542///
1543/// \returns the substituted template argument, or NULL if an error occurred.
1544static Sema::OwningExprResult
1545SubstDefaultTemplateArgument(Sema &SemaRef,
1546 TemplateDecl *Template,
1547 SourceLocation TemplateLoc,
1548 SourceLocation RAngleLoc,
1549 NonTypeTemplateParmDecl *Param,
1550 TemplateArgumentListBuilder &Converted) {
1551 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1552 /*TakeArgs=*/false);
1553
1554 MultiLevelTemplateArgumentList AllTemplateArgs
1555 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1556
1557 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1558 Template, Converted.getFlatArguments(),
1559 Converted.flatSize(),
1560 SourceRange(TemplateLoc, RAngleLoc));
1561
1562 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1563}
1564
Douglas Gregor788cd062009-11-11 01:00:40 +00001565/// \brief Substitute template arguments into the default template argument for
1566/// the given template template parameter.
1567///
1568/// \param SemaRef the semantic analysis object for which we are performing
1569/// the substitution.
1570///
1571/// \param Template the template that we are synthesizing template arguments
1572/// for.
1573///
1574/// \param TemplateLoc the location of the template name that started the
1575/// template-id we are checking.
1576///
1577/// \param RAngleLoc the location of the right angle bracket ('>') that
1578/// terminates the template-id.
1579///
1580/// \param Param the template template parameter whose default we are
1581/// substituting into.
1582///
1583/// \param Converted the list of template arguments provided for template
1584/// parameters that precede \p Param in the template parameter list.
1585///
1586/// \returns the substituted template argument, or NULL if an error occurred.
1587static TemplateName
1588SubstDefaultTemplateArgument(Sema &SemaRef,
1589 TemplateDecl *Template,
1590 SourceLocation TemplateLoc,
1591 SourceLocation RAngleLoc,
1592 TemplateTemplateParmDecl *Param,
1593 TemplateArgumentListBuilder &Converted) {
1594 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1595 /*TakeArgs=*/false);
1596
1597 MultiLevelTemplateArgumentList AllTemplateArgs
1598 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1599
1600 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1601 Template, Converted.getFlatArguments(),
1602 Converted.flatSize(),
1603 SourceRange(TemplateLoc, RAngleLoc));
1604
1605 return SemaRef.SubstTemplateName(
1606 Param->getDefaultArgument().getArgument().getAsTemplate(),
1607 Param->getDefaultArgument().getTemplateNameLoc(),
1608 AllTemplateArgs);
1609}
1610
Douglas Gregore7526412009-11-11 19:31:23 +00001611/// \brief Check that the given template argument corresponds to the given
1612/// template parameter.
1613bool Sema::CheckTemplateArgument(NamedDecl *Param,
1614 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00001615 TemplateDecl *Template,
1616 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001617 SourceLocation RAngleLoc,
1618 TemplateArgumentListBuilder &Converted) {
Douglas Gregord9e15302009-11-11 19:41:09 +00001619 // Check template type parameters.
1620 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00001621 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00001622
Douglas Gregord9e15302009-11-11 19:41:09 +00001623 // Check non-type template parameters.
1624 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00001625 // Do substitution on the type of the non-type template parameter
1626 // with the template arguments we've seen thus far.
1627 QualType NTTPType = NTTP->getType();
1628 if (NTTPType->isDependentType()) {
1629 // Do substitution on the type of the non-type template parameter.
1630 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1631 NTTP, Converted.getFlatArguments(),
1632 Converted.flatSize(),
1633 SourceRange(TemplateLoc, RAngleLoc));
1634
1635 TemplateArgumentList TemplateArgs(Context, Converted,
1636 /*TakeArgs=*/false);
1637 NTTPType = SubstType(NTTPType,
1638 MultiLevelTemplateArgumentList(TemplateArgs),
1639 NTTP->getLocation(),
1640 NTTP->getDeclName());
1641 // If that worked, check the non-type template parameter type
1642 // for validity.
1643 if (!NTTPType.isNull())
1644 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1645 NTTP->getLocation());
1646 if (NTTPType.isNull())
1647 return true;
1648 }
1649
1650 switch (Arg.getArgument().getKind()) {
1651 case TemplateArgument::Null:
1652 assert(false && "Should never see a NULL template argument here");
1653 return true;
1654
1655 case TemplateArgument::Expression: {
1656 Expr *E = Arg.getArgument().getAsExpr();
1657 TemplateArgument Result;
1658 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1659 return true;
1660
1661 Converted.Append(Result);
1662 break;
1663 }
1664
1665 case TemplateArgument::Declaration:
1666 case TemplateArgument::Integral:
1667 // We've already checked this template argument, so just copy
1668 // it to the list of converted arguments.
1669 Converted.Append(Arg.getArgument());
1670 break;
1671
1672 case TemplateArgument::Template:
1673 // We were given a template template argument. It may not be ill-formed;
1674 // see below.
1675 if (DependentTemplateName *DTN
1676 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1677 // We have a template argument such as \c T::template X, which we
1678 // parsed as a template template argument. However, since we now
1679 // know that we need a non-type template argument, convert this
1680 // template name into an expression.
1681 Expr *E = new (Context) UnresolvedDeclRefExpr(DTN->getIdentifier(),
1682 Context.DependentTy,
1683 Arg.getTemplateNameLoc(),
1684 Arg.getTemplateQualifierRange(),
1685 DTN->getQualifier(),
1686 /*isAddressOfOperand=*/false);
1687
1688 TemplateArgument Result;
1689 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1690 return true;
1691
1692 Converted.Append(Result);
1693 break;
1694 }
1695
1696 // We have a template argument that actually does refer to a class
1697 // template, template alias, or template template parameter, and
1698 // therefore cannot be a non-type template argument.
1699 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1700 << Arg.getSourceRange();
1701
1702 Diag(Param->getLocation(), diag::note_template_param_here);
1703 return true;
1704
1705 case TemplateArgument::Type: {
1706 // We have a non-type template parameter but the template
1707 // argument is a type.
1708
1709 // C++ [temp.arg]p2:
1710 // In a template-argument, an ambiguity between a type-id and
1711 // an expression is resolved to a type-id, regardless of the
1712 // form of the corresponding template-parameter.
1713 //
1714 // We warn specifically about this case, since it can be rather
1715 // confusing for users.
1716 QualType T = Arg.getArgument().getAsType();
1717 SourceRange SR = Arg.getSourceRange();
1718 if (T->isFunctionType())
1719 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1720 else
1721 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1722 Diag(Param->getLocation(), diag::note_template_param_here);
1723 return true;
1724 }
1725
1726 case TemplateArgument::Pack:
Douglas Gregord9e15302009-11-11 19:41:09 +00001727 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00001728 break;
1729 }
1730
1731 return false;
1732 }
1733
1734
1735 // Check template template parameters.
1736 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1737
1738 // Substitute into the template parameter list of the template
1739 // template parameter, since previously-supplied template arguments
1740 // may appear within the template template parameter.
1741 {
1742 // Set up a template instantiation context.
1743 LocalInstantiationScope Scope(*this);
1744 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1745 TempParm, Converted.getFlatArguments(),
1746 Converted.flatSize(),
1747 SourceRange(TemplateLoc, RAngleLoc));
1748
1749 TemplateArgumentList TemplateArgs(Context, Converted,
1750 /*TakeArgs=*/false);
1751 TempParm = cast_or_null<TemplateTemplateParmDecl>(
1752 SubstDecl(TempParm, CurContext,
1753 MultiLevelTemplateArgumentList(TemplateArgs)));
1754 if (!TempParm)
1755 return true;
1756
1757 // FIXME: TempParam is leaked.
1758 }
1759
1760 switch (Arg.getArgument().getKind()) {
1761 case TemplateArgument::Null:
1762 assert(false && "Should never see a NULL template argument here");
1763 return true;
1764
1765 case TemplateArgument::Template:
1766 if (CheckTemplateArgument(TempParm, Arg))
1767 return true;
1768
1769 Converted.Append(Arg.getArgument());
1770 break;
1771
1772 case TemplateArgument::Expression:
1773 case TemplateArgument::Type:
1774 // We have a template template parameter but the template
1775 // argument does not refer to a template.
1776 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1777 return true;
1778
1779 case TemplateArgument::Declaration:
1780 llvm::llvm_unreachable(
1781 "Declaration argument with template template parameter");
1782 break;
1783 case TemplateArgument::Integral:
1784 llvm::llvm_unreachable(
1785 "Integral argument with template template parameter");
1786 break;
1787
1788 case TemplateArgument::Pack:
Douglas Gregord9e15302009-11-11 19:41:09 +00001789 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00001790 break;
1791 }
1792
1793 return false;
1794}
1795
Douglas Gregorc15cb382009-02-09 23:23:08 +00001796/// \brief Check that the given template argument list is well-formed
1797/// for specializing the given template.
1798bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1799 SourceLocation TemplateLoc,
1800 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001801 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001802 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001803 SourceLocation RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001804 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001805 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001806 TemplateParameterList *Params = Template->getTemplateParameters();
1807 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001808 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001809 bool Invalid = false;
1810
Mike Stump1eb44332009-09-09 15:08:12 +00001811 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001812 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001814 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00001815 (NumArgs < Params->getMinRequiredArguments() &&
1816 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001817 // FIXME: point at either the first arg beyond what we can handle,
1818 // or the '>', depending on whether we have too many or too few
1819 // arguments.
1820 SourceRange Range;
1821 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001822 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001823 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1824 << (NumArgs > NumParams)
1825 << (isa<ClassTemplateDecl>(Template)? 0 :
1826 isa<FunctionTemplateDecl>(Template)? 1 :
1827 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1828 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001829 Diag(Template->getLocation(), diag::note_template_decl_here)
1830 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001831 Invalid = true;
1832 }
Mike Stump1eb44332009-09-09 15:08:12 +00001833
1834 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00001835 // [...] The type and form of each template-argument specified in
1836 // a template-id shall match the type and form specified for the
1837 // corresponding parameter declared by the template in its
1838 // template-parameter-list.
1839 unsigned ArgIdx = 0;
1840 for (TemplateParameterList::iterator Param = Params->begin(),
1841 ParamEnd = Params->end();
1842 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00001843 if (ArgIdx > NumArgs && PartialTemplateArgs)
1844 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Douglas Gregord9e15302009-11-11 19:41:09 +00001846 // If we have a template parameter pack, check every remaining template
1847 // argument against that template parameter pack.
1848 if ((*Param)->isTemplateParameterPack()) {
1849 Converted.BeginPack();
1850 for (; ArgIdx < NumArgs; ++ArgIdx) {
1851 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
1852 TemplateLoc, RAngleLoc, Converted)) {
1853 Invalid = true;
1854 break;
1855 }
1856 }
1857 Converted.EndPack();
1858 continue;
1859 }
1860
Douglas Gregorf35f8282009-11-11 21:54:23 +00001861 if (ArgIdx < NumArgs) {
1862 // Check the template argument we were given.
1863 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
1864 TemplateLoc, RAngleLoc, Converted))
1865 return true;
1866
1867 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001868 }
Douglas Gregore7526412009-11-11 19:31:23 +00001869
Douglas Gregorf35f8282009-11-11 21:54:23 +00001870 // We have a default template argument that we will use.
1871 TemplateArgumentLoc Arg;
1872
1873 // Retrieve the default template argument from the template
1874 // parameter. For each kind of template parameter, we substitute the
1875 // template arguments provided thus far and any "outer" template arguments
1876 // (when the template parameter was part of a nested template) into
1877 // the default argument.
1878 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1879 if (!TTP->hasDefaultArgument()) {
1880 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1881 break;
1882 }
1883
1884 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
1885 Template,
1886 TemplateLoc,
1887 RAngleLoc,
1888 TTP,
1889 Converted);
1890 if (!ArgType)
1891 return true;
1892
1893 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
1894 ArgType);
1895 } else if (NonTypeTemplateParmDecl *NTTP
1896 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1897 if (!NTTP->hasDefaultArgument()) {
1898 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1899 break;
1900 }
1901
1902 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
1903 TemplateLoc,
1904 RAngleLoc,
1905 NTTP,
1906 Converted);
1907 if (E.isInvalid())
1908 return true;
1909
1910 Expr *Ex = E.takeAs<Expr>();
1911 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
1912 } else {
1913 TemplateTemplateParmDecl *TempParm
1914 = cast<TemplateTemplateParmDecl>(*Param);
1915
1916 if (!TempParm->hasDefaultArgument()) {
1917 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1918 break;
1919 }
1920
1921 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
1922 TemplateLoc,
1923 RAngleLoc,
1924 TempParm,
1925 Converted);
1926 if (Name.isNull())
1927 return true;
1928
1929 Arg = TemplateArgumentLoc(TemplateArgument(Name),
1930 TempParm->getDefaultArgument().getTemplateQualifierRange(),
1931 TempParm->getDefaultArgument().getTemplateNameLoc());
1932 }
1933
1934 // Introduce an instantiation record that describes where we are using
1935 // the default template argument.
1936 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
1937 Converted.getFlatArguments(),
1938 Converted.flatSize(),
1939 SourceRange(TemplateLoc, RAngleLoc));
1940
1941 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00001942 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001943 RAngleLoc, Converted))
1944 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001945 }
1946
1947 return Invalid;
1948}
1949
1950/// \brief Check a template argument against its corresponding
1951/// template type parameter.
1952///
1953/// This routine implements the semantics of C++ [temp.arg.type]. It
1954/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001955bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001956 DeclaratorInfo *ArgInfo) {
1957 assert(ArgInfo && "invalid DeclaratorInfo");
1958 QualType Arg = ArgInfo->getType();
1959
Douglas Gregorc15cb382009-02-09 23:23:08 +00001960 // C++ [temp.arg.type]p2:
1961 // A local type, a type with no linkage, an unnamed type or a type
1962 // compounded from any of these types shall not be used as a
1963 // template-argument for a template type-parameter.
1964 //
1965 // FIXME: Perform the recursive and no-linkage type checks.
1966 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00001967 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001968 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00001969 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001970 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00001971 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
1972 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1973 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
1974 << QualType(Tag, 0) << SR;
1975 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00001976 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00001977 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1978 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001979 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1980 return true;
1981 }
1982
1983 return false;
1984}
1985
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001986/// \brief Checks whether the given template argument is the address
1987/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001988bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1989 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001990 bool Invalid = false;
1991
1992 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00001993 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001994 Arg = Cast->getSubExpr();
1995
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001996 // C++0x allows nullptr, and there's no further checking to be done for that.
1997 if (Arg->getType()->isNullPtrType())
1998 return false;
1999
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002000 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002001 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002002 // A template-argument for a non-type, non-template
2003 // template-parameter shall be one of: [...]
2004 //
2005 // -- the address of an object or function with external
2006 // linkage, including function templates and function
2007 // template-ids but excluding non-static class members,
2008 // expressed as & id-expression where the & is optional if
2009 // the name refers to a function or array, or if the
2010 // corresponding template-parameter is a reference; or
2011 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002013 // Ignore (and complain about) any excess parentheses.
2014 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2015 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002016 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002017 diag::err_template_arg_extra_parens)
2018 << Arg->getSourceRange();
2019 Invalid = true;
2020 }
2021
2022 Arg = Parens->getSubExpr();
2023 }
2024
2025 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2026 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2027 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2028 } else
2029 DRE = dyn_cast<DeclRefExpr>(Arg);
2030
2031 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00002032 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002033 diag::err_template_arg_not_object_or_func_form)
2034 << Arg->getSourceRange();
2035
2036 // Cannot refer to non-static data members
2037 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2038 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2039 << Field << Arg->getSourceRange();
2040
2041 // Cannot refer to non-static member functions
2042 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2043 if (!Method->isStatic())
Mike Stump1eb44332009-09-09 15:08:12 +00002044 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002045 diag::err_template_arg_method)
2046 << Method << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002048 // Functions must have external linkage.
2049 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2050 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump1eb44332009-09-09 15:08:12 +00002051 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002052 diag::err_template_arg_function_not_extern)
2053 << Func << Arg->getSourceRange();
2054 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2055 << true;
2056 return true;
2057 }
2058
2059 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002060 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002061 return Invalid;
2062 }
2063
2064 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2065 if (!Var->hasGlobalStorage()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002066 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002067 diag::err_template_arg_object_not_extern)
2068 << Var << Arg->getSourceRange();
2069 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2070 << true;
2071 return true;
2072 }
2073
2074 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002075 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002076 return Invalid;
2077 }
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002079 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002080 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002081 diag::err_template_arg_not_object_or_func)
2082 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002083 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002084 diag::note_template_arg_refers_here);
2085 return true;
2086}
2087
2088/// \brief Checks whether the given template argument is a pointer to
2089/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002090bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2091 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002092 bool Invalid = false;
2093
2094 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002095 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002096 Arg = Cast->getSubExpr();
2097
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002098 // C++0x allows nullptr, and there's no further checking to be done for that.
2099 if (Arg->getType()->isNullPtrType())
2100 return false;
2101
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002102 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002103 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002104 // A template-argument for a non-type, non-template
2105 // template-parameter shall be one of: [...]
2106 //
2107 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002108 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002109
2110 // Ignore (and complain about) any excess parentheses.
2111 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2112 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002113 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002114 diag::err_template_arg_extra_parens)
2115 << Arg->getSourceRange();
2116 Invalid = true;
2117 }
2118
2119 Arg = Parens->getSubExpr();
2120 }
2121
Douglas Gregorcaddba02009-11-12 18:38:13 +00002122 // A pointer-to-member constant written &Class::member.
2123 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002124 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2125 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2126 if (DRE && !DRE->getQualifier())
2127 DRE = 0;
2128 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002129 }
2130 // A constant of pointer-to-member type.
2131 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2132 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2133 if (VD->getType()->isMemberPointerType()) {
2134 if (isa<NonTypeTemplateParmDecl>(VD) ||
2135 (isa<VarDecl>(VD) &&
2136 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2137 if (Arg->isTypeDependent() || Arg->isValueDependent())
2138 Converted = TemplateArgument(Arg->Retain());
2139 else
2140 Converted = TemplateArgument(VD->getCanonicalDecl());
2141 return Invalid;
2142 }
2143 }
2144 }
2145
2146 DRE = 0;
2147 }
2148
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002149 if (!DRE)
2150 return Diag(Arg->getSourceRange().getBegin(),
2151 diag::err_template_arg_not_pointer_to_member_form)
2152 << Arg->getSourceRange();
2153
2154 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2155 assert((isa<FieldDecl>(DRE->getDecl()) ||
2156 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2157 "Only non-static member pointers can make it here");
2158
2159 // Okay: this is the address of a non-static member, and therefore
2160 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002161 if (Arg->isTypeDependent() || Arg->isValueDependent())
2162 Converted = TemplateArgument(Arg->Retain());
2163 else
2164 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002165 return Invalid;
2166 }
2167
2168 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002169 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002170 diag::err_template_arg_not_pointer_to_member_form)
2171 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002172 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002173 diag::note_template_arg_refers_here);
2174 return true;
2175}
2176
Douglas Gregorc15cb382009-02-09 23:23:08 +00002177/// \brief Check a template argument against its corresponding
2178/// non-type template parameter.
2179///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002180/// This routine implements the semantics of C++ [temp.arg.nontype].
2181/// It returns true if an error occurred, and false otherwise. \p
2182/// InstantiatedParamType is the type of the non-type template
2183/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002184///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002185/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002186bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002187 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002188 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002189 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2190
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002191 // If either the parameter has a dependent type or the argument is
2192 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002193 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00002194 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2195 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002196 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002197 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002198 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002199
2200 // C++ [temp.arg.nontype]p5:
2201 // The following conversions are performed on each expression used
2202 // as a non-type template-argument. If a non-type
2203 // template-argument cannot be converted to the type of the
2204 // corresponding template-parameter then the program is
2205 // ill-formed.
2206 //
2207 // -- for a non-type template-parameter of integral or
2208 // enumeration type, integral promotions (4.5) and integral
2209 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002210 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002211 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002212 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002213 // C++ [temp.arg.nontype]p1:
2214 // A template-argument for a non-type, non-template
2215 // template-parameter shall be one of:
2216 //
2217 // -- an integral constant-expression of integral or enumeration
2218 // type; or
2219 // -- the name of a non-type template-parameter; or
2220 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002221 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002222 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002223 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002224 diag::err_template_arg_not_integral_or_enumeral)
2225 << ArgType << Arg->getSourceRange();
2226 Diag(Param->getLocation(), diag::note_template_param_here);
2227 return true;
2228 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002229 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002230 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2231 << ArgType << Arg->getSourceRange();
2232 return true;
2233 }
2234
2235 // FIXME: We need some way to more easily get the unqualified form
2236 // of the types without going all the way to the
2237 // canonical type.
2238 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2239 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2240 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2241 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2242
2243 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002244 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002245 // Okay: no conversion necessary
2246 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2247 !ParamType->isEnumeralType()) {
2248 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002249 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002250 } else {
2251 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002252 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002253 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002254 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002255 Diag(Param->getLocation(), diag::note_template_param_here);
2256 return true;
2257 }
2258
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002259 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002260 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002261 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002262
2263 if (!Arg->isValueDependent()) {
2264 // Check that an unsigned parameter does not receive a negative
2265 // value.
2266 if (IntegerType->isUnsignedIntegerType()
2267 && (Value.isSigned() && Value.isNegative())) {
2268 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2269 << Value.toString(10) << Param->getType()
2270 << Arg->getSourceRange();
2271 Diag(Param->getLocation(), diag::note_template_param_here);
2272 return true;
2273 }
2274
2275 // Check that we don't overflow the template parameter type.
2276 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2277 if (Value.getActiveBits() > AllowedBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00002278 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002279 diag::err_template_arg_too_large)
2280 << Value.toString(10) << Param->getType()
2281 << Arg->getSourceRange();
2282 Diag(Param->getLocation(), diag::note_template_param_here);
2283 return true;
2284 }
2285
2286 if (Value.getBitWidth() != AllowedBits)
2287 Value.extOrTrunc(AllowedBits);
2288 Value.setIsSigned(IntegerType->isSignedIntegerType());
2289 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002290
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002291 // Add the value of this argument to the list of converted
2292 // arguments. We use the bitwidth and signedness of the template
2293 // parameter.
2294 if (Arg->isValueDependent()) {
2295 // The argument is value-dependent. Create a new
2296 // TemplateArgument with the converted expression.
2297 Converted = TemplateArgument(Arg);
2298 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002299 }
2300
John McCall833ca992009-10-29 08:12:44 +00002301 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002302 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002303 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002304 return false;
2305 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002306
Douglas Gregorb86b0572009-02-11 01:18:59 +00002307 // Handle pointer-to-function, reference-to-function, and
2308 // pointer-to-member-function all in (roughly) the same way.
2309 if (// -- For a non-type template-parameter of type pointer to
2310 // function, only the function-to-pointer conversion (4.3) is
2311 // applied. If the template-argument represents a set of
2312 // overloaded functions (or a pointer to such), the matching
2313 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002314 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002315 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002316 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002317 // -- For a non-type template-parameter of type reference to
2318 // function, no conversions apply. If the template-argument
2319 // represents a set of overloaded functions, the matching
2320 // function is selected from the set (13.4).
2321 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002322 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002323 // -- For a non-type template-parameter of type pointer to
2324 // member function, no conversions apply. If the
2325 // template-argument represents a set of overloaded member
2326 // functions, the matching member function is selected from
2327 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002328 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002329 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002330 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002331 ->isFunctionType())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002332 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002333 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002334 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002335 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2336 ParamType->isMemberPointerType())) {
2337 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002338 if (ParamType->isMemberPointerType())
2339 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2340 else
2341 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002342 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002343 ArgType = Context.getPointerType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002344 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump1eb44332009-09-09 15:08:12 +00002345 } else if (FunctionDecl *Fn
Douglas Gregora35284b2009-02-11 00:19:33 +00002346 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002347 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2348 return true;
2349
Anders Carlsson96ad5332009-10-21 17:16:23 +00002350 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00002351 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002352 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002353 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman73c39ab2009-10-20 08:27:19 +00002354 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregora35284b2009-02-11 00:19:33 +00002355 }
2356 }
2357
Mike Stump1eb44332009-09-09 15:08:12 +00002358 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002359 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002360 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002361 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002362 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002363 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002364 Diag(Param->getLocation(), diag::note_template_param_here);
2365 return true;
2366 }
Mike Stump1eb44332009-09-09 15:08:12 +00002367
Douglas Gregorcaddba02009-11-12 18:38:13 +00002368 if (ParamType->isMemberPointerType())
2369 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump1eb44332009-09-09 15:08:12 +00002370
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002371 NamedDecl *Entity = 0;
2372 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2373 return true;
2374
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002375 if (Entity)
2376 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002377 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002378 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00002379 }
2380
Chris Lattnerfe90de72009-02-20 21:37:53 +00002381 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002382 // -- for a non-type template-parameter of type pointer to
2383 // object, qualification conversions (4.4) and the
2384 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002385 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002386 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002387 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002388
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002389 if (ArgType->isNullPtrType()) {
2390 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002391 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002392 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002393 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002394 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002395 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002396
Douglas Gregorb86b0572009-02-11 01:18:59 +00002397 if (IsQualificationConversion(ArgType, ParamType)) {
2398 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002399 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002400 }
Mike Stump1eb44332009-09-09 15:08:12 +00002401
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002402 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002403 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002404 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002405 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002406 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002407 Diag(Param->getLocation(), diag::note_template_param_here);
2408 return true;
2409 }
Mike Stump1eb44332009-09-09 15:08:12 +00002410
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002411 NamedDecl *Entity = 0;
2412 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2413 return true;
2414
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002415 if (Entity)
2416 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002417 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002418 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002419 }
Mike Stump1eb44332009-09-09 15:08:12 +00002420
Ted Kremenek6217b802009-07-29 21:53:49 +00002421 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002422 // -- For a non-type template-parameter of type reference to
2423 // object, no conversions apply. The type referred to by the
2424 // reference may be more cv-qualified than the (otherwise
2425 // identical) type of the template-argument. The
2426 // template-parameter is bound directly to the
2427 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002428 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002429 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002430
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002431 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002432 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002433 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002434 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002435 << Arg->getSourceRange();
2436 Diag(Param->getLocation(), diag::note_template_param_here);
2437 return true;
2438 }
2439
Mike Stump1eb44332009-09-09 15:08:12 +00002440 unsigned ParamQuals
Douglas Gregorb86b0572009-02-11 01:18:59 +00002441 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2442 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00002443
Douglas Gregorb86b0572009-02-11 01:18:59 +00002444 if ((ParamQuals | ArgQuals) != ParamQuals) {
2445 Diag(Arg->getSourceRange().getBegin(),
2446 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002447 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002448 << Arg->getSourceRange();
2449 Diag(Param->getLocation(), diag::note_template_param_here);
2450 return true;
2451 }
Mike Stump1eb44332009-09-09 15:08:12 +00002452
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002453 NamedDecl *Entity = 0;
2454 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2455 return true;
2456
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002457 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002458 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002459 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002460 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002461
2462 // -- For a non-type template-parameter of type pointer to data
2463 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002464 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00002465 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2466
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002467 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002468 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002469 } else if (ArgType->isNullPtrType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002470 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002471 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002472 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002473 } else {
2474 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002475 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002476 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002477 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002478 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002479 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002480 }
2481
Douglas Gregorcaddba02009-11-12 18:38:13 +00002482 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002483}
2484
2485/// \brief Check a template argument against its corresponding
2486/// template template parameter.
2487///
2488/// This routine implements the semantics of C++ [temp.arg.template].
2489/// It returns true if an error occurred, and false otherwise.
2490bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00002491 const TemplateArgumentLoc &Arg) {
2492 TemplateName Name = Arg.getArgument().getAsTemplate();
2493 TemplateDecl *Template = Name.getAsTemplateDecl();
2494 if (!Template) {
2495 // Any dependent template name is fine.
2496 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2497 return false;
2498 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002499
2500 // C++ [temp.arg.template]p1:
2501 // A template-argument for a template template-parameter shall be
2502 // the name of a class template, expressed as id-expression. Only
2503 // primary class templates are considered when matching the
2504 // template template argument with the corresponding parameter;
2505 // partial specializations are not considered even if their
2506 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002507 //
2508 // Note that we also allow template template parameters here, which
2509 // will happen when we are dealing with, e.g., class template
2510 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002511 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002512 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002513 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00002514 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00002515 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00002516 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002517 << Template;
2518 }
2519
2520 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2521 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00002522 true,
2523 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00002524 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002525}
2526
Douglas Gregorddc29e12009-02-06 22:42:48 +00002527/// \brief Determine whether the given template parameter lists are
2528/// equivalent.
2529///
Mike Stump1eb44332009-09-09 15:08:12 +00002530/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00002531/// source code as part of a new template declaration.
2532///
2533/// \param Old The old template parameter list, typically found via
2534/// name lookup of the template declared with this template parameter
2535/// list.
2536///
2537/// \param Complain If true, this routine will produce a diagnostic if
2538/// the template parameter lists are not equivalent.
2539///
Douglas Gregorfb898e12009-11-12 16:20:59 +00002540/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00002541///
2542/// \param TemplateArgLoc If this source location is valid, then we
2543/// are actually checking the template parameter list of a template
2544/// argument (New) against the template parameter list of its
2545/// corresponding template template parameter (Old). We produce
2546/// slightly different diagnostics in this scenario.
2547///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002548/// \returns True if the template parameter lists are equal, false
2549/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002550bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00002551Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2552 TemplateParameterList *Old,
2553 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002554 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002555 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002556 if (Old->size() != New->size()) {
2557 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002558 unsigned NextDiag = diag::err_template_param_list_different_arity;
2559 if (TemplateArgLoc.isValid()) {
2560 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2561 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00002562 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002563 Diag(New->getTemplateLoc(), NextDiag)
2564 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00002565 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002566 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002567 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002568 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002569 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2570 }
2571
2572 return false;
2573 }
2574
2575 for (TemplateParameterList::iterator OldParm = Old->begin(),
2576 OldParmEnd = Old->end(), NewParm = New->begin();
2577 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2578 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002579 if (Complain) {
2580 unsigned NextDiag = diag::err_template_param_different_kind;
2581 if (TemplateArgLoc.isValid()) {
2582 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2583 NextDiag = diag::note_template_param_different_kind;
2584 }
2585 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002586 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002587 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002588 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00002589 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002590 return false;
2591 }
2592
2593 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2594 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002595 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00002596 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002597 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2598 // The types of non-type template parameters must agree.
2599 NonTypeTemplateParmDecl *NewNTTP
2600 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00002601
2602 // If we are matching a template template argument to a template
2603 // template parameter and one of the non-type template parameter types
2604 // is dependent, then we must wait until template instantiation time
2605 // to actually compare the arguments.
2606 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2607 (OldNTTP->getType()->isDependentType() ||
2608 NewNTTP->getType()->isDependentType()))
2609 continue;
2610
Douglas Gregorddc29e12009-02-06 22:42:48 +00002611 if (Context.getCanonicalType(OldNTTP->getType()) !=
2612 Context.getCanonicalType(NewNTTP->getType())) {
2613 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002614 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2615 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002616 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002617 diag::err_template_arg_template_params_mismatch);
2618 NextDiag = diag::note_template_nontype_parm_different_type;
2619 }
2620 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002621 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00002622 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00002623 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00002624 diag::note_template_nontype_parm_prev_declaration)
2625 << OldNTTP->getType();
2626 }
2627 return false;
2628 }
2629 } else {
2630 // The template parameter lists of template template
2631 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00002632 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00002633 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00002634 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002635 = cast<TemplateTemplateParmDecl>(*OldParm);
2636 TemplateTemplateParmDecl *NewTTP
2637 = cast<TemplateTemplateParmDecl>(*NewParm);
2638 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2639 OldTTP->getTemplateParameters(),
2640 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002641 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00002642 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002643 return false;
2644 }
2645 }
2646
2647 return true;
2648}
2649
2650/// \brief Check whether a template can be declared within this scope.
2651///
2652/// If the template declaration is valid in this scope, returns
2653/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00002654bool
Douglas Gregor05396e22009-08-25 17:23:04 +00002655Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002656 // Find the nearest enclosing declaration scope.
2657 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2658 (S->getFlags() & Scope::TemplateParamScope) != 0)
2659 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Douglas Gregorddc29e12009-02-06 22:42:48 +00002661 // C++ [temp]p2:
2662 // A template-declaration can appear only as a namespace scope or
2663 // class scope declaration.
2664 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002665 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2666 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00002667 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00002668 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Eli Friedman1503f772009-07-31 01:43:05 +00002670 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002671 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002672
2673 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2674 return false;
2675
Mike Stump1eb44332009-09-09 15:08:12 +00002676 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002677 diag::err_template_outside_namespace_or_class_scope)
2678 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002679}
Douglas Gregorcc636682009-02-17 23:15:12 +00002680
Douglas Gregord5cb8762009-10-07 00:13:32 +00002681/// \brief Determine what kind of template specialization the given declaration
2682/// is.
2683static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2684 if (!D)
2685 return TSK_Undeclared;
2686
Douglas Gregorf6b11852009-10-08 15:14:33 +00002687 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2688 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00002689 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2690 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002691 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2692 return Var->getTemplateSpecializationKind();
2693
Douglas Gregord5cb8762009-10-07 00:13:32 +00002694 return TSK_Undeclared;
2695}
2696
Douglas Gregor9302da62009-10-14 23:50:59 +00002697/// \brief Check whether a specialization is well-formed in the current
2698/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00002699///
Douglas Gregor9302da62009-10-14 23:50:59 +00002700/// This routine determines whether a template specialization can be declared
2701/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002702///
2703/// \param S the semantic analysis object for which this check is being
2704/// performed.
2705///
2706/// \param Specialized the entity being specialized or instantiated, which
2707/// may be a kind of template (class template, function template, etc.) or
2708/// a member of a class template (member function, static data member,
2709/// member class).
2710///
2711/// \param PrevDecl the previous declaration of this entity, if any.
2712///
2713/// \param Loc the location of the explicit specialization or instantiation of
2714/// this entity.
2715///
2716/// \param IsPartialSpecialization whether this is a partial specialization of
2717/// a class template.
2718///
Douglas Gregord5cb8762009-10-07 00:13:32 +00002719/// \returns true if there was an error that we cannot recover from, false
2720/// otherwise.
2721static bool CheckTemplateSpecializationScope(Sema &S,
2722 NamedDecl *Specialized,
2723 NamedDecl *PrevDecl,
2724 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00002725 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002726 // Keep these "kind" numbers in sync with the %select statements in the
2727 // various diagnostics emitted by this routine.
2728 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002729 bool isTemplateSpecialization = false;
2730 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002731 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002732 isTemplateSpecialization = true;
2733 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002734 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002735 isTemplateSpecialization = true;
2736 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00002737 EntityKind = 3;
2738 else if (isa<VarDecl>(Specialized))
2739 EntityKind = 4;
2740 else if (isa<RecordDecl>(Specialized))
2741 EntityKind = 5;
2742 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00002743 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2744 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00002745 return true;
2746 }
2747
Douglas Gregor88b70942009-02-25 22:02:03 +00002748 // C++ [temp.expl.spec]p2:
2749 // An explicit specialization shall be declared in the namespace
2750 // of which the template is a member, or, for member templates, in
2751 // the namespace of which the enclosing class or enclosing class
2752 // template is a member. An explicit specialization of a member
2753 // function, member class or static data member of a class
2754 // template shall be declared in the namespace of which the class
2755 // template is a member. Such a declaration may also be a
2756 // definition. If the declaration is not a definition, the
2757 // specialization may be defined later in the name- space in which
2758 // the explicit specialization was declared, or in a namespace
2759 // that encloses the one in which the explicit specialization was
2760 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00002761 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2762 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00002763 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00002764 return true;
2765 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002766
Douglas Gregor0a407472009-10-07 17:30:37 +00002767 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2768 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00002769 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00002770 return true;
2771 }
2772
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002773 // C++ [temp.class.spec]p6:
2774 // A class template partial specialization may be declared or redeclared
2775 // in any namespace scope in which its definition may be defined (14.5.1
2776 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002777 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002778 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00002779 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002780 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00002781 if ((!PrevDecl ||
2782 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2783 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2784 // There is no prior declaration of this entity, so this
2785 // specialization must be in the same context as the template
2786 // itself.
2787 if (!DC->Equals(SpecializedContext)) {
2788 if (isa<TranslationUnitDecl>(SpecializedContext))
2789 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2790 << EntityKind << Specialized;
2791 else if (isa<NamespaceDecl>(SpecializedContext))
2792 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2793 << EntityKind << Specialized
2794 << cast<NamedDecl>(SpecializedContext);
2795
2796 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2797 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002798 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002799 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00002800
2801 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00002802 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00002803 // Note that HandleDeclarator() performs this check for explicit
2804 // specializations of function templates, static data members, and member
2805 // functions, so we skip the check here for those kinds of entities.
2806 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002807 // Should we refactor that check, so that it occurs later?
2808 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00002809 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2810 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002811 if (isa<TranslationUnitDecl>(SpecializedContext))
2812 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2813 << EntityKind << Specialized;
2814 else if (isa<NamespaceDecl>(SpecializedContext))
2815 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2816 << EntityKind << Specialized
2817 << cast<NamedDecl>(SpecializedContext);
2818
Douglas Gregor9302da62009-10-14 23:50:59 +00002819 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00002820 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00002821
2822 // FIXME: check for specialization-after-instantiation errors and such.
2823
Douglas Gregor88b70942009-02-25 22:02:03 +00002824 return false;
2825}
Douglas Gregord5cb8762009-10-07 00:13:32 +00002826
Douglas Gregore94866f2009-06-12 21:21:02 +00002827/// \brief Check the non-type template arguments of a class template
2828/// partial specialization according to C++ [temp.class.spec]p9.
2829///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002830/// \param TemplateParams the template parameters of the primary class
2831/// template.
2832///
2833/// \param TemplateArg the template arguments of the class template
2834/// partial specialization.
2835///
2836/// \param MirrorsPrimaryTemplate will be set true if the class
2837/// template partial specialization arguments are identical to the
2838/// implicit template arguments of the primary template. This is not
2839/// necessarily an error (C++0x), and it is left to the caller to diagnose
2840/// this condition when it is an error.
2841///
Douglas Gregore94866f2009-06-12 21:21:02 +00002842/// \returns true if there was an error, false otherwise.
2843bool Sema::CheckClassTemplatePartialSpecializationArgs(
2844 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002845 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002846 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002847 // FIXME: the interface to this function will have to change to
2848 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002849 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Anders Carlssonfb250522009-06-23 01:26:57 +00002851 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00002852
Douglas Gregore94866f2009-06-12 21:21:02 +00002853 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002854 // Determine whether the template argument list of the partial
2855 // specialization is identical to the implicit argument list of
2856 // the primary template. The caller may need to diagnostic this as
2857 // an error per C++ [temp.class.spec]p9b3.
2858 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00002859 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002860 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2861 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002862 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002863 MirrorsPrimaryTemplate = false;
2864 } else if (TemplateTemplateParmDecl *TTP
2865 = dyn_cast<TemplateTemplateParmDecl>(
2866 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00002867 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00002868 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00002869 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002870 if (!ArgDecl ||
2871 ArgDecl->getIndex() != TTP->getIndex() ||
2872 ArgDecl->getDepth() != TTP->getDepth())
2873 MirrorsPrimaryTemplate = false;
2874 }
2875 }
2876
Mike Stump1eb44332009-09-09 15:08:12 +00002877 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00002878 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002879 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002880 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002881 }
2882
Anders Carlsson6360be72009-06-13 18:20:51 +00002883 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002884 if (!ArgExpr) {
2885 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002886 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002887 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002888
2889 // C++ [temp.class.spec]p8:
2890 // A non-type argument is non-specialized if it is the name of a
2891 // non-type parameter. All other non-type arguments are
2892 // specialized.
2893 //
2894 // Below, we check the two conditions that only apply to
2895 // specialized non-type arguments, so skip any non-specialized
2896 // arguments.
2897 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00002898 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002899 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002900 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002901 (Param->getIndex() != NTTP->getIndex() ||
2902 Param->getDepth() != NTTP->getDepth()))
2903 MirrorsPrimaryTemplate = false;
2904
Douglas Gregore94866f2009-06-12 21:21:02 +00002905 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002906 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002907
2908 // C++ [temp.class.spec]p9:
2909 // Within the argument list of a class template partial
2910 // specialization, the following restrictions apply:
2911 // -- A partially specialized non-type argument expression
2912 // shall not involve a template parameter of the partial
2913 // specialization except when the argument expression is a
2914 // simple identifier.
2915 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002916 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00002917 diag::err_dependent_non_type_arg_in_partial_spec)
2918 << ArgExpr->getSourceRange();
2919 return true;
2920 }
2921
2922 // -- The type of a template parameter corresponding to a
2923 // specialized non-type argument shall not be dependent on a
2924 // parameter of the specialization.
2925 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002926 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00002927 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2928 << Param->getType()
2929 << ArgExpr->getSourceRange();
2930 Diag(Param->getLocation(), diag::note_template_param_here);
2931 return true;
2932 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002933
2934 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002935 }
2936
2937 return false;
2938}
2939
Douglas Gregor212e81c2009-03-25 00:13:59 +00002940Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00002941Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2942 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00002943 SourceLocation KWLoc,
Douglas Gregorcc636682009-02-17 23:15:12 +00002944 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002945 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002946 SourceLocation TemplateNameLoc,
2947 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002948 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002949 SourceLocation RAngleLoc,
2950 AttributeList *Attr,
2951 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002952 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00002953
Douglas Gregorcc636682009-02-17 23:15:12 +00002954 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002955 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00002956 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00002957 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
2958
2959 if (!ClassTemplate) {
2960 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
2961 << (Name.getAsTemplateDecl() &&
2962 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
2963 return true;
2964 }
Douglas Gregorcc636682009-02-17 23:15:12 +00002965
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002966 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002967 bool isPartialSpecialization = false;
2968
Douglas Gregor88b70942009-02-25 22:02:03 +00002969 // Check the validity of the template headers that introduce this
2970 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002971 // FIXME: We probably shouldn't complain about these headers for
2972 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00002973 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00002974 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2975 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002976 TemplateParameterLists.size(),
2977 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00002978 if (TemplateParams && TemplateParams->size() > 0) {
2979 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002980
Douglas Gregor05396e22009-08-25 17:23:04 +00002981 // C++ [temp.class.spec]p10:
2982 // The template parameter list of a specialization shall not
2983 // contain default template argument values.
2984 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2985 Decl *Param = TemplateParams->getParam(I);
2986 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2987 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002988 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002989 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00002990 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00002991 }
2992 } else if (NonTypeTemplateParmDecl *NTTP
2993 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2994 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002995 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002996 diag::err_default_arg_in_partial_spec)
2997 << DefArg->getSourceRange();
2998 NTTP->setDefaultArgument(0);
2999 DefArg->Destroy(Context);
3000 }
3001 } else {
3002 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003003 if (TTP->hasDefaultArgument()) {
3004 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003005 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003006 << TTP->getDefaultArgument().getSourceRange();
3007 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003008 }
3009 }
3010 }
Douglas Gregora735b202009-10-13 14:39:41 +00003011 } else if (TemplateParams) {
3012 if (TUK == TUK_Friend)
3013 Diag(KWLoc, diag::err_template_spec_friend)
3014 << CodeModificationHint::CreateRemoval(
3015 SourceRange(TemplateParams->getTemplateLoc(),
3016 TemplateParams->getRAngleLoc()))
3017 << SourceRange(LAngleLoc, RAngleLoc);
3018 else
3019 isExplicitSpecialization = true;
3020 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003021 Diag(KWLoc, diag::err_template_spec_needs_header)
3022 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003023 isExplicitSpecialization = true;
3024 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003025
Douglas Gregorcc636682009-02-17 23:15:12 +00003026 // Check that the specialization uses the same tag kind as the
3027 // original template.
3028 TagDecl::TagKind Kind;
3029 switch (TagSpec) {
3030 default: assert(0 && "Unknown tag type!");
3031 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3032 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3033 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3034 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003035 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003036 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003037 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003038 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003039 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003040 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003041 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003042 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003043 diag::note_previous_use);
3044 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3045 }
3046
Douglas Gregor40808ce2009-03-09 23:48:35 +00003047 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00003048 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor314b97f2009-11-10 19:49:08 +00003049 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003050
Douglas Gregorcc636682009-02-17 23:15:12 +00003051 // Check that the template argument list is well-formed for this
3052 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003053 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3054 TemplateArgs.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003055 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00003056 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00003057 RAngleLoc, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003058 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003059
Mike Stump1eb44332009-09-09 15:08:12 +00003060 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003061 ClassTemplate->getTemplateParameters()->size()) &&
3062 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003063
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003064 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003065 // corresponds to these arguments.
3066 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003067 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003068 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003069 if (CheckClassTemplatePartialSpecializationArgs(
3070 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003071 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003072 return true;
3073
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003074 if (MirrorsPrimaryTemplate) {
3075 // C++ [temp.class.spec]p9b3:
3076 //
Mike Stump1eb44332009-09-09 15:08:12 +00003077 // -- The argument list of the specialization shall not be identical
3078 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003079 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003080 << (TUK == TUK_Definition)
Mike Stump1eb44332009-09-09 15:08:12 +00003081 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003082 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003083 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003084 ClassTemplate->getIdentifier(),
3085 TemplateNameLoc,
3086 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003087 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003088 AS_none);
3089 }
3090
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003091 // FIXME: Diagnose friend partial specializations
3092
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003093 // FIXME: Template parameter list matters, too
Mike Stump1eb44332009-09-09 15:08:12 +00003094 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003095 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003096 Converted.flatSize(),
3097 Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003098 } else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003099 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003100 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003101 Converted.flatSize(),
3102 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003103 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003104 ClassTemplateSpecializationDecl *PrevDecl = 0;
3105
3106 if (isPartialSpecialization)
3107 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003108 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003109 InsertPos);
3110 else
3111 PrevDecl
3112 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003113
3114 ClassTemplateSpecializationDecl *Specialization = 0;
3115
Douglas Gregor88b70942009-02-25 22:02:03 +00003116 // Check whether we can declare a class template specialization in
3117 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003118 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003119 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003120 TemplateNameLoc,
3121 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003122 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003123
Douglas Gregorb88e8882009-07-30 17:40:51 +00003124 // The canonical type
3125 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003126 if (PrevDecl &&
3127 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3128 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003129 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003130 // arguments was referenced but not declared, or we're only
3131 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003132 // declaration node as our own, updating its source location to
3133 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003134 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003135 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003136 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003137 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003138 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003139 // Build the canonical type that describes the converted template
3140 // arguments of the class template partial specialization.
3141 CanonType = Context.getTemplateSpecializationType(
3142 TemplateName(ClassTemplate),
3143 Converted.getFlatArguments(),
3144 Converted.flatSize());
3145
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003146 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003147 ClassTemplatePartialSpecializationDecl *PrevPartial
3148 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00003149 ClassTemplatePartialSpecializationDecl *Partial
3150 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003151 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003152 TemplateNameLoc,
3153 TemplateParams,
3154 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003155 Converted,
John McCall833ca992009-10-29 08:12:44 +00003156 TemplateArgs.data(),
3157 TemplateArgs.size(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003158 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003159
3160 if (PrevPartial) {
3161 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3162 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3163 } else {
3164 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3165 }
3166 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003167
Douglas Gregored9c0f92009-10-29 00:04:11 +00003168 // If we are providing an explicit specialization of a member class
3169 // template specialization, make a note of that.
3170 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3171 PrevPartial->setMemberSpecialization();
3172
Douglas Gregor031a5882009-06-13 00:26:55 +00003173 // Check that all of the template parameters of the class template
3174 // partial specialization are deducible from the template
3175 // arguments. If not, this class template partial specialization
3176 // will never be used.
3177 llvm::SmallVector<bool, 8> DeducibleParams;
3178 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003179 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003180 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003181 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003182 unsigned NumNonDeducible = 0;
3183 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3184 if (!DeducibleParams[I])
3185 ++NumNonDeducible;
3186
3187 if (NumNonDeducible) {
3188 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3189 << (NumNonDeducible > 1)
3190 << SourceRange(TemplateNameLoc, RAngleLoc);
3191 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3192 if (!DeducibleParams[I]) {
3193 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3194 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003195 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003196 diag::note_partial_spec_unused_parameter)
3197 << Param->getDeclName();
3198 else
Mike Stump1eb44332009-09-09 15:08:12 +00003199 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003200 diag::note_partial_spec_unused_parameter)
3201 << std::string("<anonymous>");
3202 }
3203 }
3204 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003205 } else {
3206 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003207 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003208 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003209 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorcc636682009-02-17 23:15:12 +00003210 ClassTemplate->getDeclContext(),
3211 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003212 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003213 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003214 PrevDecl);
3215
3216 if (PrevDecl) {
3217 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3218 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3219 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003220 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003221 InsertPos);
3222 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003223
3224 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003225 }
3226
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003227 // C++ [temp.expl.spec]p6:
3228 // If a template, a member template or the member of a class template is
3229 // explicitly specialized then that specialization shall be declared
3230 // before the first use of that specialization that would cause an implicit
3231 // instantiation to take place, in every translation unit in which such a
3232 // use occurs; no diagnostic is required.
3233 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3234 SourceRange Range(TemplateNameLoc, RAngleLoc);
3235 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3236 << Context.getTypeDeclType(Specialization) << Range;
3237
3238 Diag(PrevDecl->getPointOfInstantiation(),
3239 diag::note_instantiation_required_here)
3240 << (PrevDecl->getTemplateSpecializationKind()
3241 != TSK_ImplicitInstantiation);
3242 return true;
3243 }
3244
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003245 // If this is not a friend, note that this is an explicit specialization.
3246 if (TUK != TUK_Friend)
3247 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003248
3249 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003250 if (TUK == TUK_Definition) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003251 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003252 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003253 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003254 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003255 Diag(Def->getLocation(), diag::note_previous_definition);
3256 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003257 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003258 }
3259 }
3260
Douglas Gregorfc705b82009-02-26 22:19:44 +00003261 // Build the fully-sugared type for this class template
3262 // specialization as the user wrote in the specialization
3263 // itself. This means that we'll pretty-print the type retrieved
3264 // from the specialization's declaration the way that the user
3265 // actually wrote the specialization, rather than formatting the
3266 // name based on the "canonical" representation used to store the
3267 // template arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003268 QualType WrittenTy
3269 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00003270 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00003271 TemplateArgs.size(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00003272 CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003273 if (TUK != TUK_Friend)
3274 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003275 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003276
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003277 // C++ [temp.expl.spec]p9:
3278 // A template explicit specialization is in the scope of the
3279 // namespace in which the template was defined.
3280 //
3281 // We actually implement this paragraph where we set the semantic
3282 // context (in the creation of the ClassTemplateSpecializationDecl),
3283 // but we also maintain the lexical context where the actual
3284 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003285 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003286
Douglas Gregorcc636682009-02-17 23:15:12 +00003287 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003288 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003289 Specialization->startDefinition();
3290
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003291 if (TUK == TUK_Friend) {
3292 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3293 TemplateNameLoc,
3294 WrittenTy.getTypePtr(),
3295 /*FIXME:*/KWLoc);
3296 Friend->setAccess(AS_public);
3297 CurContext->addDecl(Friend);
3298 } else {
3299 // Add the specialization into its lexical context, so that it can
3300 // be seen when iterating through the list of declarations in that
3301 // context. However, specializations are not found by name lookup.
3302 CurContext->addDecl(Specialization);
3303 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003304 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003305}
Douglas Gregord57959a2009-03-27 23:10:48 +00003306
Mike Stump1eb44332009-09-09 15:08:12 +00003307Sema::DeclPtrTy
3308Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003309 MultiTemplateParamsArg TemplateParameterLists,
3310 Declarator &D) {
3311 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3312}
3313
Mike Stump1eb44332009-09-09 15:08:12 +00003314Sema::DeclPtrTy
3315Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003316 MultiTemplateParamsArg TemplateParameterLists,
3317 Declarator &D) {
3318 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3319 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3320 "Not a function declarator!");
3321 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003322
Douglas Gregor52591bf2009-06-24 00:54:41 +00003323 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003324 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003325 }
Mike Stump1eb44332009-09-09 15:08:12 +00003326
Douglas Gregor52591bf2009-06-24 00:54:41 +00003327 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003328
3329 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003330 move(TemplateParameterLists),
3331 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003332 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003333 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003334 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003335 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003336 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3337 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00003338 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00003339}
3340
Douglas Gregor454885e2009-10-15 15:54:05 +00003341/// \brief Diagnose cases where we have an explicit template specialization
3342/// before/after an explicit template instantiation, producing diagnostics
3343/// for those cases where they are required and determining whether the
3344/// new specialization/instantiation will have any effect.
3345///
Douglas Gregor454885e2009-10-15 15:54:05 +00003346/// \param NewLoc the location of the new explicit specialization or
3347/// instantiation.
3348///
3349/// \param NewTSK the kind of the new explicit specialization or instantiation.
3350///
3351/// \param PrevDecl the previous declaration of the entity.
3352///
3353/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3354///
3355/// \param PrevPointOfInstantiation if valid, indicates where the previus
3356/// declaration was instantiated (either implicitly or explicitly).
3357///
3358/// \param SuppressNew will be set to true to indicate that the new
3359/// specialization or instantiation has no effect and should be ignored.
3360///
3361/// \returns true if there was an error that should prevent the introduction of
3362/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00003363bool
3364Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3365 TemplateSpecializationKind NewTSK,
3366 NamedDecl *PrevDecl,
3367 TemplateSpecializationKind PrevTSK,
3368 SourceLocation PrevPointOfInstantiation,
3369 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003370 SuppressNew = false;
3371
3372 switch (NewTSK) {
3373 case TSK_Undeclared:
3374 case TSK_ImplicitInstantiation:
3375 assert(false && "Don't check implicit instantiations here");
3376 return false;
3377
3378 case TSK_ExplicitSpecialization:
3379 switch (PrevTSK) {
3380 case TSK_Undeclared:
3381 case TSK_ExplicitSpecialization:
3382 // Okay, we're just specializing something that is either already
3383 // explicitly specialized or has merely been mentioned without any
3384 // instantiation.
3385 return false;
3386
3387 case TSK_ImplicitInstantiation:
3388 if (PrevPointOfInstantiation.isInvalid()) {
3389 // The declaration itself has not actually been instantiated, so it is
3390 // still okay to specialize it.
3391 return false;
3392 }
3393 // Fall through
3394
3395 case TSK_ExplicitInstantiationDeclaration:
3396 case TSK_ExplicitInstantiationDefinition:
3397 assert((PrevTSK == TSK_ImplicitInstantiation ||
3398 PrevPointOfInstantiation.isValid()) &&
3399 "Explicit instantiation without point of instantiation?");
3400
3401 // C++ [temp.expl.spec]p6:
3402 // If a template, a member template or the member of a class template
3403 // is explicitly specialized then that specialization shall be declared
3404 // before the first use of that specialization that would cause an
3405 // implicit instantiation to take place, in every translation unit in
3406 // which such a use occurs; no diagnostic is required.
Douglas Gregor0d035142009-10-27 18:42:08 +00003407 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00003408 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003409 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00003410 << (PrevTSK != TSK_ImplicitInstantiation);
3411
3412 return true;
3413 }
3414 break;
3415
3416 case TSK_ExplicitInstantiationDeclaration:
3417 switch (PrevTSK) {
3418 case TSK_ExplicitInstantiationDeclaration:
3419 // This explicit instantiation declaration is redundant (that's okay).
3420 SuppressNew = true;
3421 return false;
3422
3423 case TSK_Undeclared:
3424 case TSK_ImplicitInstantiation:
3425 // We're explicitly instantiating something that may have already been
3426 // implicitly instantiated; that's fine.
3427 return false;
3428
3429 case TSK_ExplicitSpecialization:
3430 // C++0x [temp.explicit]p4:
3431 // For a given set of template parameters, if an explicit instantiation
3432 // of a template appears after a declaration of an explicit
3433 // specialization for that template, the explicit instantiation has no
3434 // effect.
3435 return false;
3436
3437 case TSK_ExplicitInstantiationDefinition:
3438 // C++0x [temp.explicit]p10:
3439 // If an entity is the subject of both an explicit instantiation
3440 // declaration and an explicit instantiation definition in the same
3441 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00003442 Diag(NewLoc,
3443 diag::err_explicit_instantiation_declaration_after_definition);
3444 Diag(PrevPointOfInstantiation,
3445 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00003446 assert(PrevPointOfInstantiation.isValid() &&
3447 "Explicit instantiation without point of instantiation?");
3448 SuppressNew = true;
3449 return false;
3450 }
3451 break;
3452
3453 case TSK_ExplicitInstantiationDefinition:
3454 switch (PrevTSK) {
3455 case TSK_Undeclared:
3456 case TSK_ImplicitInstantiation:
3457 // We're explicitly instantiating something that may have already been
3458 // implicitly instantiated; that's fine.
3459 return false;
3460
3461 case TSK_ExplicitSpecialization:
3462 // C++ DR 259, C++0x [temp.explicit]p4:
3463 // For a given set of template parameters, if an explicit
3464 // instantiation of a template appears after a declaration of
3465 // an explicit specialization for that template, the explicit
3466 // instantiation has no effect.
3467 //
3468 // In C++98/03 mode, we only give an extension warning here, because it
3469 // is not not harmful to try to explicitly instantiate something that
3470 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00003471 if (!getLangOptions().CPlusPlus0x) {
3472 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00003473 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003474 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00003475 diag::note_previous_template_specialization);
3476 }
3477 SuppressNew = true;
3478 return false;
3479
3480 case TSK_ExplicitInstantiationDeclaration:
3481 // We're explicity instantiating a definition for something for which we
3482 // were previously asked to suppress instantiations. That's fine.
3483 return false;
3484
3485 case TSK_ExplicitInstantiationDefinition:
3486 // C++0x [temp.spec]p5:
3487 // For a given template and a given set of template-arguments,
3488 // - an explicit instantiation definition shall appear at most once
3489 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00003490 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00003491 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003492 Diag(PrevPointOfInstantiation,
3493 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00003494 SuppressNew = true;
3495 return false;
3496 }
3497 break;
3498 }
3499
3500 assert(false && "Missing specialization/instantiation case?");
3501
3502 return false;
3503}
3504
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003505/// \brief Perform semantic analysis for the given function template
3506/// specialization.
3507///
3508/// This routine performs all of the semantic analysis required for an
3509/// explicit function template specialization. On successful completion,
3510/// the function declaration \p FD will become a function template
3511/// specialization.
3512///
3513/// \param FD the function declaration, which will be updated to become a
3514/// function template specialization.
3515///
3516/// \param HasExplicitTemplateArgs whether any template arguments were
3517/// explicitly provided.
3518///
3519/// \param LAngleLoc the location of the left angle bracket ('<'), if
3520/// template arguments were explicitly provided.
3521///
3522/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3523/// if any.
3524///
3525/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3526/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3527/// true as in, e.g., \c void sort<>(char*, char*);
3528///
3529/// \param RAngleLoc the location of the right angle bracket ('>'), if
3530/// template arguments were explicitly provided.
3531///
3532/// \param PrevDecl the set of declarations that
3533bool
3534Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3535 bool HasExplicitTemplateArgs,
3536 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00003537 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003538 unsigned NumExplicitTemplateArgs,
3539 SourceLocation RAngleLoc,
3540 NamedDecl *&PrevDecl) {
3541 // The set of function template specializations that could match this
3542 // explicit function template specialization.
3543 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3544 CandidateSet Candidates;
3545
3546 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3547 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3548 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3549 // Only consider templates found within the same semantic lookup scope as
3550 // FD.
3551 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3552 continue;
3553
3554 // C++ [temp.expl.spec]p11:
3555 // A trailing template-argument can be left unspecified in the
3556 // template-id naming an explicit function template specialization
3557 // provided it can be deduced from the function argument type.
3558 // Perform template argument deduction to determine whether we may be
3559 // specializing this template.
3560 // FIXME: It is somewhat wasteful to build
3561 TemplateDeductionInfo Info(Context);
3562 FunctionDecl *Specialization = 0;
3563 if (TemplateDeductionResult TDK
3564 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3565 ExplicitTemplateArgs,
3566 NumExplicitTemplateArgs,
3567 FD->getType(),
3568 Specialization,
3569 Info)) {
3570 // FIXME: Template argument deduction failed; record why it failed, so
3571 // that we can provide nifty diagnostics.
3572 (void)TDK;
3573 continue;
3574 }
3575
3576 // Record this candidate.
3577 Candidates.push_back(Specialization);
3578 }
3579 }
3580
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003581 // Find the most specialized function template.
3582 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3583 Candidates.size(),
3584 TPOC_Other,
3585 FD->getLocation(),
3586 PartialDiagnostic(diag::err_function_template_spec_no_match)
3587 << FD->getDeclName(),
3588 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3589 << FD->getDeclName() << HasExplicitTemplateArgs,
3590 PartialDiagnostic(diag::note_function_template_spec_matched));
3591 if (!Specialization)
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003592 return true;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003593
3594 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003595 // If so, we have run afoul of .
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003596
Douglas Gregord5cb8762009-10-07 00:13:32 +00003597 // Check the scope of this explicit specialization.
3598 if (CheckTemplateSpecializationScope(*this,
3599 Specialization->getPrimaryTemplate(),
3600 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003601 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003602 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003603
3604 // C++ [temp.expl.spec]p6:
3605 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00003606 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003607 // before the first use of that specialization that would cause an implicit
3608 // instantiation to take place, in every translation unit in which such a
3609 // use occurs; no diagnostic is required.
3610 FunctionTemplateSpecializationInfo *SpecInfo
3611 = Specialization->getTemplateSpecializationInfo();
3612 assert(SpecInfo && "Function template specialization info missing?");
3613 if (SpecInfo->getPointOfInstantiation().isValid()) {
3614 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3615 << FD;
3616 Diag(SpecInfo->getPointOfInstantiation(),
3617 diag::note_instantiation_required_here)
3618 << (Specialization->getTemplateSpecializationKind()
3619 != TSK_ImplicitInstantiation);
3620 return true;
3621 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003622
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003623 // Mark the prior declaration as an explicit specialization, so that later
3624 // clients know that this is an explicit specialization.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003625 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003626
3627 // Turn the given function declaration into a function template
3628 // specialization, with the template arguments from the previous
3629 // specialization.
3630 FD->setFunctionTemplateSpecialization(Context,
3631 Specialization->getPrimaryTemplate(),
3632 new (Context) TemplateArgumentList(
3633 *Specialization->getTemplateSpecializationArgs()),
3634 /*InsertPos=*/0,
3635 TSK_ExplicitSpecialization);
3636
3637 // The "previous declaration" for this function template specialization is
3638 // the prior function template specialization.
3639 PrevDecl = Specialization;
3640 return false;
3641}
3642
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003643/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003644/// specialization.
3645///
3646/// This routine performs all of the semantic analysis required for an
3647/// explicit member function specialization. On successful completion,
3648/// the function declaration \p FD will become a member function
3649/// specialization.
3650///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003651/// \param Member the member declaration, which will be updated to become a
3652/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003653///
3654/// \param PrevDecl the set of declarations, one of which may be specialized
3655/// by this function specialization.
3656bool
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003657Sema::CheckMemberSpecialization(NamedDecl *Member, NamedDecl *&PrevDecl) {
3658 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3659
3660 // Try to find the member we are instantiating.
3661 NamedDecl *Instantiation = 0;
3662 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003663 MemberSpecializationInfo *MSInfo = 0;
3664
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003665 if (!PrevDecl) {
3666 // Nowhere to look anyway.
3667 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3668 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3669 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl)) {
3670 if (Context.hasSameType(Function->getType(), Method->getType())) {
3671 Instantiation = Method;
3672 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003673 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003674 break;
3675 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003676 }
3677 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003678 } else if (isa<VarDecl>(Member)) {
3679 if (VarDecl *PrevVar = dyn_cast<VarDecl>(PrevDecl))
3680 if (PrevVar->isStaticDataMember()) {
3681 Instantiation = PrevDecl;
3682 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003683 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003684 }
3685 } else if (isa<RecordDecl>(Member)) {
3686 if (CXXRecordDecl *PrevRecord = dyn_cast<CXXRecordDecl>(PrevDecl)) {
3687 Instantiation = PrevDecl;
3688 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003689 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003690 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003691 }
3692
3693 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003694 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003695 // specializations are always out-of-line, the caller will complain about
3696 // this mismatch later.
3697 return false;
3698 }
3699
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003700 // Make sure that this is a specialization of a member.
3701 if (!InstantiatedFrom) {
3702 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3703 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003704 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3705 return true;
3706 }
3707
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003708 // C++ [temp.expl.spec]p6:
3709 // If a template, a member template or the member of a class template is
3710 // explicitly specialized then that spe- cialization shall be declared
3711 // before the first use of that specialization that would cause an implicit
3712 // instantiation to take place, in every translation unit in which such a
3713 // use occurs; no diagnostic is required.
3714 assert(MSInfo && "Member specialization info missing?");
3715 if (MSInfo->getPointOfInstantiation().isValid()) {
3716 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3717 << Member;
3718 Diag(MSInfo->getPointOfInstantiation(),
3719 diag::note_instantiation_required_here)
3720 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3721 return true;
3722 }
3723
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003724 // Check the scope of this explicit specialization.
3725 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003726 InstantiatedFrom,
3727 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003728 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003729 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00003730
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003731 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00003732 // the original declaration to note that it is an explicit specialization
3733 // (if it was previously an implicit instantiation). This latter step
3734 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003735 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003736 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3737 if (InstantiationFunction->getTemplateSpecializationKind() ==
3738 TSK_ImplicitInstantiation) {
3739 InstantiationFunction->setTemplateSpecializationKind(
3740 TSK_ExplicitSpecialization);
3741 InstantiationFunction->setLocation(Member->getLocation());
3742 }
3743
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003744 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3745 cast<CXXMethodDecl>(InstantiatedFrom),
3746 TSK_ExplicitSpecialization);
3747 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003748 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3749 if (InstantiationVar->getTemplateSpecializationKind() ==
3750 TSK_ImplicitInstantiation) {
3751 InstantiationVar->setTemplateSpecializationKind(
3752 TSK_ExplicitSpecialization);
3753 InstantiationVar->setLocation(Member->getLocation());
3754 }
3755
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003756 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3757 cast<VarDecl>(InstantiatedFrom),
3758 TSK_ExplicitSpecialization);
3759 } else {
3760 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00003761 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3762 if (InstantiationClass->getTemplateSpecializationKind() ==
3763 TSK_ImplicitInstantiation) {
3764 InstantiationClass->setTemplateSpecializationKind(
3765 TSK_ExplicitSpecialization);
3766 InstantiationClass->setLocation(Member->getLocation());
3767 }
3768
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003769 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00003770 cast<CXXRecordDecl>(InstantiatedFrom),
3771 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003772 }
3773
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003774 // Save the caller the trouble of having to figure out which declaration
3775 // this specialization matches.
3776 PrevDecl = Instantiation;
3777 return false;
3778}
3779
Douglas Gregor558c0322009-10-14 23:41:34 +00003780/// \brief Check the scope of an explicit instantiation.
3781static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3782 SourceLocation InstLoc,
3783 bool WasQualifiedName) {
3784 DeclContext *ExpectedContext
3785 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3786 DeclContext *CurContext = S.CurContext->getLookupContext();
3787
3788 // C++0x [temp.explicit]p2:
3789 // An explicit instantiation shall appear in an enclosing namespace of its
3790 // template.
3791 //
3792 // This is DR275, which we do not retroactively apply to C++98/03.
3793 if (S.getLangOptions().CPlusPlus0x &&
3794 !CurContext->Encloses(ExpectedContext)) {
3795 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3796 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3797 << D << NS;
3798 else
3799 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3800 << D;
3801 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3802 return;
3803 }
3804
3805 // C++0x [temp.explicit]p2:
3806 // If the name declared in the explicit instantiation is an unqualified
3807 // name, the explicit instantiation shall appear in the namespace where
3808 // its template is declared or, if that namespace is inline (7.3.1), any
3809 // namespace from its enclosing namespace set.
3810 if (WasQualifiedName)
3811 return;
3812
3813 if (CurContext->Equals(ExpectedContext))
3814 return;
3815
3816 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3817 << D << ExpectedContext;
3818 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3819}
3820
3821/// \brief Determine whether the given scope specifier has a template-id in it.
3822static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3823 if (!SS.isSet())
3824 return false;
3825
3826 // C++0x [temp.explicit]p2:
3827 // If the explicit instantiation is for a member function, a member class
3828 // or a static data member of a class template specialization, the name of
3829 // the class template specialization in the qualified-id for the member
3830 // name shall be a simple-template-id.
3831 //
3832 // C++98 has the same restriction, just worded differently.
3833 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3834 NNS; NNS = NNS->getPrefix())
3835 if (Type *T = NNS->getAsType())
3836 if (isa<TemplateSpecializationType>(T))
3837 return true;
3838
3839 return false;
3840}
3841
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003842// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00003843// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003844Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00003845Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00003846 SourceLocation ExternLoc,
3847 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003848 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003849 SourceLocation KWLoc,
3850 const CXXScopeSpec &SS,
3851 TemplateTy TemplateD,
3852 SourceLocation TemplateNameLoc,
3853 SourceLocation LAngleLoc,
3854 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003855 SourceLocation RAngleLoc,
3856 AttributeList *Attr) {
3857 // Find the class template we're specializing
3858 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003859 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003860 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3861
3862 // Check that the specialization uses the same tag kind as the
3863 // original template.
3864 TagDecl::TagKind Kind;
3865 switch (TagSpec) {
3866 default: assert(0 && "Unknown tag type!");
3867 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3868 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3869 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3870 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003871 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003872 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003873 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003874 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003875 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003876 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003877 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003878 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003879 diag::note_previous_use);
3880 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3881 }
3882
Douglas Gregor558c0322009-10-14 23:41:34 +00003883 // C++0x [temp.explicit]p2:
3884 // There are two forms of explicit instantiation: an explicit instantiation
3885 // definition and an explicit instantiation declaration. An explicit
3886 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00003887 TemplateSpecializationKind TSK
3888 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3889 : TSK_ExplicitInstantiationDeclaration;
3890
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003891 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00003892 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor314b97f2009-11-10 19:49:08 +00003893 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003894
3895 // Check that the template argument list is well-formed for this
3896 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003897 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3898 TemplateArgs.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003899 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00003900 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00003901 RAngleLoc, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003902 return true;
3903
Mike Stump1eb44332009-09-09 15:08:12 +00003904 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003905 ClassTemplate->getTemplateParameters()->size()) &&
3906 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003907
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003908 // Find the class template specialization declaration that
3909 // corresponds to these arguments.
3910 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00003911 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003912 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003913 Converted.flatSize(),
3914 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003915 void *InsertPos = 0;
3916 ClassTemplateSpecializationDecl *PrevDecl
3917 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3918
Douglas Gregord5cb8762009-10-07 00:13:32 +00003919 // C++0x [temp.explicit]p2:
3920 // [...] An explicit instantiation shall appear in an enclosing
3921 // namespace of its template. [...]
3922 //
3923 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00003924 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
3925 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00003926
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003927 ClassTemplateSpecializationDecl *Specialization = 0;
3928
3929 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003930 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00003931 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003932 PrevDecl,
3933 PrevDecl->getSpecializationKind(),
3934 PrevDecl->getPointOfInstantiation(),
3935 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003936 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003937
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003938 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00003939 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003940
Douglas Gregor52604ab2009-09-11 21:19:12 +00003941 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3942 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3943 // Since the only prior class template specialization with these
3944 // arguments was referenced but not declared, reuse that
3945 // declaration node as our own, updating its source location to
3946 // reflect our new declaration.
3947 Specialization = PrevDecl;
3948 Specialization->setLocation(TemplateNameLoc);
3949 PrevDecl = 0;
3950 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003951 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00003952
3953 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003954 // Create a new class template specialization declaration node for
3955 // this explicit specialization.
3956 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003957 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003958 ClassTemplate->getDeclContext(),
3959 TemplateNameLoc,
3960 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00003961 Converted, PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003962
Douglas Gregor52604ab2009-09-11 21:19:12 +00003963 if (PrevDecl) {
3964 // Remove the previous declaration from the folding set, since we want
3965 // to introduce a new declaration.
3966 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3967 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3968 }
3969
3970 // Insert the new specialization.
3971 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003972 }
3973
3974 // Build the fully-sugared type for this explicit instantiation as
3975 // the user wrote in the explicit instantiation itself. This means
3976 // that we'll pretty-print the type retrieved from the
3977 // specialization's declaration the way that the user actually wrote
3978 // the explicit instantiation, rather than formatting the name based
3979 // on the "canonical" representation used to store the template
3980 // arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003981 QualType WrittenTy
3982 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00003983 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003984 TemplateArgs.size(),
3985 Context.getTypeDeclType(Specialization));
3986 Specialization->setTypeAsWritten(WrittenTy);
3987 TemplateArgsIn.release();
3988
3989 // Add the explicit instantiation into its lexical context. However,
3990 // since explicit instantiations are never found by name lookup, we
3991 // just put it into the declaration context directly.
3992 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003993 CurContext->addDecl(Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003994
3995 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003996 // A definition of a class template or class member template
3997 // shall be in scope at the point of the explicit instantiation of
3998 // the class template or class member template.
3999 //
4000 // This check comes when we actually try to perform the
4001 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004002 ClassTemplateSpecializationDecl *Def
4003 = cast_or_null<ClassTemplateSpecializationDecl>(
4004 Specialization->getDefinition(Context));
4005 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004006 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor0d035142009-10-27 18:42:08 +00004007
4008 // Instantiate the members of this class template specialization.
4009 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4010 Specialization->getDefinition(Context));
4011 if (Def)
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004012 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004013
4014 return DeclPtrTy::make(Specialization);
4015}
4016
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004017// Explicit instantiation of a member class of a class template.
4018Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004019Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004020 SourceLocation ExternLoc,
4021 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004022 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004023 SourceLocation KWLoc,
4024 const CXXScopeSpec &SS,
4025 IdentifierInfo *Name,
4026 SourceLocation NameLoc,
4027 AttributeList *Attr) {
4028
Douglas Gregor402abb52009-05-28 23:31:59 +00004029 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004030 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004031 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004032 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004033 MultiTemplateParamsArg(*this, 0, 0),
4034 Owned, IsDependent);
4035 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4036
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004037 if (!TagD)
4038 return true;
4039
4040 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4041 if (Tag->isEnum()) {
4042 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4043 << Context.getTypeDeclType(Tag);
4044 return true;
4045 }
4046
Douglas Gregord0c87372009-05-27 17:30:49 +00004047 if (Tag->isInvalidDecl())
4048 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004049
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004050 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4051 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4052 if (!Pattern) {
4053 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4054 << Context.getTypeDeclType(Record);
4055 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4056 return true;
4057 }
4058
Douglas Gregor558c0322009-10-14 23:41:34 +00004059 // C++0x [temp.explicit]p2:
4060 // If the explicit instantiation is for a class or member class, the
4061 // elaborated-type-specifier in the declaration shall include a
4062 // simple-template-id.
4063 //
4064 // C++98 has the same restriction, just worded differently.
4065 if (!ScopeSpecifierHasTemplateId(SS))
4066 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4067 << Record << SS.getRange();
4068
4069 // C++0x [temp.explicit]p2:
4070 // There are two forms of explicit instantiation: an explicit instantiation
4071 // definition and an explicit instantiation declaration. An explicit
4072 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004073 TemplateSpecializationKind TSK
4074 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4075 : TSK_ExplicitInstantiationDeclaration;
4076
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004077 // C++0x [temp.explicit]p2:
4078 // [...] An explicit instantiation shall appear in an enclosing
4079 // namespace of its template. [...]
4080 //
4081 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004082 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004083
4084 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004085 CXXRecordDecl *PrevDecl
4086 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4087 if (!PrevDecl && Record->getDefinition(Context))
4088 PrevDecl = Record;
4089 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004090 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4091 bool SuppressNew = false;
4092 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004093 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004094 PrevDecl,
4095 MSInfo->getTemplateSpecializationKind(),
4096 MSInfo->getPointOfInstantiation(),
4097 SuppressNew))
4098 return true;
4099 if (SuppressNew)
4100 return TagD;
4101 }
4102
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004103 CXXRecordDecl *RecordDef
4104 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4105 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004106 // C++ [temp.explicit]p3:
4107 // A definition of a member class of a class template shall be in scope
4108 // at the point of an explicit instantiation of the member class.
4109 CXXRecordDecl *Def
4110 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4111 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004112 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4113 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004114 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4115 << Pattern;
4116 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004117 } else {
4118 if (InstantiateClass(NameLoc, Record, Def,
4119 getTemplateInstantiationArgs(Record),
4120 TSK))
4121 return true;
4122
4123 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4124 if (!RecordDef)
4125 return true;
4126 }
4127 }
4128
4129 // Instantiate all of the members of the class.
4130 InstantiateClassMembers(NameLoc, RecordDef,
4131 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004132
Mike Stump390b4cc2009-05-16 07:39:55 +00004133 // FIXME: We don't have any representation for explicit instantiations of
4134 // member classes. Such a representation is not needed for compilation, but it
4135 // should be available for clients that want to see all of the declarations in
4136 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004137 return TagD;
4138}
4139
Douglas Gregord5a423b2009-09-25 18:43:00 +00004140Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4141 SourceLocation ExternLoc,
4142 SourceLocation TemplateLoc,
4143 Declarator &D) {
4144 // Explicit instantiations always require a name.
4145 DeclarationName Name = GetNameForDeclarator(D);
4146 if (!Name) {
4147 if (!D.isInvalidType())
4148 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4149 diag::err_explicit_instantiation_requires_name)
4150 << D.getDeclSpec().getSourceRange()
4151 << D.getSourceRange();
4152
4153 return true;
4154 }
4155
4156 // The scope passed in may not be a decl scope. Zip up the scope tree until
4157 // we find one that is.
4158 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4159 (S->getFlags() & Scope::TemplateParamScope) != 0)
4160 S = S->getParent();
4161
4162 // Determine the type of the declaration.
4163 QualType R = GetTypeForDeclarator(D, S, 0);
4164 if (R.isNull())
4165 return true;
4166
4167 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4168 // Cannot explicitly instantiate a typedef.
4169 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4170 << Name;
4171 return true;
4172 }
4173
Douglas Gregor663b5a02009-10-14 20:14:33 +00004174 // C++0x [temp.explicit]p1:
4175 // [...] An explicit instantiation of a function template shall not use the
4176 // inline or constexpr specifiers.
4177 // Presumably, this also applies to member functions of class templates as
4178 // well.
4179 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4180 Diag(D.getDeclSpec().getInlineSpecLoc(),
4181 diag::err_explicit_instantiation_inline)
4182 << CodeModificationHint::CreateRemoval(
4183 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
4184
4185 // FIXME: check for constexpr specifier.
4186
Douglas Gregor558c0322009-10-14 23:41:34 +00004187 // C++0x [temp.explicit]p2:
4188 // There are two forms of explicit instantiation: an explicit instantiation
4189 // definition and an explicit instantiation declaration. An explicit
4190 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004191 TemplateSpecializationKind TSK
4192 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4193 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004194
John McCallf36e02d2009-10-09 21:13:30 +00004195 LookupResult Previous;
4196 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
4197 Name, LookupOrdinaryName);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004198
4199 if (!R->isFunctionType()) {
4200 // C++ [temp.explicit]p1:
4201 // A [...] static data member of a class template can be explicitly
4202 // instantiated from the member definition associated with its class
4203 // template.
4204 if (Previous.isAmbiguous()) {
4205 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
4206 D.getSourceRange());
4207 }
4208
John McCallf36e02d2009-10-09 21:13:30 +00004209 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4210 Previous.getAsSingleDecl(Context));
Douglas Gregord5a423b2009-09-25 18:43:00 +00004211 if (!Prev || !Prev->isStaticDataMember()) {
4212 // We expect to see a data data member here.
4213 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4214 << Name;
4215 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4216 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004217 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004218 return true;
4219 }
4220
4221 if (!Prev->getInstantiatedFromStaticDataMember()) {
4222 // FIXME: Check for explicit specialization?
4223 Diag(D.getIdentifierLoc(),
4224 diag::err_explicit_instantiation_data_member_not_instantiated)
4225 << Prev;
4226 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4227 // FIXME: Can we provide a note showing where this was declared?
4228 return true;
4229 }
4230
Douglas Gregor558c0322009-10-14 23:41:34 +00004231 // C++0x [temp.explicit]p2:
4232 // If the explicit instantiation is for a member function, a member class
4233 // or a static data member of a class template specialization, the name of
4234 // the class template specialization in the qualified-id for the member
4235 // name shall be a simple-template-id.
4236 //
4237 // C++98 has the same restriction, just worded differently.
4238 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4239 Diag(D.getIdentifierLoc(),
4240 diag::err_explicit_instantiation_without_qualified_id)
4241 << Prev << D.getCXXScopeSpec().getRange();
4242
4243 // Check the scope of this explicit instantiation.
4244 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4245
Douglas Gregor454885e2009-10-15 15:54:05 +00004246 // Verify that it is okay to explicitly instantiate here.
4247 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4248 assert(MSInfo && "Missing static data member specialization info?");
4249 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004250 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00004251 MSInfo->getTemplateSpecializationKind(),
4252 MSInfo->getPointOfInstantiation(),
4253 SuppressNew))
4254 return true;
4255 if (SuppressNew)
4256 return DeclPtrTy();
4257
Douglas Gregord5a423b2009-09-25 18:43:00 +00004258 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004259 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004260 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004261 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4262 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004263
4264 // FIXME: Create an ExplicitInstantiation node?
4265 return DeclPtrTy();
4266 }
4267
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004268 // If the declarator is a template-id, translate the parser's template
4269 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00004270 bool HasExplicitTemplateArgs = false;
John McCall833ca992009-10-29 08:12:44 +00004271 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004272 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4273 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Douglas Gregordb422df2009-09-25 21:45:23 +00004274 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4275 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00004276 TemplateId->NumArgs);
4277 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregordb422df2009-09-25 21:45:23 +00004278 TemplateArgs);
4279 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00004280 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00004281 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004282
Douglas Gregord5a423b2009-09-25 18:43:00 +00004283 // C++ [temp.explicit]p1:
4284 // A [...] function [...] can be explicitly instantiated from its template.
4285 // A member function [...] of a class template can be explicitly
4286 // instantiated from the member definition associated with its class
4287 // template.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004288 llvm::SmallVector<FunctionDecl *, 8> Matches;
4289 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4290 P != PEnd; ++P) {
4291 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00004292 if (!HasExplicitTemplateArgs) {
4293 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4294 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4295 Matches.clear();
4296 Matches.push_back(Method);
4297 break;
4298 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00004299 }
4300 }
4301
4302 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4303 if (!FunTmpl)
4304 continue;
4305
4306 TemplateDeductionInfo Info(Context);
4307 FunctionDecl *Specialization = 0;
4308 if (TemplateDeductionResult TDK
Douglas Gregordb422df2009-09-25 21:45:23 +00004309 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
4310 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004311 R, Specialization, Info)) {
4312 // FIXME: Keep track of almost-matches?
4313 (void)TDK;
4314 continue;
4315 }
4316
4317 Matches.push_back(Specialization);
4318 }
4319
4320 // Find the most specialized function template specialization.
4321 FunctionDecl *Specialization
4322 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4323 D.getIdentifierLoc(),
4324 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4325 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4326 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4327
4328 if (!Specialization)
4329 return true;
4330
Douglas Gregor0a897e32009-10-15 17:21:20 +00004331 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00004332 Diag(D.getIdentifierLoc(),
4333 diag::err_explicit_instantiation_member_function_not_instantiated)
4334 << Specialization
4335 << (Specialization->getTemplateSpecializationKind() ==
4336 TSK_ExplicitSpecialization);
4337 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4338 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00004339 }
Douglas Gregor558c0322009-10-14 23:41:34 +00004340
Douglas Gregor0a897e32009-10-15 17:21:20 +00004341 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00004342 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4343 PrevDecl = Specialization;
4344
Douglas Gregor0a897e32009-10-15 17:21:20 +00004345 if (PrevDecl) {
4346 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004347 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00004348 PrevDecl,
4349 PrevDecl->getTemplateSpecializationKind(),
4350 PrevDecl->getPointOfInstantiation(),
4351 SuppressNew))
4352 return true;
4353
4354 // FIXME: We may still want to build some representation of this
4355 // explicit specialization.
4356 if (SuppressNew)
4357 return DeclPtrTy();
4358 }
4359
4360 if (TSK == TSK_ExplicitInstantiationDefinition)
4361 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4362 false, /*DefinitionRequired=*/true);
4363
4364 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4365
Douglas Gregor558c0322009-10-14 23:41:34 +00004366 // C++0x [temp.explicit]p2:
4367 // If the explicit instantiation is for a member function, a member class
4368 // or a static data member of a class template specialization, the name of
4369 // the class template specialization in the qualified-id for the member
4370 // name shall be a simple-template-id.
4371 //
4372 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004373 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004374 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00004375 D.getCXXScopeSpec().isSet() &&
4376 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4377 Diag(D.getIdentifierLoc(),
4378 diag::err_explicit_instantiation_without_qualified_id)
4379 << Specialization << D.getCXXScopeSpec().getRange();
4380
4381 CheckExplicitInstantiationScope(*this,
4382 FunTmpl? (NamedDecl *)FunTmpl
4383 : Specialization->getInstantiatedFromMemberFunction(),
4384 D.getIdentifierLoc(),
4385 D.getCXXScopeSpec().isSet());
4386
Douglas Gregord5a423b2009-09-25 18:43:00 +00004387 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4388 return DeclPtrTy();
4389}
4390
Douglas Gregord57959a2009-03-27 23:10:48 +00004391Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00004392Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4393 const CXXScopeSpec &SS, IdentifierInfo *Name,
4394 SourceLocation TagLoc, SourceLocation NameLoc) {
4395 // This has to hold, because SS is expected to be defined.
4396 assert(Name && "Expected a name in a dependent tag");
4397
4398 NestedNameSpecifier *NNS
4399 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4400 if (!NNS)
4401 return true;
4402
4403 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4404 if (T.isNull())
4405 return true;
4406
4407 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4408 QualType ElabType = Context.getElaboratedType(T, TagKind);
4409
4410 return ElabType.getAsOpaquePtr();
4411}
4412
4413Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00004414Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4415 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004416 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00004417 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4418 if (!NNS)
4419 return true;
4420
4421 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00004422 if (T.isNull())
4423 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00004424 return T.getAsOpaquePtr();
4425}
4426
Douglas Gregor17343172009-04-01 00:28:59 +00004427Sema::TypeResult
4428Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4429 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00004430 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004431 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00004432 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00004433 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00004434 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00004435 assert(TemplateId && "Expected a template specialization type");
4436
Douglas Gregor6946baf2009-09-02 13:05:45 +00004437 if (computeDeclContext(SS, false)) {
4438 // If we can compute a declaration context, then the "typename"
4439 // keyword was superfluous. Just build a QualifiedNameType to keep
4440 // track of the nested-name-specifier.
Mike Stump1eb44332009-09-09 15:08:12 +00004441
Douglas Gregor6946baf2009-09-02 13:05:45 +00004442 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4443 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4444 }
Mike Stump1eb44332009-09-09 15:08:12 +00004445
Douglas Gregor6946baf2009-09-02 13:05:45 +00004446 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00004447}
4448
Douglas Gregord57959a2009-03-27 23:10:48 +00004449/// \brief Build the type that describes a C++ typename specifier,
4450/// e.g., "typename T::type".
4451QualType
4452Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4453 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00004454 CXXRecordDecl *CurrentInstantiation = 0;
4455 if (NNS->isDependent()) {
4456 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00004457
Douglas Gregor42af25f2009-05-11 19:58:34 +00004458 // If the nested-name-specifier does not refer to the current
4459 // instantiation, then build a typename type.
4460 if (!CurrentInstantiation)
4461 return Context.getTypenameType(NNS, &II);
Mike Stump1eb44332009-09-09 15:08:12 +00004462
Douglas Gregorde18d122009-09-02 13:12:51 +00004463 // The nested-name-specifier refers to the current instantiation, so the
4464 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump1eb44332009-09-09 15:08:12 +00004465 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorde18d122009-09-02 13:12:51 +00004466 // extraneous "typename" keywords, and we retroactively apply this DR to
4467 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00004468 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004469
Douglas Gregor42af25f2009-05-11 19:58:34 +00004470 DeclContext *Ctx = 0;
4471
4472 if (CurrentInstantiation)
4473 Ctx = CurrentInstantiation;
4474 else {
4475 CXXScopeSpec SS;
4476 SS.setScopeRep(NNS);
4477 SS.setRange(Range);
4478 if (RequireCompleteDeclContext(SS))
4479 return QualType();
4480
4481 Ctx = computeDeclContext(SS);
4482 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004483 assert(Ctx && "No declaration context?");
4484
4485 DeclarationName Name(&II);
John McCallf36e02d2009-10-09 21:13:30 +00004486 LookupResult Result;
4487 LookupQualifiedName(Result, Ctx, Name, LookupOrdinaryName, false);
Douglas Gregord57959a2009-03-27 23:10:48 +00004488 unsigned DiagID = 0;
4489 Decl *Referenced = 0;
4490 switch (Result.getKind()) {
4491 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00004492 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00004493 break;
4494
4495 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00004496 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004497 // We found a type. Build a QualifiedNameType, since the
4498 // typename-specifier was just sugar. FIXME: Tell
4499 // QualifiedNameType that it has a "typename" prefix.
4500 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4501 }
4502
4503 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00004504 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00004505 break;
4506
4507 case LookupResult::FoundOverloaded:
4508 DiagID = diag::err_typename_nested_not_type;
4509 Referenced = *Result.begin();
4510 break;
4511
John McCall6e247262009-10-10 05:48:19 +00004512 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00004513 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
4514 return QualType();
4515 }
4516
4517 // If we get here, it's because name lookup did not find a
4518 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor3f093272009-10-13 21:16:44 +00004519 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00004520 if (Referenced)
4521 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4522 << Name;
4523 return QualType();
4524}
Douglas Gregor4a959d82009-08-06 16:20:37 +00004525
4526namespace {
4527 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump1eb44332009-09-09 15:08:12 +00004528 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4529 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00004530 SourceLocation Loc;
4531 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00004532
Douglas Gregor4a959d82009-08-06 16:20:37 +00004533 public:
Mike Stump1eb44332009-09-09 15:08:12 +00004534 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00004535 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004536 DeclarationName Entity)
4537 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00004538 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00004539
4540 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00004541 /// transformed.
4542 ///
4543 /// For the purposes of type reconstruction, a type has already been
4544 /// transformed if it is NULL or if it is not dependent.
4545 bool AlreadyTransformed(QualType T) {
4546 return T.isNull() || !T->isDependentType();
4547 }
Mike Stump1eb44332009-09-09 15:08:12 +00004548
4549 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00004550 /// rebuilt.
4551 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00004552
Douglas Gregor4a959d82009-08-06 16:20:37 +00004553 /// \brief Returns the name of the entity whose type is being rebuilt.
4554 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00004555
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004556 /// \brief Sets the "base" location and entity when that
4557 /// information is known based on another transformation.
4558 void setBase(SourceLocation Loc, DeclarationName Entity) {
4559 this->Loc = Loc;
4560 this->Entity = Entity;
4561 }
4562
Douglas Gregor4a959d82009-08-06 16:20:37 +00004563 /// \brief Transforms an expression by returning the expression itself
4564 /// (an identity function).
4565 ///
4566 /// FIXME: This is completely unsafe; we will need to actually clone the
4567 /// expressions.
4568 Sema::OwningExprResult TransformExpr(Expr *E) {
4569 return getSema().Owned(E);
4570 }
Mike Stump1eb44332009-09-09 15:08:12 +00004571
Douglas Gregor4a959d82009-08-06 16:20:37 +00004572 /// \brief Transforms a typename type by determining whether the type now
4573 /// refers to a member of the current instantiation, and then
4574 /// type-checking and building a QualifiedNameType (when possible).
John McCalla2becad2009-10-21 00:40:46 +00004575 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor4a959d82009-08-06 16:20:37 +00004576 };
4577}
4578
Mike Stump1eb44332009-09-09 15:08:12 +00004579QualType
John McCalla2becad2009-10-21 00:40:46 +00004580CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4581 TypenameTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00004582 TypenameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00004583
Douglas Gregor4a959d82009-08-06 16:20:37 +00004584 NestedNameSpecifier *NNS
4585 = TransformNestedNameSpecifier(T->getQualifier(),
4586 /*FIXME:*/SourceRange(getBaseLocation()));
4587 if (!NNS)
4588 return QualType();
4589
4590 // If the nested-name-specifier did not change, and we cannot compute the
4591 // context corresponding to the nested-name-specifier, then this
4592 // typename type will not change; exit early.
4593 CXXScopeSpec SS;
4594 SS.setRange(SourceRange(getBaseLocation()));
4595 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00004596
4597 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004598 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00004599 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004600
4601 // Rebuild the typename type, which will probably turn into a
Douglas Gregor4a959d82009-08-06 16:20:37 +00004602 // QualifiedNameType.
John McCall833ca992009-10-29 08:12:44 +00004603 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004604 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00004605 = TransformType(QualType(TemplateId, 0));
4606 if (NewTemplateId.isNull())
4607 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004608
Douglas Gregor4a959d82009-08-06 16:20:37 +00004609 if (NNS == T->getQualifier() &&
4610 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00004611 Result = QualType(T, 0);
4612 else
4613 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4614 } else
4615 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4616 SourceRange(TL.getNameLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +00004617
John McCall833ca992009-10-29 08:12:44 +00004618 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4619 NewTL.setNameLoc(TL.getNameLoc());
4620 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004621}
4622
4623/// \brief Rebuilds a type within the context of the current instantiation.
4624///
Mike Stump1eb44332009-09-09 15:08:12 +00004625/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00004626/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00004627/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00004628/// partial specialization thereof). This routine will rebuild that type now
4629/// that we have entered the declarator's scope, which may produce different
4630/// canonical types, e.g.,
4631///
4632/// \code
4633/// template<typename T>
4634/// struct X {
4635/// typedef T* pointer;
4636/// pointer data();
4637/// };
4638///
4639/// template<typename T>
4640/// typename X<T>::pointer X<T>::data() { ... }
4641/// \endcode
4642///
4643/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4644/// since we do not know that we can look into X<T> when we parsed the type.
4645/// This function will rebuild the type, performing the lookup of "pointer"
4646/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4647/// as the canonical type of T*, allowing the return types of the out-of-line
4648/// definition and the declaration to match.
4649QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4650 DeclarationName Name) {
4651 if (T.isNull() || !T->isDependentType())
4652 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00004653
Douglas Gregor4a959d82009-08-06 16:20:37 +00004654 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4655 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00004656}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004657
4658/// \brief Produces a formatted string that describes the binding of
4659/// template parameters to template arguments.
4660std::string
4661Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4662 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004663 // FIXME: For variadic templates, we'll need to get the structured list.
4664 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4665 Args.flat_size());
4666}
4667
4668std::string
4669Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4670 const TemplateArgument *Args,
4671 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004672 std::string Result;
4673
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004674 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004675 return Result;
4676
4677 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004678 if (I >= NumArgs)
4679 break;
4680
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004681 if (I == 0)
4682 Result += "[with ";
4683 else
4684 Result += ", ";
4685
4686 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4687 Result += Id->getName();
4688 } else {
4689 Result += '$';
4690 Result += llvm::utostr(I);
4691 }
4692
4693 Result += " = ";
4694
4695 switch (Args[I].getKind()) {
4696 case TemplateArgument::Null:
4697 Result += "<no value>";
4698 break;
4699
4700 case TemplateArgument::Type: {
4701 std::string TypeStr;
4702 Args[I].getAsType().getAsStringInternal(TypeStr,
4703 Context.PrintingPolicy);
4704 Result += TypeStr;
4705 break;
4706 }
4707
4708 case TemplateArgument::Declaration: {
4709 bool Unnamed = true;
4710 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4711 if (ND->getDeclName()) {
4712 Unnamed = false;
4713 Result += ND->getNameAsString();
4714 }
4715 }
4716
4717 if (Unnamed) {
4718 Result += "<anonymous>";
4719 }
4720 break;
4721 }
4722
Douglas Gregor788cd062009-11-11 01:00:40 +00004723 case TemplateArgument::Template: {
4724 std::string Str;
4725 llvm::raw_string_ostream OS(Str);
4726 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4727 Result += OS.str();
4728 break;
4729 }
4730
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004731 case TemplateArgument::Integral: {
4732 Result += Args[I].getAsIntegral()->toString(10);
4733 break;
4734 }
4735
4736 case TemplateArgument::Expression: {
4737 assert(false && "No expressions in deduced template arguments!");
4738 Result += "<expression>";
4739 break;
4740 }
4741
4742 case TemplateArgument::Pack:
4743 // FIXME: Format template argument packs
4744 Result += "<template argument pack>";
4745 break;
4746 }
4747 }
4748
4749 Result += ']';
4750 return Result;
4751}