blob: f013343894179b6b65ecfd223e1a53de56bbeb64 [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-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 Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000020#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000023#include "llvm/Support/Compiler.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregorb7bfe792009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
31 if (!D)
32 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
Mike Stump11289f42009-09-09 15:08:12 +000036
Douglas Gregorb7bfe792009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregorb7bfe792009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
63 if (!Ovl)
64 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000065
Douglas Gregorb7bfe792009-09-02 22:59:36 +000066 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
67 FEnd = Ovl->function_end();
68 F != FEnd; ++F) {
69 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
70 // We've found a function template. Determine whether there are
71 // any other function templates we need to bundle together in an
72 // OverloadedFunctionDecl
73 for (++F; F != FEnd; ++F) {
74 if (isa<FunctionTemplateDecl>(*F))
75 break;
76 }
Mike Stump11289f42009-09-09 15:08:12 +000077
Douglas Gregorb7bfe792009-09-02 22:59:36 +000078 if (F != FEnd) {
79 // Build an overloaded function decl containing only the
80 // function templates in Ovl.
Mike Stump11289f42009-09-09 15:08:12 +000081 OverloadedFunctionDecl *OvlTemplate
Douglas Gregorb7bfe792009-09-02 22:59:36 +000082 = OverloadedFunctionDecl::Create(Context,
83 Ovl->getDeclContext(),
84 Ovl->getDeclName());
85 OvlTemplate->addOverload(FuncTmpl);
86 OvlTemplate->addOverload(*F);
87 for (++F; F != FEnd; ++F) {
88 if (isa<FunctionTemplateDecl>(*F))
89 OvlTemplate->addOverload(*F);
90 }
Mike Stump11289f42009-09-09 15:08:12 +000091
Douglas Gregorb7bfe792009-09-02 22:59:36 +000092 return OvlTemplate;
93 }
94
95 return FuncTmpl;
96 }
97 }
Mike Stump11289f42009-09-09 15:08:12 +000098
Douglas Gregorb7bfe792009-09-02 22:59:36 +000099 return 0;
100}
101
102TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000103 const CXXScopeSpec &SS,
104 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000105 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000106 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000107 TemplateTy &TemplateResult) {
Douglas Gregor3cf81312009-11-03 23:16:33 +0000108 DeclarationName TName;
109
110 switch (Name.getKind()) {
111 case UnqualifiedId::IK_Identifier:
112 TName = DeclarationName(Name.Identifier);
113 break;
114
115 case UnqualifiedId::IK_OperatorFunctionId:
116 TName = Context.DeclarationNames.getCXXOperatorName(
117 Name.OperatorFunctionId.Operator);
118 break;
119
120 default:
121 return TNK_Non_template;
122 }
123
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000124 // Determine where to perform name lookup
125 DeclContext *LookupCtx = 0;
126 bool isDependent = false;
127 if (ObjectTypePtr) {
128 // This nested-name-specifier occurs in a member access expression, e.g.,
129 // x->B::f, and we are looking into the type of the object.
Douglas Gregor3cf81312009-11-03 23:16:33 +0000130 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000131 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
132 LookupCtx = computeDeclContext(ObjectType);
133 isDependent = ObjectType->isDependentType();
Douglas Gregor3fad6172009-11-17 05:17:33 +0000134 assert((isDependent || !ObjectType->isIncompleteType()) &&
135 "Caller should have completed object type");
Douglas Gregor3cf81312009-11-03 23:16:33 +0000136 } else if (SS.isSet()) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000137 // This nested-name-specifier occurs after another nested-name-specifier,
138 // so long into the context associated with the prior nested-name-specifier.
Douglas Gregor3cf81312009-11-03 23:16:33 +0000139 LookupCtx = computeDeclContext(SS, EnteringContext);
140 isDependent = isDependentScopeSpecifier(SS);
Douglas Gregor3fad6172009-11-17 05:17:33 +0000141
142 // The declaration context must be complete.
143 if (LookupCtx && RequireCompleteDeclContext(SS))
144 return TNK_Non_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000145 }
Mike Stump11289f42009-09-09 15:08:12 +0000146
John McCall27b18f82009-11-17 02:14:36 +0000147 LookupResult Found(*this, TName, SourceLocation(), LookupOrdinaryName);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000148 bool ObjectTypeSearchedInScope = false;
149 if (LookupCtx) {
150 // Perform "qualified" name lookup into the declaration context we
151 // computed, which is either the type of the base of a member access
Mike Stump11289f42009-09-09 15:08:12 +0000152 // expression or the declaration context associated with a prior
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000153 // nested-name-specifier.
John McCall27b18f82009-11-17 02:14:36 +0000154 LookupQualifiedName(Found, LookupCtx);
Mike Stump11289f42009-09-09 15:08:12 +0000155
John McCall27b18f82009-11-17 02:14:36 +0000156 if (ObjectTypePtr && Found.empty()) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000157 // C++ [basic.lookup.classref]p1:
158 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump11289f42009-09-09 15:08:12 +0000159 // immediately followed by an identifier followed by a <, the
160 // identifier must be looked up to determine whether the < is the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000161 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump11289f42009-09-09 15:08:12 +0000162 // The identifier is first looked up in the class of the object
163 // expression. If the identifier is not found, it is then looked up in
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000164 // the context of the entire postfix-expression and shall name a class
165 // or function template.
166 //
167 // FIXME: When we're instantiating a template, do we actually have to
168 // look in the scope of the template? Seems fishy...
John McCall27b18f82009-11-17 02:14:36 +0000169 LookupName(Found, S);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000170 ObjectTypeSearchedInScope = true;
171 }
172 } else if (isDependent) {
Mike Stump11289f42009-09-09 15:08:12 +0000173 // We cannot look into a dependent object type or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000174 return TNK_Non_template;
175 } else {
176 // Perform unqualified name lookup in the current scope.
John McCall27b18f82009-11-17 02:14:36 +0000177 LookupName(Found, S);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000178 }
Mike Stump11289f42009-09-09 15:08:12 +0000179
Douglas Gregore861bac2009-08-25 22:51:20 +0000180 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump11289f42009-09-09 15:08:12 +0000181 assert(!Found.isAmbiguous() &&
Douglas Gregore861bac2009-08-25 22:51:20 +0000182 "Cannot handle template name-lookup ambiguities");
Douglas Gregordc572a32009-03-30 22:58:21 +0000183
John McCall9f3059a2009-10-09 21:13:30 +0000184 NamedDecl *Template
185 = isAcceptableTemplateName(Context, Found.getAsSingleDecl(Context));
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000186 if (!Template)
187 return TNK_Non_template;
188
189 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
190 // C++ [basic.lookup.classref]p1:
Mike Stump11289f42009-09-09 15:08:12 +0000191 // [...] If the lookup in the class of the object expression finds a
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000192 // template, the name is also looked up in the context of the entire
193 // postfix-expression and [...]
194 //
John McCall27b18f82009-11-17 02:14:36 +0000195 LookupResult FoundOuter(*this, TName, SourceLocation(), LookupOrdinaryName);
196 LookupName(FoundOuter, S);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000197 // FIXME: Handle ambiguities in this lookup better
John McCall9f3059a2009-10-09 21:13:30 +0000198 NamedDecl *OuterTemplate
199 = isAcceptableTemplateName(Context, FoundOuter.getAsSingleDecl(Context));
Mike Stump11289f42009-09-09 15:08:12 +0000200
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000201 if (!OuterTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +0000202 // - if the name is not found, the name found in the class of the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000203 // object expression is used, otherwise
204 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump11289f42009-09-09 15:08:12 +0000205 // - if the name is found in the context of the entire
206 // postfix-expression and does not name a class template, the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000207 // found in the class of the object expression is used, otherwise
208 } else {
209 // - if the name found is a class template, it must refer to the same
Mike Stump11289f42009-09-09 15:08:12 +0000210 // entity as the one found in the class of the object expression,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000211 // otherwise the program is ill-formed.
212 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
Douglas Gregor3cf81312009-11-03 23:16:33 +0000213 Diag(Name.getSourceRange().getBegin(),
214 diag::err_nested_name_member_ref_lookup_ambiguous)
215 << TName
216 << Name.getSourceRange();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000217 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
218 << QualType::getFromOpaquePtr(ObjectTypePtr);
219 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump11289f42009-09-09 15:08:12 +0000220
221 // Recover by taking the template that we found in the object
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000222 // expression's type.
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000223 }
Mike Stump11289f42009-09-09 15:08:12 +0000224 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000225 }
Mike Stump11289f42009-09-09 15:08:12 +0000226
Douglas Gregor3cf81312009-11-03 23:16:33 +0000227 if (SS.isSet() && !SS.isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000228 NestedNameSpecifier *Qualifier
Douglas Gregor3cf81312009-11-03 23:16:33 +0000229 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000230 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000231 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000232 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000233 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
234 Ovl));
235 else
Mike Stump11289f42009-09-09 15:08:12 +0000236 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000237 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000238 cast<TemplateDecl>(Template)));
239 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000240 = dyn_cast<OverloadedFunctionDecl>(Template)) {
241 TemplateResult = TemplateTy::make(TemplateName(Ovl));
242 } else {
243 TemplateResult = TemplateTy::make(
244 TemplateName(cast<TemplateDecl>(Template)));
245 }
Mike Stump11289f42009-09-09 15:08:12 +0000246
247 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000248 isa<TemplateTemplateParmDecl>(Template))
249 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000250
251 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000252 isa<OverloadedFunctionDecl>(Template)) &&
253 "Unhandled template kind in Sema::isTemplateName");
254 return TNK_Function_template;
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000255}
256
Douglas Gregor5101c242008-12-05 18:15:24 +0000257/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
258/// that the template parameter 'PrevDecl' is being shadowed by a new
259/// declaration at location Loc. Returns true to indicate that this is
260/// an error, and false otherwise.
261bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000262 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000263
264 // Microsoft Visual C++ permits template parameters to be shadowed.
265 if (getLangOptions().Microsoft)
266 return false;
267
268 // C++ [temp.local]p4:
269 // A template-parameter shall not be redeclared within its
270 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000271 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000272 << cast<NamedDecl>(PrevDecl)->getDeclName();
273 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
274 return true;
275}
276
Douglas Gregor463421d2009-03-03 04:44:36 +0000277/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000278/// the parameter D to reference the templated declaration and return a pointer
279/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000280TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000281 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000282 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000283 return Temp;
284 }
285 return 0;
286}
287
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000288static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
289 const ParsedTemplateArgument &Arg) {
290
291 switch (Arg.getKind()) {
292 case ParsedTemplateArgument::Type: {
293 DeclaratorInfo *DI;
294 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
295 if (!DI)
296 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation());
297 return TemplateArgumentLoc(TemplateArgument(T), DI);
298 }
299
300 case ParsedTemplateArgument::NonType: {
301 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
302 return TemplateArgumentLoc(TemplateArgument(E), E);
303 }
304
305 case ParsedTemplateArgument::Template: {
306 TemplateName Template
307 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
308 return TemplateArgumentLoc(TemplateArgument(Template),
309 Arg.getScopeSpec().getRange(),
310 Arg.getLocation());
311 }
312 }
313
314 llvm::llvm_unreachable("Unhandled parsed template argument");
315 return TemplateArgumentLoc();
316}
317
318/// \brief Translates template arguments as provided by the parser
319/// into template arguments used by semantic analysis.
320void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
321 llvm::SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs) {
322 TemplateArgs.reserve(TemplateArgsIn.size());
323
324 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
325 TemplateArgs.push_back(translateTemplateArgument(*this, TemplateArgsIn[I]));
326}
327
Douglas Gregor5101c242008-12-05 18:15:24 +0000328/// ActOnTypeParameter - Called when a C++ template type parameter
329/// (e.g., "typename T") has been parsed. Typename specifies whether
330/// the keyword "typename" was used to declare the type parameter
331/// (otherwise, "class" was used), and KeyLoc is the location of the
332/// "class" or "typename" keyword. ParamName is the name of the
333/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000334/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000335/// If the type parameter has a default argument, it will be added
336/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000337Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000338 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000339 SourceLocation KeyLoc,
340 IdentifierInfo *ParamName,
341 SourceLocation ParamNameLoc,
342 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000343 assert(S->isTemplateParamScope() &&
344 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000345 bool Invalid = false;
346
347 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000348 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000349 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000350 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000351 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000352 }
353
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000354 SourceLocation Loc = ParamNameLoc;
355 if (!ParamName)
356 Loc = KeyLoc;
357
Douglas Gregor5101c242008-12-05 18:15:24 +0000358 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000359 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
360 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000361 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000362 if (Invalid)
363 Param->setInvalidDecl();
364
365 if (ParamName) {
366 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000367 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000368 IdResolver.AddDecl(Param);
369 }
370
Chris Lattner83f095c2009-03-28 19:18:32 +0000371 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000372}
373
Douglas Gregordba32632009-02-10 19:49:53 +0000374/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000375/// Default) to the given template type parameter (TypeParam).
376void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000377 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000378 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000379 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000380 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000381 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000382
383 DeclaratorInfo *DefaultDInfo;
384 GetTypeFromParser(DefaultT, &DefaultDInfo);
385
386 assert(DefaultDInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000387
Anders Carlssond3824352009-06-12 22:30:13 +0000388 // C++0x [temp.param]p9:
389 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000390 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000391 if (Parm->isParameterPack()) {
392 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000393 return;
394 }
Mike Stump11289f42009-09-09 15:08:12 +0000395
Douglas Gregordba32632009-02-10 19:49:53 +0000396 // C++ [temp.param]p14:
397 // A template-parameter shall not be used in its own default argument.
398 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000399
Douglas Gregordba32632009-02-10 19:49:53 +0000400 // Check the template argument itself.
John McCall0ad16662009-10-29 08:12:44 +0000401 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000402 Parm->setInvalidDecl();
403 return;
404 }
405
John McCall0ad16662009-10-29 08:12:44 +0000406 Parm->setDefaultArgument(DefaultDInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000407}
408
Douglas Gregor463421d2009-03-03 04:44:36 +0000409/// \brief Check that the type of a non-type template parameter is
410/// well-formed.
411///
412/// \returns the (possibly-promoted) parameter type if valid;
413/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000414QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000415Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
416 // C++ [temp.param]p4:
417 //
418 // A non-type template-parameter shall have one of the following
419 // (optionally cv-qualified) types:
420 //
421 // -- integral or enumeration type,
422 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000423 // -- pointer to object or pointer to function,
424 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000425 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
426 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000427 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000428 T->isReferenceType() ||
429 // -- pointer to member.
430 T->isMemberPointerType() ||
431 // If T is a dependent type, we can't do the check now, so we
432 // assume that it is well-formed.
433 T->isDependentType())
434 return T;
435 // C++ [temp.param]p8:
436 //
437 // A non-type template-parameter of type "array of T" or
438 // "function returning T" is adjusted to be of type "pointer to
439 // T" or "pointer to function returning T", respectively.
440 else if (T->isArrayType())
441 // FIXME: Keep the type prior to promotion?
442 return Context.getArrayDecayedType(T);
443 else if (T->isFunctionType())
444 // FIXME: Keep the type prior to promotion?
445 return Context.getPointerType(T);
446
447 Diag(Loc, diag::err_template_nontype_parm_bad_type)
448 << T;
449
450 return QualType();
451}
452
Douglas Gregor5101c242008-12-05 18:15:24 +0000453/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
454/// template parameter (e.g., "int Size" in "template<int Size>
455/// class Array") has been parsed. S is the current scope and D is
456/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000457Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000458 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000459 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000460 DeclaratorInfo *DInfo = 0;
461 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000462
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000463 assert(S->isTemplateParamScope() &&
464 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000465 bool Invalid = false;
466
467 IdentifierInfo *ParamName = D.getIdentifier();
468 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000469 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000470 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000471 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000472 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000473 }
474
Douglas Gregor463421d2009-03-03 04:44:36 +0000475 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000476 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000477 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000478 Invalid = true;
479 }
Douglas Gregor81338792009-02-10 17:43:50 +0000480
Douglas Gregor5101c242008-12-05 18:15:24 +0000481 NonTypeTemplateParmDecl *Param
482 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000483 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000484 if (Invalid)
485 Param->setInvalidDecl();
486
487 if (D.getIdentifier()) {
488 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000489 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000490 IdResolver.AddDecl(Param);
491 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000492 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000493}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000494
Douglas Gregordba32632009-02-10 19:49:53 +0000495/// \brief Adds a default argument to the given non-type template
496/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000497void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000498 SourceLocation EqualLoc,
499 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000500 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000501 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000502 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000503
Douglas Gregordba32632009-02-10 19:49:53 +0000504 // C++ [temp.param]p14:
505 // A template-parameter shall not be used in its own default argument.
506 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000507
Douglas Gregordba32632009-02-10 19:49:53 +0000508 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000509 TemplateArgument Converted;
510 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
511 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000512 TemplateParm->setInvalidDecl();
513 return;
514 }
515
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000516 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000517}
518
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000519
520/// ActOnTemplateTemplateParameter - Called when a C++ template template
521/// parameter (e.g. T in template <template <typename> class T> class array)
522/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000523Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
524 SourceLocation TmpLoc,
525 TemplateParamsTy *Params,
526 IdentifierInfo *Name,
527 SourceLocation NameLoc,
528 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000529 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000530 assert(S->isTemplateParamScope() &&
531 "Template template parameter not in template parameter scope!");
532
533 // Construct the parameter object.
534 TemplateTemplateParmDecl *Param =
535 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
536 Position, Name,
537 (TemplateParameterList*)Params);
538
539 // Make sure the parameter is valid.
540 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
541 // do anything yet. However, if the template parameter list or (eventual)
542 // default value is ever invalidated, that will propagate here.
543 bool Invalid = false;
544 if (Invalid) {
545 Param->setInvalidDecl();
546 }
547
548 // If the tt-param has a name, then link the identifier into the scope
549 // and lookup mechanisms.
550 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000551 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000552 IdResolver.AddDecl(Param);
553 }
554
Chris Lattner83f095c2009-03-28 19:18:32 +0000555 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000556}
557
Douglas Gregordba32632009-02-10 19:49:53 +0000558/// \brief Adds a default argument to the given template template
559/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000560void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000561 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000562 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000563 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000564 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000565
Douglas Gregordba32632009-02-10 19:49:53 +0000566 // C++ [temp.param]p14:
567 // A template-parameter shall not be used in its own default argument.
568 // FIXME: Implement this check! Needs a recursive walk over the types.
569
Douglas Gregore62e6a02009-11-11 19:13:48 +0000570 // Check only that we have a template template argument. We don't want to
571 // try to check well-formedness now, because our template template parameter
572 // might have dependent types in its template parameters, which we wouldn't
573 // be able to match now.
574 //
575 // If none of the template template parameter's template arguments mention
576 // other template parameters, we could actually perform more checking here.
577 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000578 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000579 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
580 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
581 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000582 return;
583 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000584
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000585 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000586}
587
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000588/// ActOnTemplateParameterList - Builds a TemplateParameterList that
589/// contains the template parameters in Params/NumParams.
590Sema::TemplateParamsTy *
591Sema::ActOnTemplateParameterList(unsigned Depth,
592 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000593 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000594 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000595 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000596 SourceLocation RAngleLoc) {
597 if (ExportLoc.isValid())
598 Diag(ExportLoc, diag::note_template_export_unsupported);
599
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000600 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000601 (NamedDecl**)Params, NumParams,
602 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000603}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000604
Douglas Gregorc08f4892009-03-25 00:13:59 +0000605Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000606Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000607 SourceLocation KWLoc, const CXXScopeSpec &SS,
608 IdentifierInfo *Name, SourceLocation NameLoc,
609 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000610 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000611 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000612 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000613 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000614 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000615 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000616
617 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000618 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000619 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000620
John McCall27b5c252009-09-14 21:59:20 +0000621 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
622 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000623
624 // There is no such thing as an unnamed class template.
625 if (!Name) {
626 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000627 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000628 }
629
630 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000631 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000632 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000633 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000634 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000635 if (RequireCompleteDeclContext(SS))
636 return true;
637
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000638 SemanticContext = computeDeclContext(SS, true);
639 if (!SemanticContext) {
640 // FIXME: Produce a reasonable diagnostic here
641 return true;
642 }
Mike Stump11289f42009-09-09 15:08:12 +0000643
John McCall27b18f82009-11-17 02:14:36 +0000644 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000645 } else {
646 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000647 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000648 }
Mike Stump11289f42009-09-09 15:08:12 +0000649
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000650 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
651 NamedDecl *PrevDecl = 0;
652 if (Previous.begin() != Previous.end())
653 PrevDecl = *Previous.begin();
654
Douglas Gregor9acb6902009-09-26 07:05:09 +0000655 if (PrevDecl && TUK == TUK_Friend) {
656 // C++ [namespace.memdef]p3:
657 // [...] When looking for a prior declaration of a class or a function
658 // declared as a friend, and when the name of the friend class or
659 // function is neither a qualified name nor a template-id, scopes outside
660 // the innermost enclosing namespace scope are not considered.
661 DeclContext *OutermostContext = CurContext;
662 while (!OutermostContext->isFileContext())
663 OutermostContext = OutermostContext->getLookupParent();
664
665 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
666 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
667 SemanticContext = PrevDecl->getDeclContext();
668 } else {
669 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000670 // context we computed is the semantic context for our new
Douglas Gregor9acb6902009-09-26 07:05:09 +0000671 // declaration.
672 PrevDecl = 0;
673 SemanticContext = OutermostContext;
674 }
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000675
676 if (CurContext->isDependentContext()) {
677 // If this is a dependent context, we don't want to link the friend
678 // class template to the template in scope, because that would perform
679 // checking of the template parameter lists that can't be performed
680 // until the outer context is instantiated.
681 PrevDecl = 0;
682 }
Douglas Gregor9acb6902009-09-26 07:05:09 +0000683 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000684 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000685
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000686 // If there is a previous declaration with the same name, check
687 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000688 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000689 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000690
691 // We may have found the injected-class-name of a class template,
692 // class template partial specialization, or class template specialization.
693 // In these cases, grab the template that is being defined or specialized.
694 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
695 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
696 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
697 PrevClassTemplate
698 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
699 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
700 PrevClassTemplate
701 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
702 ->getSpecializedTemplate();
703 }
704 }
705
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000706 if (PrevClassTemplate) {
707 // Ensure that the template parameter lists are compatible.
708 if (!TemplateParameterListsAreEqual(TemplateParams,
709 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000710 /*Complain=*/true,
711 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000712 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000713
714 // C++ [temp.class]p4:
715 // In a redeclaration, partial specialization, explicit
716 // specialization or explicit instantiation of a class template,
717 // the class-key shall agree in kind with the original class
718 // template declaration (7.1.5.3).
719 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000720 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000721 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000722 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000723 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000724 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000725 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000726 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000727 }
728
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000729 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000730 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000731 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
732 Diag(NameLoc, diag::err_redefinition) << Name;
733 Diag(Def->getLocation(), diag::note_previous_definition);
734 // FIXME: Would it make sense to try to "forget" the previous
735 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000736 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000737 }
738 }
739 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
740 // Maybe we will complain about the shadowed template parameter.
741 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
742 // Just pretend that we didn't see the previous declaration.
743 PrevDecl = 0;
744 } else if (PrevDecl) {
745 // C++ [temp]p5:
746 // A class template shall not have the same name as any other
747 // template, class, function, object, enumeration, enumerator,
748 // namespace, or type in the same scope (3.3), except as specified
749 // in (14.5.4).
750 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
751 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000752 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000753 }
754
Douglas Gregordba32632009-02-10 19:49:53 +0000755 // Check the template parameter list of this declaration, possibly
756 // merging in the template parameter list from the previous class
757 // template declaration.
758 if (CheckTemplateParameterList(TemplateParams,
759 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
760 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000761
Douglas Gregore362cea2009-05-10 22:57:19 +0000762 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000763 // declaration!
764
Mike Stump11289f42009-09-09 15:08:12 +0000765 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000766 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000767 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000768 PrevClassTemplate->getTemplatedDecl() : 0,
769 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000770
771 ClassTemplateDecl *NewTemplate
772 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
773 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000774 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000775 NewClass->setDescribedClassTemplate(NewTemplate);
776
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000777 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000778 QualType T =
779 Context.getTypeDeclType(NewClass,
780 PrevClassTemplate?
781 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000782 assert(T->isDependentType() && "Class template type is not dependent?");
783 (void)T;
784
Douglas Gregorcf915552009-10-13 16:30:37 +0000785 // If we are providing an explicit specialization of a member that is a
786 // class template, make a note of that.
787 if (PrevClassTemplate &&
788 PrevClassTemplate->getInstantiatedFromMemberTemplate())
789 PrevClassTemplate->setMemberSpecialization();
790
Anders Carlsson137108d2009-03-26 01:24:28 +0000791 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000792 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000793 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000794
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000795 // Set the lexical context of these templates
796 NewClass->setLexicalDeclContext(CurContext);
797 NewTemplate->setLexicalDeclContext(CurContext);
798
John McCall9bb74a52009-07-31 02:45:11 +0000799 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000800 NewClass->startDefinition();
801
802 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000803 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000804
John McCall27b5c252009-09-14 21:59:20 +0000805 if (TUK != TUK_Friend)
806 PushOnScopeChains(NewTemplate, S);
807 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000808 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000809 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000810 NewClass->setAccess(PrevClassTemplate->getAccess());
811 }
John McCall27b5c252009-09-14 21:59:20 +0000812
Douglas Gregor3dad8422009-09-26 06:47:28 +0000813 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
814 PrevClassTemplate != NULL);
815
John McCall27b5c252009-09-14 21:59:20 +0000816 // Friend templates are visible in fairly strange ways.
817 if (!CurContext->isDependentContext()) {
818 DeclContext *DC = SemanticContext->getLookupContext();
819 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
820 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
821 PushOnScopeChains(NewTemplate, EnclosingScope,
822 /* AddToContext = */ false);
823 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000824
825 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
826 NewClass->getLocation(),
827 NewTemplate,
828 /*FIXME:*/NewClass->getLocation());
829 Friend->setAccess(AS_public);
830 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000831 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000832
Douglas Gregordba32632009-02-10 19:49:53 +0000833 if (Invalid) {
834 NewTemplate->setInvalidDecl();
835 NewClass->setInvalidDecl();
836 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000837 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000838}
839
Douglas Gregordba32632009-02-10 19:49:53 +0000840/// \brief Checks the validity of a template parameter list, possibly
841/// considering the template parameter list from a previous
842/// declaration.
843///
844/// If an "old" template parameter list is provided, it must be
845/// equivalent (per TemplateParameterListsAreEqual) to the "new"
846/// template parameter list.
847///
848/// \param NewParams Template parameter list for a new template
849/// declaration. This template parameter list will be updated with any
850/// default arguments that are carried through from the previous
851/// template parameter list.
852///
853/// \param OldParams If provided, template parameter list from a
854/// previous declaration of the same template. Default template
855/// arguments will be merged from the old template parameter list to
856/// the new template parameter list.
857///
858/// \returns true if an error occurred, false otherwise.
859bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
860 TemplateParameterList *OldParams) {
861 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000862
Douglas Gregordba32632009-02-10 19:49:53 +0000863 // C++ [temp.param]p10:
864 // The set of default template-arguments available for use with a
865 // template declaration or definition is obtained by merging the
866 // default arguments from the definition (if in scope) and all
867 // declarations in scope in the same way default function
868 // arguments are (8.3.6).
869 bool SawDefaultArgument = false;
870 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000871
Anders Carlsson327865d2009-06-12 23:20:15 +0000872 bool SawParameterPack = false;
873 SourceLocation ParameterPackLoc;
874
Mike Stumpc89c8e32009-02-11 23:03:27 +0000875 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000876 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000877 if (OldParams)
878 OldParam = OldParams->begin();
879
880 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
881 NewParamEnd = NewParams->end();
882 NewParam != NewParamEnd; ++NewParam) {
883 // Variables used to diagnose redundant default arguments
884 bool RedundantDefaultArg = false;
885 SourceLocation OldDefaultLoc;
886 SourceLocation NewDefaultLoc;
887
888 // Variables used to diagnose missing default arguments
889 bool MissingDefaultArg = false;
890
Anders Carlsson327865d2009-06-12 23:20:15 +0000891 // C++0x [temp.param]p11:
892 // If a template parameter of a class template is a template parameter pack,
893 // it must be the last template parameter.
894 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +0000895 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +0000896 diag::err_template_param_pack_must_be_last_template_parameter);
897 Invalid = true;
898 }
899
Douglas Gregordba32632009-02-10 19:49:53 +0000900 // Merge default arguments for template type parameters.
901 if (TemplateTypeParmDecl *NewTypeParm
902 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump11289f42009-09-09 15:08:12 +0000903 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000904 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000905
Anders Carlsson327865d2009-06-12 23:20:15 +0000906 if (NewTypeParm->isParameterPack()) {
907 assert(!NewTypeParm->hasDefaultArgument() &&
908 "Parameter packs can't have a default argument!");
909 SawParameterPack = true;
910 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000911 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +0000912 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +0000913 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
914 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
915 SawDefaultArgument = true;
916 RedundantDefaultArg = true;
917 PreviousDefaultArgLoc = NewDefaultLoc;
918 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
919 // Merge the default argument from the old declaration to the
920 // new declaration.
921 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +0000922 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +0000923 true);
924 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
925 } else if (NewTypeParm->hasDefaultArgument()) {
926 SawDefaultArgument = true;
927 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
928 } else if (SawDefaultArgument)
929 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000930 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000931 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000932 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000933 NonTypeTemplateParmDecl *OldNonTypeParm
934 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000935 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000936 NewNonTypeParm->hasDefaultArgument()) {
937 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
938 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
939 SawDefaultArgument = true;
940 RedundantDefaultArg = true;
941 PreviousDefaultArgLoc = NewDefaultLoc;
942 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
943 // Merge the default argument from the old declaration to the
944 // new declaration.
945 SawDefaultArgument = true;
946 // FIXME: We need to create a new kind of "default argument"
947 // expression that points to a previous template template
948 // parameter.
949 NewNonTypeParm->setDefaultArgument(
950 OldNonTypeParm->getDefaultArgument());
951 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
952 } else if (NewNonTypeParm->hasDefaultArgument()) {
953 SawDefaultArgument = true;
954 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
955 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000956 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000957 } else {
Douglas Gregordba32632009-02-10 19:49:53 +0000958 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000959 TemplateTemplateParmDecl *NewTemplateParm
960 = cast<TemplateTemplateParmDecl>(*NewParam);
961 TemplateTemplateParmDecl *OldTemplateParm
962 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000963 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000964 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000965 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
966 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +0000967 SawDefaultArgument = true;
968 RedundantDefaultArg = true;
969 PreviousDefaultArgLoc = NewDefaultLoc;
970 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
971 // Merge the default argument from the old declaration to the
972 // new declaration.
973 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +0000974 // FIXME: We need to create a new kind of "default argument" expression
975 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +0000976 NewTemplateParm->setDefaultArgument(
977 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000978 PreviousDefaultArgLoc
979 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +0000980 } else if (NewTemplateParm->hasDefaultArgument()) {
981 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000982 PreviousDefaultArgLoc
983 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +0000984 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000985 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +0000986 }
987
988 if (RedundantDefaultArg) {
989 // C++ [temp.param]p12:
990 // A template-parameter shall not be given default arguments
991 // by two different declarations in the same scope.
992 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
993 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
994 Invalid = true;
995 } else if (MissingDefaultArg) {
996 // C++ [temp.param]p11:
997 // If a template-parameter has a default template-argument,
998 // all subsequent template-parameters shall have a default
999 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001000 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001001 diag::err_template_param_default_arg_missing);
1002 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1003 Invalid = true;
1004 }
1005
1006 // If we have an old template parameter list that we're merging
1007 // in, move on to the next parameter.
1008 if (OldParams)
1009 ++OldParam;
1010 }
1011
1012 return Invalid;
1013}
Douglas Gregord32e0282009-02-09 23:23:08 +00001014
Mike Stump11289f42009-09-09 15:08:12 +00001015/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001016/// specifier, returning the template parameter list that applies to the
1017/// name.
1018///
1019/// \param DeclStartLoc the start of the declaration that has a scope
1020/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001021///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001022/// \param SS the scope specifier that will be matched to the given template
1023/// parameter lists. This scope specifier precedes a qualified name that is
1024/// being declared.
1025///
1026/// \param ParamLists the template parameter lists, from the outermost to the
1027/// innermost template parameter lists.
1028///
1029/// \param NumParamLists the number of template parameter lists in ParamLists.
1030///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001031/// \param IsExplicitSpecialization will be set true if the entity being
1032/// declared is an explicit specialization, false otherwise.
1033///
Mike Stump11289f42009-09-09 15:08:12 +00001034/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001035/// name that is preceded by the scope specifier @p SS. This template
1036/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001037/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001038/// template specialization), or may be NULL (if we were's declaring isn't
1039/// itself a template).
1040TemplateParameterList *
1041Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1042 const CXXScopeSpec &SS,
1043 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001044 unsigned NumParamLists,
1045 bool &IsExplicitSpecialization) {
1046 IsExplicitSpecialization = false;
1047
Douglas Gregord8d297c2009-07-21 23:53:31 +00001048 // Find the template-ids that occur within the nested-name-specifier. These
1049 // template-ids will match up with the template parameter lists.
1050 llvm::SmallVector<const TemplateSpecializationType *, 4>
1051 TemplateIdsInSpecifier;
1052 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1053 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +00001054 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +00001055 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1056 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1057 if (!Template)
1058 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001059
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001060 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001061 ClassTemplateSpecializationDecl *SpecDecl
1062 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1063 // If the nested name specifier refers to an explicit specialization,
1064 // we don't need a template<> header.
Douglas Gregor82e22862009-09-16 00:01:48 +00001065 // FIXME: revisit this approach once we cope with specializations
Douglas Gregor15301382009-07-30 17:40:51 +00001066 // properly.
Douglas Gregord8d297c2009-07-21 23:53:31 +00001067 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
1068 continue;
1069 }
Mike Stump11289f42009-09-09 15:08:12 +00001070
Douglas Gregord8d297c2009-07-21 23:53:31 +00001071 TemplateIdsInSpecifier.push_back(SpecType);
1072 }
1073 }
Mike Stump11289f42009-09-09 15:08:12 +00001074
Douglas Gregord8d297c2009-07-21 23:53:31 +00001075 // Reverse the list of template-ids in the scope specifier, so that we can
1076 // more easily match up the template-ids and the template parameter lists.
1077 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001078
Douglas Gregord8d297c2009-07-21 23:53:31 +00001079 SourceLocation FirstTemplateLoc = DeclStartLoc;
1080 if (NumParamLists)
1081 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001082
Douglas Gregord8d297c2009-07-21 23:53:31 +00001083 // Match the template-ids found in the specifier to the template parameter
1084 // lists.
1085 unsigned Idx = 0;
1086 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1087 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001088 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1089 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001090 if (Idx >= NumParamLists) {
1091 // We have a template-id without a corresponding template parameter
1092 // list.
1093 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001094 // FIXME: the location information here isn't great.
1095 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001096 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001097 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001098 << SS.getRange();
1099 } else {
1100 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1101 << SS.getRange()
1102 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1103 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001104 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001105 }
1106 return 0;
1107 }
Mike Stump11289f42009-09-09 15:08:12 +00001108
Douglas Gregord8d297c2009-07-21 23:53:31 +00001109 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001110 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001111 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001112 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1113
Mike Stump11289f42009-09-09 15:08:12 +00001114 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001115 = dyn_cast<ClassTemplateDecl>(Template)) {
1116 TemplateParameterList *ExpectedTemplateParams = 0;
1117 // Is this template-id naming the primary template?
1118 if (Context.hasSameType(TemplateId,
1119 ClassTemplate->getInjectedClassNameType(Context)))
1120 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1121 // ... or a partial specialization?
1122 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1123 = ClassTemplate->findPartialSpecialization(TemplateId))
1124 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1125
1126 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001127 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001128 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001129 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001130 }
Douglas Gregor15301382009-07-30 17:40:51 +00001131 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001132 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001133 diag::err_template_param_list_matches_nontemplate)
1134 << TemplateId
1135 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001136 else
1137 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001138 }
Mike Stump11289f42009-09-09 15:08:12 +00001139
Douglas Gregord8d297c2009-07-21 23:53:31 +00001140 // If there were at least as many template-ids as there were template
1141 // parameter lists, then there are no template parameter lists remaining for
1142 // the declaration itself.
1143 if (Idx >= NumParamLists)
1144 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001145
Douglas Gregord8d297c2009-07-21 23:53:31 +00001146 // If there were too many template parameter lists, complain about that now.
1147 if (Idx != NumParamLists - 1) {
1148 while (Idx < NumParamLists - 1) {
Mike Stump11289f42009-09-09 15:08:12 +00001149 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001150 diag::err_template_spec_extra_headers)
1151 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1152 ParamLists[Idx]->getRAngleLoc());
1153 ++Idx;
1154 }
1155 }
Mike Stump11289f42009-09-09 15:08:12 +00001156
Douglas Gregord8d297c2009-07-21 23:53:31 +00001157 // Return the last template parameter list, which corresponds to the
1158 // entity being declared.
1159 return ParamLists[NumParamLists - 1];
1160}
1161
Douglas Gregordc572a32009-03-30 22:58:21 +00001162QualType Sema::CheckTemplateIdType(TemplateName Name,
1163 SourceLocation TemplateLoc,
1164 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001165 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregordc572a32009-03-30 22:58:21 +00001166 unsigned NumTemplateArgs,
1167 SourceLocation RAngleLoc) {
1168 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001169 if (!Template) {
1170 // The template name does not resolve to a template, so we just
1171 // build a dependent template-id type.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001172 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001173 NumTemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001174 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001175
Douglas Gregorc40290e2009-03-09 23:48:35 +00001176 // Check that the template argument list is well-formed for this
1177 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001178 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1179 NumTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001180 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001181 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001182 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001183 return QualType();
1184
Mike Stump11289f42009-09-09 15:08:12 +00001185 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001186 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001187 "Converted template argument list is too short!");
1188
1189 QualType CanonType;
1190
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001191 if (Name.isDependent() ||
1192 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorc40290e2009-03-09 23:48:35 +00001193 TemplateArgs,
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001194 NumTemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001195 // This class template specialization is a dependent
1196 // type. Therefore, its canonical type is another class template
1197 // specialization type that contains all of the converted
1198 // arguments in canonical form. This ensures that, e.g., A<T> and
1199 // A<T, T> have identical types when A is declared as:
1200 //
1201 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001202 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001203 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001204 Converted.getFlatArguments(),
1205 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001206
Douglas Gregora8e02e72009-07-28 23:00:59 +00001207 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001208 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001209 // In the future, we need to teach getTemplateSpecializationType to only
1210 // build the canonical type and return that to us.
1211 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001212 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001213 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001214 // Find the class template specialization declaration that
1215 // corresponds to these arguments.
1216 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001217 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001218 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001219 Converted.flatSize(),
1220 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001221 void *InsertPos = 0;
1222 ClassTemplateSpecializationDecl *Decl
1223 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1224 if (!Decl) {
1225 // This is the first time we have referenced this class template
1226 // specialization. Create the canonical declaration and add it to
1227 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001228 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001229 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001230 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001231 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001232 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001233 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1234 Decl->setLexicalDeclContext(CurContext);
1235 }
1236
1237 CanonType = Context.getTypeDeclType(Decl);
1238 }
Mike Stump11289f42009-09-09 15:08:12 +00001239
Douglas Gregorc40290e2009-03-09 23:48:35 +00001240 // Build the fully-sugared type for this class template
1241 // specialization, which refers back to the class template
1242 // specialization we created or found.
Douglas Gregordc572a32009-03-30 22:58:21 +00001243 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1244 NumTemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001245}
1246
Douglas Gregor67a65642009-02-17 23:15:12 +00001247Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001248Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001249 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001250 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001251 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001252 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001253
Douglas Gregorc40290e2009-03-09 23:48:35 +00001254 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00001255 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001256 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001257
Douglas Gregordc572a32009-03-30 22:58:21 +00001258 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +00001259 TemplateArgs.data(),
1260 TemplateArgs.size(),
Douglas Gregordc572a32009-03-30 22:58:21 +00001261 RAngleLoc);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001262 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001263
1264 if (Result.isNull())
1265 return true;
1266
John McCall0ad16662009-10-29 08:12:44 +00001267 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1268 TemplateSpecializationTypeLoc TL
1269 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1270 TL.setTemplateNameLoc(TemplateLoc);
1271 TL.setLAngleLoc(LAngleLoc);
1272 TL.setRAngleLoc(RAngleLoc);
1273 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1274 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1275
1276 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001277}
John McCall06f6fe8d2009-09-04 01:14:41 +00001278
John McCalld8fe9af2009-09-08 17:47:29 +00001279Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1280 TagUseKind TUK,
1281 DeclSpec::TST TagSpec,
1282 SourceLocation TagLoc) {
1283 if (TypeResult.isInvalid())
1284 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001285
John McCall0ad16662009-10-29 08:12:44 +00001286 // FIXME: preserve source info, ideally without copying the DI.
1287 DeclaratorInfo *DI;
1288 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001289
John McCalld8fe9af2009-09-08 17:47:29 +00001290 // Verify the tag specifier.
1291 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001292
John McCalld8fe9af2009-09-08 17:47:29 +00001293 if (const RecordType *RT = Type->getAs<RecordType>()) {
1294 RecordDecl *D = RT->getDecl();
1295
1296 IdentifierInfo *Id = D->getIdentifier();
1297 assert(Id && "templated class must have an identifier");
1298
1299 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1300 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001301 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001302 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1303 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001304 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001305 }
1306 }
1307
John McCalld8fe9af2009-09-08 17:47:29 +00001308 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1309
1310 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001311}
1312
Douglas Gregord019ff62009-10-22 17:20:55 +00001313Sema::OwningExprResult Sema::BuildTemplateIdExpr(NestedNameSpecifier *Qualifier,
1314 SourceRange QualifierRange,
1315 TemplateName Template,
Douglas Gregora727cb92009-06-30 22:34:41 +00001316 SourceLocation TemplateNameLoc,
1317 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001318 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001319 unsigned NumTemplateArgs,
1320 SourceLocation RAngleLoc) {
1321 // FIXME: Can we do any checking at this point? I guess we could check the
1322 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001323 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001324 // though.
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001325
1326 // Cope with an implicit member access in a C++ non-static member function.
1327 NamedDecl *D = Template.getAsTemplateDecl();
1328 if (!D)
1329 D = Template.getAsOverloadedFunctionDecl();
1330
Douglas Gregord019ff62009-10-22 17:20:55 +00001331 CXXScopeSpec SS;
1332 SS.setRange(QualifierRange);
1333 SS.setScopeRep(Qualifier);
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001334 QualType ThisType, MemberType;
Douglas Gregord019ff62009-10-22 17:20:55 +00001335 if (D && isImplicitMemberReference(&SS, D, TemplateNameLoc,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001336 ThisType, MemberType)) {
1337 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
1338 return Owned(MemberExpr::Create(Context, This, true,
Douglas Gregord019ff62009-10-22 17:20:55 +00001339 Qualifier, QualifierRange,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001340 D, TemplateNameLoc, true,
1341 LAngleLoc, TemplateArgs,
1342 NumTemplateArgs, RAngleLoc,
1343 Context.OverloadTy));
1344 }
1345
Douglas Gregord019ff62009-10-22 17:20:55 +00001346 return Owned(TemplateIdRefExpr::Create(Context, Context.OverloadTy,
1347 Qualifier, QualifierRange,
Douglas Gregora727cb92009-06-30 22:34:41 +00001348 Template, TemplateNameLoc, LAngleLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001349 TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001350 NumTemplateArgs, RAngleLoc));
1351}
1352
Douglas Gregord019ff62009-10-22 17:20:55 +00001353Sema::OwningExprResult Sema::ActOnTemplateIdExpr(const CXXScopeSpec &SS,
1354 TemplateTy TemplateD,
Douglas Gregora727cb92009-06-30 22:34:41 +00001355 SourceLocation TemplateNameLoc,
1356 SourceLocation LAngleLoc,
1357 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora727cb92009-06-30 22:34:41 +00001358 SourceLocation RAngleLoc) {
1359 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001360
Douglas Gregora727cb92009-06-30 22:34:41 +00001361 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00001362 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001363 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001364 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001365
Douglas Gregord019ff62009-10-22 17:20:55 +00001366 return BuildTemplateIdExpr((NestedNameSpecifier *)SS.getScopeRep(),
1367 SS.getRange(),
1368 Template, TemplateNameLoc, LAngleLoc,
Douglas Gregora727cb92009-06-30 22:34:41 +00001369 TemplateArgs.data(), TemplateArgs.size(),
1370 RAngleLoc);
1371}
1372
Douglas Gregorb67535d2009-03-31 00:43:58 +00001373/// \brief Form a dependent template name.
1374///
1375/// This action forms a dependent template name given the template
1376/// name and its (presumably dependent) scope specifier. For
1377/// example, given "MetaFun::template apply", the scope specifier \p
1378/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1379/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001380Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001381Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001382 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001383 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001384 TypeTy *ObjectType,
1385 bool EnteringContext) {
Mike Stump11289f42009-09-09 15:08:12 +00001386 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001387 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001388 (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001389 // C++0x [temp.names]p5:
1390 // If a name prefixed by the keyword template is not the name of
1391 // a template, the program is ill-formed. [Note: the keyword
1392 // template may not be applied to non-template members of class
1393 // templates. -end note ] [ Note: as is the case with the
1394 // typename prefix, the template prefix is allowed in cases
1395 // where it is not strictly necessary; i.e., when the
1396 // nested-name-specifier or the expression on the left of the ->
1397 // or . is not dependent on a template-parameter, or the use
1398 // does not appear in the scope of a template. -end note]
1399 //
1400 // Note: C++03 was more strict here, because it banned the use of
1401 // the "template" keyword prior to a template-name that was not a
1402 // dependent name. C++ DR468 relaxed this requirement (the
1403 // "template" keyword is now permitted). We follow the C++0x
1404 // rules, even in C++03 mode, retroactively applying the DR.
1405 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001406 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001407 EnteringContext, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001408 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001409 Diag(Name.getSourceRange().getBegin(),
1410 diag::err_template_kw_refers_to_non_template)
1411 << GetNameFromUnqualifiedId(Name)
1412 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001413 return TemplateTy();
1414 }
1415
1416 return Template;
1417 }
1418
Mike Stump11289f42009-09-09 15:08:12 +00001419 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001420 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001421
1422 switch (Name.getKind()) {
1423 case UnqualifiedId::IK_Identifier:
1424 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1425 Name.Identifier));
1426
Douglas Gregor71395fa2009-11-04 00:56:37 +00001427 case UnqualifiedId::IK_OperatorFunctionId:
1428 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1429 Name.OperatorFunctionId.Operator));
1430
Douglas Gregor3cf81312009-11-03 23:16:33 +00001431 default:
1432 break;
1433 }
1434
1435 Diag(Name.getSourceRange().getBegin(),
1436 diag::err_template_kw_refers_to_non_template)
1437 << GetNameFromUnqualifiedId(Name)
1438 << Name.getSourceRange();
1439 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001440}
1441
Mike Stump11289f42009-09-09 15:08:12 +00001442bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001443 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001444 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001445 const TemplateArgument &Arg = AL.getArgument();
1446
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001447 // Check template type parameter.
1448 if (Arg.getKind() != TemplateArgument::Type) {
1449 // C++ [temp.arg.type]p1:
1450 // A template-argument for a template-parameter which is a
1451 // type shall be a type-id.
1452
1453 // We have a template type parameter but the template argument
1454 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001455 SourceRange SR = AL.getSourceRange();
1456 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001457 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001458
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001459 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001460 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001461
John McCall0ad16662009-10-29 08:12:44 +00001462 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001463 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001464
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001465 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001466 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001467 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001468 return false;
1469}
1470
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001471/// \brief Substitute template arguments into the default template argument for
1472/// the given template type parameter.
1473///
1474/// \param SemaRef the semantic analysis object for which we are performing
1475/// the substitution.
1476///
1477/// \param Template the template that we are synthesizing template arguments
1478/// for.
1479///
1480/// \param TemplateLoc the location of the template name that started the
1481/// template-id we are checking.
1482///
1483/// \param RAngleLoc the location of the right angle bracket ('>') that
1484/// terminates the template-id.
1485///
1486/// \param Param the template template parameter whose default we are
1487/// substituting into.
1488///
1489/// \param Converted the list of template arguments provided for template
1490/// parameters that precede \p Param in the template parameter list.
1491///
1492/// \returns the substituted template argument, or NULL if an error occurred.
1493static DeclaratorInfo *
1494SubstDefaultTemplateArgument(Sema &SemaRef,
1495 TemplateDecl *Template,
1496 SourceLocation TemplateLoc,
1497 SourceLocation RAngleLoc,
1498 TemplateTypeParmDecl *Param,
1499 TemplateArgumentListBuilder &Converted) {
1500 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1501
1502 // If the argument type is dependent, instantiate it now based
1503 // on the previously-computed template arguments.
1504 if (ArgType->getType()->isDependentType()) {
1505 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1506 /*TakeArgs=*/false);
1507
1508 MultiLevelTemplateArgumentList AllTemplateArgs
1509 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1510
1511 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1512 Template, Converted.getFlatArguments(),
1513 Converted.flatSize(),
1514 SourceRange(TemplateLoc, RAngleLoc));
1515
1516 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1517 Param->getDefaultArgumentLoc(),
1518 Param->getDeclName());
1519 }
1520
1521 return ArgType;
1522}
1523
1524/// \brief Substitute template arguments into the default template argument for
1525/// the given non-type template parameter.
1526///
1527/// \param SemaRef the semantic analysis object for which we are performing
1528/// the substitution.
1529///
1530/// \param Template the template that we are synthesizing template arguments
1531/// for.
1532///
1533/// \param TemplateLoc the location of the template name that started the
1534/// template-id we are checking.
1535///
1536/// \param RAngleLoc the location of the right angle bracket ('>') that
1537/// terminates the template-id.
1538///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001539/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001540/// substituting into.
1541///
1542/// \param Converted the list of template arguments provided for template
1543/// parameters that precede \p Param in the template parameter list.
1544///
1545/// \returns the substituted template argument, or NULL if an error occurred.
1546static Sema::OwningExprResult
1547SubstDefaultTemplateArgument(Sema &SemaRef,
1548 TemplateDecl *Template,
1549 SourceLocation TemplateLoc,
1550 SourceLocation RAngleLoc,
1551 NonTypeTemplateParmDecl *Param,
1552 TemplateArgumentListBuilder &Converted) {
1553 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1554 /*TakeArgs=*/false);
1555
1556 MultiLevelTemplateArgumentList AllTemplateArgs
1557 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1558
1559 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1560 Template, Converted.getFlatArguments(),
1561 Converted.flatSize(),
1562 SourceRange(TemplateLoc, RAngleLoc));
1563
1564 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1565}
1566
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001567/// \brief Substitute template arguments into the default template argument for
1568/// the given template template parameter.
1569///
1570/// \param SemaRef the semantic analysis object for which we are performing
1571/// the substitution.
1572///
1573/// \param Template the template that we are synthesizing template arguments
1574/// for.
1575///
1576/// \param TemplateLoc the location of the template name that started the
1577/// template-id we are checking.
1578///
1579/// \param RAngleLoc the location of the right angle bracket ('>') that
1580/// terminates the template-id.
1581///
1582/// \param Param the template template parameter whose default we are
1583/// substituting into.
1584///
1585/// \param Converted the list of template arguments provided for template
1586/// parameters that precede \p Param in the template parameter list.
1587///
1588/// \returns the substituted template argument, or NULL if an error occurred.
1589static TemplateName
1590SubstDefaultTemplateArgument(Sema &SemaRef,
1591 TemplateDecl *Template,
1592 SourceLocation TemplateLoc,
1593 SourceLocation RAngleLoc,
1594 TemplateTemplateParmDecl *Param,
1595 TemplateArgumentListBuilder &Converted) {
1596 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1597 /*TakeArgs=*/false);
1598
1599 MultiLevelTemplateArgumentList AllTemplateArgs
1600 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1601
1602 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1603 Template, Converted.getFlatArguments(),
1604 Converted.flatSize(),
1605 SourceRange(TemplateLoc, RAngleLoc));
1606
1607 return SemaRef.SubstTemplateName(
1608 Param->getDefaultArgument().getArgument().getAsTemplate(),
1609 Param->getDefaultArgument().getTemplateNameLoc(),
1610 AllTemplateArgs);
1611}
1612
Douglas Gregorda0fb532009-11-11 19:31:23 +00001613/// \brief Check that the given template argument corresponds to the given
1614/// template parameter.
1615bool Sema::CheckTemplateArgument(NamedDecl *Param,
1616 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001617 TemplateDecl *Template,
1618 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001619 SourceLocation RAngleLoc,
1620 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001621 // Check template type parameters.
1622 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001623 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001624
Douglas Gregoreebed722009-11-11 19:41:09 +00001625 // Check non-type template parameters.
1626 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001627 // Do substitution on the type of the non-type template parameter
1628 // with the template arguments we've seen thus far.
1629 QualType NTTPType = NTTP->getType();
1630 if (NTTPType->isDependentType()) {
1631 // Do substitution on the type of the non-type template parameter.
1632 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1633 NTTP, Converted.getFlatArguments(),
1634 Converted.flatSize(),
1635 SourceRange(TemplateLoc, RAngleLoc));
1636
1637 TemplateArgumentList TemplateArgs(Context, Converted,
1638 /*TakeArgs=*/false);
1639 NTTPType = SubstType(NTTPType,
1640 MultiLevelTemplateArgumentList(TemplateArgs),
1641 NTTP->getLocation(),
1642 NTTP->getDeclName());
1643 // If that worked, check the non-type template parameter type
1644 // for validity.
1645 if (!NTTPType.isNull())
1646 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1647 NTTP->getLocation());
1648 if (NTTPType.isNull())
1649 return true;
1650 }
1651
1652 switch (Arg.getArgument().getKind()) {
1653 case TemplateArgument::Null:
1654 assert(false && "Should never see a NULL template argument here");
1655 return true;
1656
1657 case TemplateArgument::Expression: {
1658 Expr *E = Arg.getArgument().getAsExpr();
1659 TemplateArgument Result;
1660 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1661 return true;
1662
1663 Converted.Append(Result);
1664 break;
1665 }
1666
1667 case TemplateArgument::Declaration:
1668 case TemplateArgument::Integral:
1669 // We've already checked this template argument, so just copy
1670 // it to the list of converted arguments.
1671 Converted.Append(Arg.getArgument());
1672 break;
1673
1674 case TemplateArgument::Template:
1675 // We were given a template template argument. It may not be ill-formed;
1676 // see below.
1677 if (DependentTemplateName *DTN
1678 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1679 // We have a template argument such as \c T::template X, which we
1680 // parsed as a template template argument. However, since we now
1681 // know that we need a non-type template argument, convert this
1682 // template name into an expression.
John McCall8cd78132009-11-19 22:55:06 +00001683 Expr *E = new (Context) DependentScopeDeclRefExpr(DTN->getIdentifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00001684 Context.DependentTy,
1685 Arg.getTemplateNameLoc(),
1686 Arg.getTemplateQualifierRange(),
1687 DTN->getQualifier(),
1688 /*isAddressOfOperand=*/false);
1689
1690 TemplateArgument Result;
1691 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1692 return true;
1693
1694 Converted.Append(Result);
1695 break;
1696 }
1697
1698 // We have a template argument that actually does refer to a class
1699 // template, template alias, or template template parameter, and
1700 // therefore cannot be a non-type template argument.
1701 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1702 << Arg.getSourceRange();
1703
1704 Diag(Param->getLocation(), diag::note_template_param_here);
1705 return true;
1706
1707 case TemplateArgument::Type: {
1708 // We have a non-type template parameter but the template
1709 // argument is a type.
1710
1711 // C++ [temp.arg]p2:
1712 // In a template-argument, an ambiguity between a type-id and
1713 // an expression is resolved to a type-id, regardless of the
1714 // form of the corresponding template-parameter.
1715 //
1716 // We warn specifically about this case, since it can be rather
1717 // confusing for users.
1718 QualType T = Arg.getArgument().getAsType();
1719 SourceRange SR = Arg.getSourceRange();
1720 if (T->isFunctionType())
1721 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1722 else
1723 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1724 Diag(Param->getLocation(), diag::note_template_param_here);
1725 return true;
1726 }
1727
1728 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00001729 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001730 break;
1731 }
1732
1733 return false;
1734 }
1735
1736
1737 // Check template template parameters.
1738 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1739
1740 // Substitute into the template parameter list of the template
1741 // template parameter, since previously-supplied template arguments
1742 // may appear within the template template parameter.
1743 {
1744 // Set up a template instantiation context.
1745 LocalInstantiationScope Scope(*this);
1746 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1747 TempParm, Converted.getFlatArguments(),
1748 Converted.flatSize(),
1749 SourceRange(TemplateLoc, RAngleLoc));
1750
1751 TemplateArgumentList TemplateArgs(Context, Converted,
1752 /*TakeArgs=*/false);
1753 TempParm = cast_or_null<TemplateTemplateParmDecl>(
1754 SubstDecl(TempParm, CurContext,
1755 MultiLevelTemplateArgumentList(TemplateArgs)));
1756 if (!TempParm)
1757 return true;
1758
1759 // FIXME: TempParam is leaked.
1760 }
1761
1762 switch (Arg.getArgument().getKind()) {
1763 case TemplateArgument::Null:
1764 assert(false && "Should never see a NULL template argument here");
1765 return true;
1766
1767 case TemplateArgument::Template:
1768 if (CheckTemplateArgument(TempParm, Arg))
1769 return true;
1770
1771 Converted.Append(Arg.getArgument());
1772 break;
1773
1774 case TemplateArgument::Expression:
1775 case TemplateArgument::Type:
1776 // We have a template template parameter but the template
1777 // argument does not refer to a template.
1778 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1779 return true;
1780
1781 case TemplateArgument::Declaration:
1782 llvm::llvm_unreachable(
1783 "Declaration argument with template template parameter");
1784 break;
1785 case TemplateArgument::Integral:
1786 llvm::llvm_unreachable(
1787 "Integral argument with template template parameter");
1788 break;
1789
1790 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00001791 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001792 break;
1793 }
1794
1795 return false;
1796}
1797
Douglas Gregord32e0282009-02-09 23:23:08 +00001798/// \brief Check that the given template argument list is well-formed
1799/// for specializing the given template.
1800bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1801 SourceLocation TemplateLoc,
1802 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001803 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001804 unsigned NumTemplateArgs,
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001805 SourceLocation RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001806 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001807 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001808 TemplateParameterList *Params = Template->getTemplateParameters();
1809 unsigned NumParams = Params->size();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001810 unsigned NumArgs = NumTemplateArgs;
Douglas Gregord32e0282009-02-09 23:23:08 +00001811 bool Invalid = false;
1812
Mike Stump11289f42009-09-09 15:08:12 +00001813 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001814 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001815
Anders Carlsson15201f12009-06-13 02:08:00 +00001816 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001817 (NumArgs < Params->getMinRequiredArguments() &&
1818 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001819 // FIXME: point at either the first arg beyond what we can handle,
1820 // or the '>', depending on whether we have too many or too few
1821 // arguments.
1822 SourceRange Range;
1823 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001824 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001825 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1826 << (NumArgs > NumParams)
1827 << (isa<ClassTemplateDecl>(Template)? 0 :
1828 isa<FunctionTemplateDecl>(Template)? 1 :
1829 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1830 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001831 Diag(Template->getLocation(), diag::note_template_decl_here)
1832 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001833 Invalid = true;
1834 }
Mike Stump11289f42009-09-09 15:08:12 +00001835
1836 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001837 // [...] The type and form of each template-argument specified in
1838 // a template-id shall match the type and form specified for the
1839 // corresponding parameter declared by the template in its
1840 // template-parameter-list.
1841 unsigned ArgIdx = 0;
1842 for (TemplateParameterList::iterator Param = Params->begin(),
1843 ParamEnd = Params->end();
1844 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001845 if (ArgIdx > NumArgs && PartialTemplateArgs)
1846 break;
Mike Stump11289f42009-09-09 15:08:12 +00001847
Douglas Gregoreebed722009-11-11 19:41:09 +00001848 // If we have a template parameter pack, check every remaining template
1849 // argument against that template parameter pack.
1850 if ((*Param)->isTemplateParameterPack()) {
1851 Converted.BeginPack();
1852 for (; ArgIdx < NumArgs; ++ArgIdx) {
1853 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
1854 TemplateLoc, RAngleLoc, Converted)) {
1855 Invalid = true;
1856 break;
1857 }
1858 }
1859 Converted.EndPack();
1860 continue;
1861 }
1862
Douglas Gregor84d49a22009-11-11 21:54:23 +00001863 if (ArgIdx < NumArgs) {
1864 // Check the template argument we were given.
1865 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
1866 TemplateLoc, RAngleLoc, Converted))
1867 return true;
1868
1869 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001870 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00001871
Douglas Gregor84d49a22009-11-11 21:54:23 +00001872 // We have a default template argument that we will use.
1873 TemplateArgumentLoc Arg;
1874
1875 // Retrieve the default template argument from the template
1876 // parameter. For each kind of template parameter, we substitute the
1877 // template arguments provided thus far and any "outer" template arguments
1878 // (when the template parameter was part of a nested template) into
1879 // the default argument.
1880 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1881 if (!TTP->hasDefaultArgument()) {
1882 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1883 break;
1884 }
1885
1886 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
1887 Template,
1888 TemplateLoc,
1889 RAngleLoc,
1890 TTP,
1891 Converted);
1892 if (!ArgType)
1893 return true;
1894
1895 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
1896 ArgType);
1897 } else if (NonTypeTemplateParmDecl *NTTP
1898 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1899 if (!NTTP->hasDefaultArgument()) {
1900 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1901 break;
1902 }
1903
1904 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
1905 TemplateLoc,
1906 RAngleLoc,
1907 NTTP,
1908 Converted);
1909 if (E.isInvalid())
1910 return true;
1911
1912 Expr *Ex = E.takeAs<Expr>();
1913 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
1914 } else {
1915 TemplateTemplateParmDecl *TempParm
1916 = cast<TemplateTemplateParmDecl>(*Param);
1917
1918 if (!TempParm->hasDefaultArgument()) {
1919 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1920 break;
1921 }
1922
1923 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
1924 TemplateLoc,
1925 RAngleLoc,
1926 TempParm,
1927 Converted);
1928 if (Name.isNull())
1929 return true;
1930
1931 Arg = TemplateArgumentLoc(TemplateArgument(Name),
1932 TempParm->getDefaultArgument().getTemplateQualifierRange(),
1933 TempParm->getDefaultArgument().getTemplateNameLoc());
1934 }
1935
1936 // Introduce an instantiation record that describes where we are using
1937 // the default template argument.
1938 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
1939 Converted.getFlatArguments(),
1940 Converted.flatSize(),
1941 SourceRange(TemplateLoc, RAngleLoc));
1942
1943 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00001944 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001945 RAngleLoc, Converted))
1946 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00001947 }
1948
1949 return Invalid;
1950}
1951
1952/// \brief Check a template argument against its corresponding
1953/// template type parameter.
1954///
1955/// This routine implements the semantics of C++ [temp.arg.type]. It
1956/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001957bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001958 DeclaratorInfo *ArgInfo) {
1959 assert(ArgInfo && "invalid DeclaratorInfo");
1960 QualType Arg = ArgInfo->getType();
1961
Douglas Gregord32e0282009-02-09 23:23:08 +00001962 // C++ [temp.arg.type]p2:
1963 // A local type, a type with no linkage, an unnamed type or a type
1964 // compounded from any of these types shall not be used as a
1965 // template-argument for a template type-parameter.
1966 //
1967 // FIXME: Perform the recursive and no-linkage type checks.
1968 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001969 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001970 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001971 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001972 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00001973 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
1974 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1975 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
1976 << QualType(Tag, 0) << SR;
1977 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001978 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00001979 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1980 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00001981 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1982 return true;
1983 }
1984
1985 return false;
1986}
1987
Douglas Gregorccb07762009-02-11 19:52:55 +00001988/// \brief Checks whether the given template argument is the address
1989/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001990bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1991 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001992 bool Invalid = false;
1993
1994 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00001995 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00001996 Arg = Cast->getSubExpr();
1997
Sebastian Redl576fd422009-05-10 18:38:11 +00001998 // C++0x allows nullptr, and there's no further checking to be done for that.
1999 if (Arg->getType()->isNullPtrType())
2000 return false;
2001
Douglas Gregorccb07762009-02-11 19:52:55 +00002002 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002003 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002004 // A template-argument for a non-type, non-template
2005 // template-parameter shall be one of: [...]
2006 //
2007 // -- the address of an object or function with external
2008 // linkage, including function templates and function
2009 // template-ids but excluding non-static class members,
2010 // expressed as & id-expression where the & is optional if
2011 // the name refers to a function or array, or if the
2012 // corresponding template-parameter is a reference; or
2013 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002014
Douglas Gregorccb07762009-02-11 19:52:55 +00002015 // Ignore (and complain about) any excess parentheses.
2016 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2017 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002018 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002019 diag::err_template_arg_extra_parens)
2020 << Arg->getSourceRange();
2021 Invalid = true;
2022 }
2023
2024 Arg = Parens->getSubExpr();
2025 }
2026
2027 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2028 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2029 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2030 } else
2031 DRE = dyn_cast<DeclRefExpr>(Arg);
2032
2033 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002034 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002035 diag::err_template_arg_not_object_or_func_form)
2036 << Arg->getSourceRange();
2037
2038 // Cannot refer to non-static data members
2039 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2040 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2041 << Field << Arg->getSourceRange();
2042
2043 // Cannot refer to non-static member functions
2044 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2045 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002046 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002047 diag::err_template_arg_method)
2048 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002049
Douglas Gregorccb07762009-02-11 19:52:55 +00002050 // Functions must have external linkage.
2051 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2052 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00002053 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002054 diag::err_template_arg_function_not_extern)
2055 << Func << Arg->getSourceRange();
2056 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2057 << true;
2058 return true;
2059 }
2060
2061 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002062 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002063 return Invalid;
2064 }
2065
2066 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2067 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00002068 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002069 diag::err_template_arg_object_not_extern)
2070 << Var << Arg->getSourceRange();
2071 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2072 << true;
2073 return true;
2074 }
2075
2076 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002077 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002078 return Invalid;
2079 }
Mike Stump11289f42009-09-09 15:08:12 +00002080
Douglas Gregorccb07762009-02-11 19:52:55 +00002081 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002082 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002083 diag::err_template_arg_not_object_or_func)
2084 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002085 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002086 diag::note_template_arg_refers_here);
2087 return true;
2088}
2089
2090/// \brief Checks whether the given template argument is a pointer to
2091/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002092bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2093 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002094 bool Invalid = false;
2095
2096 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002097 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002098 Arg = Cast->getSubExpr();
2099
Sebastian Redl576fd422009-05-10 18:38:11 +00002100 // C++0x allows nullptr, and there's no further checking to be done for that.
2101 if (Arg->getType()->isNullPtrType())
2102 return false;
2103
Douglas Gregorccb07762009-02-11 19:52:55 +00002104 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002105 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002106 // A template-argument for a non-type, non-template
2107 // template-parameter shall be one of: [...]
2108 //
2109 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002110 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002111
2112 // Ignore (and complain about) any excess parentheses.
2113 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2114 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002115 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002116 diag::err_template_arg_extra_parens)
2117 << Arg->getSourceRange();
2118 Invalid = true;
2119 }
2120
2121 Arg = Parens->getSubExpr();
2122 }
2123
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002124 // A pointer-to-member constant written &Class::member.
2125 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002126 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2127 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2128 if (DRE && !DRE->getQualifier())
2129 DRE = 0;
2130 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002131 }
2132 // A constant of pointer-to-member type.
2133 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2134 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2135 if (VD->getType()->isMemberPointerType()) {
2136 if (isa<NonTypeTemplateParmDecl>(VD) ||
2137 (isa<VarDecl>(VD) &&
2138 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2139 if (Arg->isTypeDependent() || Arg->isValueDependent())
2140 Converted = TemplateArgument(Arg->Retain());
2141 else
2142 Converted = TemplateArgument(VD->getCanonicalDecl());
2143 return Invalid;
2144 }
2145 }
2146 }
2147
2148 DRE = 0;
2149 }
2150
Douglas Gregorccb07762009-02-11 19:52:55 +00002151 if (!DRE)
2152 return Diag(Arg->getSourceRange().getBegin(),
2153 diag::err_template_arg_not_pointer_to_member_form)
2154 << Arg->getSourceRange();
2155
2156 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2157 assert((isa<FieldDecl>(DRE->getDecl()) ||
2158 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2159 "Only non-static member pointers can make it here");
2160
2161 // Okay: this is the address of a non-static member, and therefore
2162 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002163 if (Arg->isTypeDependent() || Arg->isValueDependent())
2164 Converted = TemplateArgument(Arg->Retain());
2165 else
2166 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002167 return Invalid;
2168 }
2169
2170 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002171 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002172 diag::err_template_arg_not_pointer_to_member_form)
2173 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002174 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002175 diag::note_template_arg_refers_here);
2176 return true;
2177}
2178
Douglas Gregord32e0282009-02-09 23:23:08 +00002179/// \brief Check a template argument against its corresponding
2180/// non-type template parameter.
2181///
Douglas Gregor463421d2009-03-03 04:44:36 +00002182/// This routine implements the semantics of C++ [temp.arg.nontype].
2183/// It returns true if an error occurred, and false otherwise. \p
2184/// InstantiatedParamType is the type of the non-type template
2185/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002186///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002187/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002188bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002189 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002190 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002191 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2192
Douglas Gregor86560402009-02-10 23:36:10 +00002193 // If either the parameter has a dependent type or the argument is
2194 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002195 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002196 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2197 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002198 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002199 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002200 }
Douglas Gregor86560402009-02-10 23:36:10 +00002201
2202 // C++ [temp.arg.nontype]p5:
2203 // The following conversions are performed on each expression used
2204 // as a non-type template-argument. If a non-type
2205 // template-argument cannot be converted to the type of the
2206 // corresponding template-parameter then the program is
2207 // ill-formed.
2208 //
2209 // -- for a non-type template-parameter of integral or
2210 // enumeration type, integral promotions (4.5) and integral
2211 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002212 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002213 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002214 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002215 // C++ [temp.arg.nontype]p1:
2216 // A template-argument for a non-type, non-template
2217 // template-parameter shall be one of:
2218 //
2219 // -- an integral constant-expression of integral or enumeration
2220 // type; or
2221 // -- the name of a non-type template-parameter; or
2222 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002223 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002224 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002225 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002226 diag::err_template_arg_not_integral_or_enumeral)
2227 << ArgType << Arg->getSourceRange();
2228 Diag(Param->getLocation(), diag::note_template_param_here);
2229 return true;
2230 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002231 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002232 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2233 << ArgType << Arg->getSourceRange();
2234 return true;
2235 }
2236
2237 // FIXME: We need some way to more easily get the unqualified form
2238 // of the types without going all the way to the
2239 // canonical type.
2240 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2241 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2242 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2243 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2244
2245 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002246 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002247 // Okay: no conversion necessary
2248 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2249 !ParamType->isEnumeralType()) {
2250 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002251 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002252 } else {
2253 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002254 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002255 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002256 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002257 Diag(Param->getLocation(), diag::note_template_param_here);
2258 return true;
2259 }
2260
Douglas Gregor52aba872009-03-14 00:20:21 +00002261 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002262 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002263 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002264
2265 if (!Arg->isValueDependent()) {
2266 // Check that an unsigned parameter does not receive a negative
2267 // value.
2268 if (IntegerType->isUnsignedIntegerType()
2269 && (Value.isSigned() && Value.isNegative())) {
2270 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2271 << Value.toString(10) << Param->getType()
2272 << Arg->getSourceRange();
2273 Diag(Param->getLocation(), diag::note_template_param_here);
2274 return true;
2275 }
2276
2277 // Check that we don't overflow the template parameter type.
2278 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2279 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002280 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002281 diag::err_template_arg_too_large)
2282 << Value.toString(10) << Param->getType()
2283 << Arg->getSourceRange();
2284 Diag(Param->getLocation(), diag::note_template_param_here);
2285 return true;
2286 }
2287
2288 if (Value.getBitWidth() != AllowedBits)
2289 Value.extOrTrunc(AllowedBits);
2290 Value.setIsSigned(IntegerType->isSignedIntegerType());
2291 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002292
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002293 // Add the value of this argument to the list of converted
2294 // arguments. We use the bitwidth and signedness of the template
2295 // parameter.
2296 if (Arg->isValueDependent()) {
2297 // The argument is value-dependent. Create a new
2298 // TemplateArgument with the converted expression.
2299 Converted = TemplateArgument(Arg);
2300 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002301 }
2302
John McCall0ad16662009-10-29 08:12:44 +00002303 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002304 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002305 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002306 return false;
2307 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002308
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002309 // Handle pointer-to-function, reference-to-function, and
2310 // pointer-to-member-function all in (roughly) the same way.
2311 if (// -- For a non-type template-parameter of type pointer to
2312 // function, only the function-to-pointer conversion (4.3) is
2313 // applied. If the template-argument represents a set of
2314 // overloaded functions (or a pointer to such), the matching
2315 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002316 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002317 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002318 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002319 // -- For a non-type template-parameter of type reference to
2320 // function, no conversions apply. If the template-argument
2321 // represents a set of overloaded functions, the matching
2322 // function is selected from the set (13.4).
2323 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002324 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002325 // -- For a non-type template-parameter of type pointer to
2326 // member function, no conversions apply. If the
2327 // template-argument represents a set of overloaded member
2328 // functions, the matching member function is selected from
2329 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002330 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002331 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002332 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002333 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002334 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002335 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002336 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002337 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2338 ParamType->isMemberPointerType())) {
2339 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002340 if (ParamType->isMemberPointerType())
2341 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2342 else
2343 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002344 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002345 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002346 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002347 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002348 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002349 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2350 return true;
2351
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002352 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002353 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002354 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002355 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002356 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002357 }
2358 }
2359
Mike Stump11289f42009-09-09 15:08:12 +00002360 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002361 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002362 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002363 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002364 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002365 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002366 Diag(Param->getLocation(), diag::note_template_param_here);
2367 return true;
2368 }
Mike Stump11289f42009-09-09 15:08:12 +00002369
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002370 if (ParamType->isMemberPointerType())
2371 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002372
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002373 NamedDecl *Entity = 0;
2374 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2375 return true;
2376
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002377 if (Entity)
2378 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002379 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002380 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002381 }
2382
Chris Lattner696197c2009-02-20 21:37:53 +00002383 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002384 // -- for a non-type template-parameter of type pointer to
2385 // object, qualification conversions (4.4) and the
2386 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002387 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002388 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002389 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002390
Sebastian Redl576fd422009-05-10 18:38:11 +00002391 if (ArgType->isNullPtrType()) {
2392 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002393 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002394 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002395 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002396 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002397 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002398
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002399 if (IsQualificationConversion(ArgType, ParamType)) {
2400 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002401 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002402 }
Mike Stump11289f42009-09-09 15:08:12 +00002403
Douglas Gregor1515f762009-02-11 18:22:40 +00002404 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002405 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002406 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002407 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002408 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002409 Diag(Param->getLocation(), diag::note_template_param_here);
2410 return true;
2411 }
Mike Stump11289f42009-09-09 15:08:12 +00002412
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002413 NamedDecl *Entity = 0;
2414 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2415 return true;
2416
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002417 if (Entity)
2418 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002419 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002420 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002421 }
Mike Stump11289f42009-09-09 15:08:12 +00002422
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002423 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002424 // -- For a non-type template-parameter of type reference to
2425 // object, no conversions apply. The type referred to by the
2426 // reference may be more cv-qualified than the (otherwise
2427 // identical) type of the template-argument. The
2428 // template-parameter is bound directly to the
2429 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002430 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002431 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002432
Douglas Gregor1515f762009-02-11 18:22:40 +00002433 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002434 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002435 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002436 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002437 << Arg->getSourceRange();
2438 Diag(Param->getLocation(), diag::note_template_param_here);
2439 return true;
2440 }
2441
Mike Stump11289f42009-09-09 15:08:12 +00002442 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002443 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2444 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002445
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002446 if ((ParamQuals | ArgQuals) != ParamQuals) {
2447 Diag(Arg->getSourceRange().getBegin(),
2448 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002449 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002450 << Arg->getSourceRange();
2451 Diag(Param->getLocation(), diag::note_template_param_here);
2452 return true;
2453 }
Mike Stump11289f42009-09-09 15:08:12 +00002454
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002455 NamedDecl *Entity = 0;
2456 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2457 return true;
2458
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002459 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002460 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002461 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002462 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002463
2464 // -- For a non-type template-parameter of type pointer to data
2465 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002466 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002467 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2468
Douglas Gregor1515f762009-02-11 18:22:40 +00002469 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002470 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002471 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002472 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002473 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002474 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002475 } else {
2476 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002477 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002478 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002479 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002480 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002481 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002482 }
2483
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002484 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002485}
2486
2487/// \brief Check a template argument against its corresponding
2488/// template template parameter.
2489///
2490/// This routine implements the semantics of C++ [temp.arg.template].
2491/// It returns true if an error occurred, and false otherwise.
2492bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002493 const TemplateArgumentLoc &Arg) {
2494 TemplateName Name = Arg.getArgument().getAsTemplate();
2495 TemplateDecl *Template = Name.getAsTemplateDecl();
2496 if (!Template) {
2497 // Any dependent template name is fine.
2498 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2499 return false;
2500 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002501
2502 // C++ [temp.arg.template]p1:
2503 // A template-argument for a template template-parameter shall be
2504 // the name of a class template, expressed as id-expression. Only
2505 // primary class templates are considered when matching the
2506 // template template argument with the corresponding parameter;
2507 // partial specializations are not considered even if their
2508 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002509 //
2510 // Note that we also allow template template parameters here, which
2511 // will happen when we are dealing with, e.g., class template
2512 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002513 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002514 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002515 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002516 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002517 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002518 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002519 << Template;
2520 }
2521
2522 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2523 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002524 true,
2525 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002526 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002527}
2528
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002529/// \brief Determine whether the given template parameter lists are
2530/// equivalent.
2531///
Mike Stump11289f42009-09-09 15:08:12 +00002532/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002533/// source code as part of a new template declaration.
2534///
2535/// \param Old The old template parameter list, typically found via
2536/// name lookup of the template declared with this template parameter
2537/// list.
2538///
2539/// \param Complain If true, this routine will produce a diagnostic if
2540/// the template parameter lists are not equivalent.
2541///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002542/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00002543///
2544/// \param TemplateArgLoc If this source location is valid, then we
2545/// are actually checking the template parameter list of a template
2546/// argument (New) against the template parameter list of its
2547/// corresponding template template parameter (Old). We produce
2548/// slightly different diagnostics in this scenario.
2549///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002550/// \returns True if the template parameter lists are equal, false
2551/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002552bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002553Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2554 TemplateParameterList *Old,
2555 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002556 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002557 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002558 if (Old->size() != New->size()) {
2559 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002560 unsigned NextDiag = diag::err_template_param_list_different_arity;
2561 if (TemplateArgLoc.isValid()) {
2562 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2563 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002564 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002565 Diag(New->getTemplateLoc(), NextDiag)
2566 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002567 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002568 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002569 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002570 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002571 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2572 }
2573
2574 return false;
2575 }
2576
2577 for (TemplateParameterList::iterator OldParm = Old->begin(),
2578 OldParmEnd = Old->end(), NewParm = New->begin();
2579 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2580 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002581 if (Complain) {
2582 unsigned NextDiag = diag::err_template_param_different_kind;
2583 if (TemplateArgLoc.isValid()) {
2584 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2585 NextDiag = diag::note_template_param_different_kind;
2586 }
2587 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002588 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00002589 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002590 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00002591 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002592 return false;
2593 }
2594
2595 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2596 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002597 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002598 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002599 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2600 // The types of non-type template parameters must agree.
2601 NonTypeTemplateParmDecl *NewNTTP
2602 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002603
2604 // If we are matching a template template argument to a template
2605 // template parameter and one of the non-type template parameter types
2606 // is dependent, then we must wait until template instantiation time
2607 // to actually compare the arguments.
2608 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2609 (OldNTTP->getType()->isDependentType() ||
2610 NewNTTP->getType()->isDependentType()))
2611 continue;
2612
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002613 if (Context.getCanonicalType(OldNTTP->getType()) !=
2614 Context.getCanonicalType(NewNTTP->getType())) {
2615 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002616 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2617 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002618 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002619 diag::err_template_arg_template_params_mismatch);
2620 NextDiag = diag::note_template_nontype_parm_different_type;
2621 }
2622 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002623 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002624 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00002625 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002626 diag::note_template_nontype_parm_prev_declaration)
2627 << OldNTTP->getType();
2628 }
2629 return false;
2630 }
2631 } else {
2632 // The template parameter lists of template template
2633 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002634 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002635 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002636 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002637 = cast<TemplateTemplateParmDecl>(*OldParm);
2638 TemplateTemplateParmDecl *NewTTP
2639 = cast<TemplateTemplateParmDecl>(*NewParm);
2640 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2641 OldTTP->getTemplateParameters(),
2642 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002643 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00002644 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002645 return false;
2646 }
2647 }
2648
2649 return true;
2650}
2651
2652/// \brief Check whether a template can be declared within this scope.
2653///
2654/// If the template declaration is valid in this scope, returns
2655/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002656bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002657Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002658 // Find the nearest enclosing declaration scope.
2659 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2660 (S->getFlags() & Scope::TemplateParamScope) != 0)
2661 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002662
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002663 // C++ [temp]p2:
2664 // A template-declaration can appear only as a namespace scope or
2665 // class scope declaration.
2666 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002667 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2668 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002669 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002670 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002671
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002672 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002673 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002674
2675 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2676 return false;
2677
Mike Stump11289f42009-09-09 15:08:12 +00002678 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002679 diag::err_template_outside_namespace_or_class_scope)
2680 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002681}
Douglas Gregor67a65642009-02-17 23:15:12 +00002682
Douglas Gregor54888652009-10-07 00:13:32 +00002683/// \brief Determine what kind of template specialization the given declaration
2684/// is.
2685static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2686 if (!D)
2687 return TSK_Undeclared;
2688
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002689 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2690 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002691 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2692 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002693 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2694 return Var->getTemplateSpecializationKind();
2695
Douglas Gregor54888652009-10-07 00:13:32 +00002696 return TSK_Undeclared;
2697}
2698
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002699/// \brief Check whether a specialization is well-formed in the current
2700/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002701///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002702/// This routine determines whether a template specialization can be declared
2703/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002704///
2705/// \param S the semantic analysis object for which this check is being
2706/// performed.
2707///
2708/// \param Specialized the entity being specialized or instantiated, which
2709/// may be a kind of template (class template, function template, etc.) or
2710/// a member of a class template (member function, static data member,
2711/// member class).
2712///
2713/// \param PrevDecl the previous declaration of this entity, if any.
2714///
2715/// \param Loc the location of the explicit specialization or instantiation of
2716/// this entity.
2717///
2718/// \param IsPartialSpecialization whether this is a partial specialization of
2719/// a class template.
2720///
Douglas Gregor54888652009-10-07 00:13:32 +00002721/// \returns true if there was an error that we cannot recover from, false
2722/// otherwise.
2723static bool CheckTemplateSpecializationScope(Sema &S,
2724 NamedDecl *Specialized,
2725 NamedDecl *PrevDecl,
2726 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002727 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002728 // Keep these "kind" numbers in sync with the %select statements in the
2729 // various diagnostics emitted by this routine.
2730 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002731 bool isTemplateSpecialization = false;
2732 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002733 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002734 isTemplateSpecialization = true;
2735 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002736 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002737 isTemplateSpecialization = true;
2738 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002739 EntityKind = 3;
2740 else if (isa<VarDecl>(Specialized))
2741 EntityKind = 4;
2742 else if (isa<RecordDecl>(Specialized))
2743 EntityKind = 5;
2744 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002745 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2746 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00002747 return true;
2748 }
2749
Douglas Gregorf47b9112009-02-25 22:02:03 +00002750 // C++ [temp.expl.spec]p2:
2751 // An explicit specialization shall be declared in the namespace
2752 // of which the template is a member, or, for member templates, in
2753 // the namespace of which the enclosing class or enclosing class
2754 // template is a member. An explicit specialization of a member
2755 // function, member class or static data member of a class
2756 // template shall be declared in the namespace of which the class
2757 // template is a member. Such a declaration may also be a
2758 // definition. If the declaration is not a definition, the
2759 // specialization may be defined later in the name- space in which
2760 // the explicit specialization was declared, or in a namespace
2761 // that encloses the one in which the explicit specialization was
2762 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002763 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2764 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002765 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002766 return true;
2767 }
Douglas Gregore4b05162009-10-07 17:21:34 +00002768
Douglas Gregor40fb7442009-10-07 17:30:37 +00002769 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2770 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002771 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00002772 return true;
2773 }
2774
Douglas Gregore4b05162009-10-07 17:21:34 +00002775 // C++ [temp.class.spec]p6:
2776 // A class template partial specialization may be declared or redeclared
2777 // in any namespace scope in which its definition may be defined (14.5.1
2778 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002779 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002780 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002781 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002782 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002783 if ((!PrevDecl ||
2784 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2785 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2786 // There is no prior declaration of this entity, so this
2787 // specialization must be in the same context as the template
2788 // itself.
2789 if (!DC->Equals(SpecializedContext)) {
2790 if (isa<TranslationUnitDecl>(SpecializedContext))
2791 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2792 << EntityKind << Specialized;
2793 else if (isa<NamespaceDecl>(SpecializedContext))
2794 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2795 << EntityKind << Specialized
2796 << cast<NamedDecl>(SpecializedContext);
2797
2798 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2799 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002800 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002801 }
Douglas Gregor54888652009-10-07 00:13:32 +00002802
2803 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002804 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00002805 // Note that HandleDeclarator() performs this check for explicit
2806 // specializations of function templates, static data members, and member
2807 // functions, so we skip the check here for those kinds of entities.
2808 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00002809 // Should we refactor that check, so that it occurs later?
2810 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002811 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2812 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00002813 if (isa<TranslationUnitDecl>(SpecializedContext))
2814 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2815 << EntityKind << Specialized;
2816 else if (isa<NamespaceDecl>(SpecializedContext))
2817 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2818 << EntityKind << Specialized
2819 << cast<NamedDecl>(SpecializedContext);
2820
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002821 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002822 }
Douglas Gregor54888652009-10-07 00:13:32 +00002823
2824 // FIXME: check for specialization-after-instantiation errors and such.
2825
Douglas Gregorf47b9112009-02-25 22:02:03 +00002826 return false;
2827}
Douglas Gregor54888652009-10-07 00:13:32 +00002828
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002829/// \brief Check the non-type template arguments of a class template
2830/// partial specialization according to C++ [temp.class.spec]p9.
2831///
Douglas Gregor09a30232009-06-12 22:08:06 +00002832/// \param TemplateParams the template parameters of the primary class
2833/// template.
2834///
2835/// \param TemplateArg the template arguments of the class template
2836/// partial specialization.
2837///
2838/// \param MirrorsPrimaryTemplate will be set true if the class
2839/// template partial specialization arguments are identical to the
2840/// implicit template arguments of the primary template. This is not
2841/// necessarily an error (C++0x), and it is left to the caller to diagnose
2842/// this condition when it is an error.
2843///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002844/// \returns true if there was an error, false otherwise.
2845bool Sema::CheckClassTemplatePartialSpecializationArgs(
2846 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002847 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002848 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002849 // FIXME: the interface to this function will have to change to
2850 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002851 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002852
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002853 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002854
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002855 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002856 // Determine whether the template argument list of the partial
2857 // specialization is identical to the implicit argument list of
2858 // the primary template. The caller may need to diagnostic this as
2859 // an error per C++ [temp.class.spec]p9b3.
2860 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002861 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002862 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2863 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002864 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002865 MirrorsPrimaryTemplate = false;
2866 } else if (TemplateTemplateParmDecl *TTP
2867 = dyn_cast<TemplateTemplateParmDecl>(
2868 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002869 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00002870 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002871 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002872 if (!ArgDecl ||
2873 ArgDecl->getIndex() != TTP->getIndex() ||
2874 ArgDecl->getDepth() != TTP->getDepth())
2875 MirrorsPrimaryTemplate = false;
2876 }
2877 }
2878
Mike Stump11289f42009-09-09 15:08:12 +00002879 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002880 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002881 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002882 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002883 }
2884
Anders Carlsson40c1d492009-06-13 18:20:51 +00002885 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002886 if (!ArgExpr) {
2887 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002888 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002889 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002890
2891 // C++ [temp.class.spec]p8:
2892 // A non-type argument is non-specialized if it is the name of a
2893 // non-type parameter. All other non-type arguments are
2894 // specialized.
2895 //
2896 // Below, we check the two conditions that only apply to
2897 // specialized non-type arguments, so skip any non-specialized
2898 // arguments.
2899 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002900 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002901 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002902 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002903 (Param->getIndex() != NTTP->getIndex() ||
2904 Param->getDepth() != NTTP->getDepth()))
2905 MirrorsPrimaryTemplate = false;
2906
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002907 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002908 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002909
2910 // C++ [temp.class.spec]p9:
2911 // Within the argument list of a class template partial
2912 // specialization, the following restrictions apply:
2913 // -- A partially specialized non-type argument expression
2914 // shall not involve a template parameter of the partial
2915 // specialization except when the argument expression is a
2916 // simple identifier.
2917 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002918 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002919 diag::err_dependent_non_type_arg_in_partial_spec)
2920 << ArgExpr->getSourceRange();
2921 return true;
2922 }
2923
2924 // -- The type of a template parameter corresponding to a
2925 // specialized non-type argument shall not be dependent on a
2926 // parameter of the specialization.
2927 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002928 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002929 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2930 << Param->getType()
2931 << ArgExpr->getSourceRange();
2932 Diag(Param->getLocation(), diag::note_template_param_here);
2933 return true;
2934 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002935
2936 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002937 }
2938
2939 return false;
2940}
2941
Douglas Gregorc08f4892009-03-25 00:13:59 +00002942Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002943Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2944 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002945 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002946 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002947 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002948 SourceLocation TemplateNameLoc,
2949 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002950 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002951 SourceLocation RAngleLoc,
2952 AttributeList *Attr,
2953 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00002954 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00002955
Douglas Gregor67a65642009-02-17 23:15:12 +00002956 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002957 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002958 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00002959 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
2960
2961 if (!ClassTemplate) {
2962 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
2963 << (Name.getAsTemplateDecl() &&
2964 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
2965 return true;
2966 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002967
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002968 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00002969 bool isPartialSpecialization = false;
2970
Douglas Gregorf47b9112009-02-25 22:02:03 +00002971 // Check the validity of the template headers that introduce this
2972 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00002973 // FIXME: We probably shouldn't complain about these headers for
2974 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002975 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002976 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2977 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002978 TemplateParameterLists.size(),
2979 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002980 if (TemplateParams && TemplateParams->size() > 0) {
2981 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002982
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002983 // C++ [temp.class.spec]p10:
2984 // The template parameter list of a specialization shall not
2985 // contain default template argument values.
2986 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2987 Decl *Param = TemplateParams->getParam(I);
2988 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2989 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002990 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002991 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00002992 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002993 }
2994 } else if (NonTypeTemplateParmDecl *NTTP
2995 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2996 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002997 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002998 diag::err_default_arg_in_partial_spec)
2999 << DefArg->getSourceRange();
3000 NTTP->setDefaultArgument(0);
3001 DefArg->Destroy(Context);
3002 }
3003 } else {
3004 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003005 if (TTP->hasDefaultArgument()) {
3006 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003007 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003008 << TTP->getDefaultArgument().getSourceRange();
3009 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003010 }
3011 }
3012 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003013 } else if (TemplateParams) {
3014 if (TUK == TUK_Friend)
3015 Diag(KWLoc, diag::err_template_spec_friend)
3016 << CodeModificationHint::CreateRemoval(
3017 SourceRange(TemplateParams->getTemplateLoc(),
3018 TemplateParams->getRAngleLoc()))
3019 << SourceRange(LAngleLoc, RAngleLoc);
3020 else
3021 isExplicitSpecialization = true;
3022 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003023 Diag(KWLoc, diag::err_template_spec_needs_header)
3024 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003025 isExplicitSpecialization = true;
3026 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003027
Douglas Gregor67a65642009-02-17 23:15:12 +00003028 // Check that the specialization uses the same tag kind as the
3029 // original template.
3030 TagDecl::TagKind Kind;
3031 switch (TagSpec) {
3032 default: assert(0 && "Unknown tag type!");
3033 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3034 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3035 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3036 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003037 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003038 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003039 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003040 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003041 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003042 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003043 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003044 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003045 diag::note_previous_use);
3046 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3047 }
3048
Douglas Gregorc40290e2009-03-09 23:48:35 +00003049 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00003050 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003051 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003052
Douglas Gregor67a65642009-02-17 23:15:12 +00003053 // Check that the template argument list is well-formed for this
3054 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003055 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3056 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003057 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003058 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003059 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003060 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003061
Mike Stump11289f42009-09-09 15:08:12 +00003062 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003063 ClassTemplate->getTemplateParameters()->size()) &&
3064 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003065
Douglas Gregor2373c592009-05-31 09:31:02 +00003066 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003067 // corresponds to these arguments.
3068 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003069 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003070 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003071 if (CheckClassTemplatePartialSpecializationArgs(
3072 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003073 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003074 return true;
3075
Douglas Gregor09a30232009-06-12 22:08:06 +00003076 if (MirrorsPrimaryTemplate) {
3077 // C++ [temp.class.spec]p9b3:
3078 //
Mike Stump11289f42009-09-09 15:08:12 +00003079 // -- The argument list of the specialization shall not be identical
3080 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003081 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003082 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003083 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003084 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003085 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003086 ClassTemplate->getIdentifier(),
3087 TemplateNameLoc,
3088 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003089 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003090 AS_none);
3091 }
3092
Douglas Gregor2208a292009-09-26 20:57:03 +00003093 // FIXME: Diagnose friend partial specializations
3094
Douglas Gregor2373c592009-05-31 09:31:02 +00003095 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00003096 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003097 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003098 Converted.flatSize(),
3099 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003100 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003101 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003102 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003103 Converted.flatSize(),
3104 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003105 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003106 ClassTemplateSpecializationDecl *PrevDecl = 0;
3107
3108 if (isPartialSpecialization)
3109 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003110 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003111 InsertPos);
3112 else
3113 PrevDecl
3114 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003115
3116 ClassTemplateSpecializationDecl *Specialization = 0;
3117
Douglas Gregorf47b9112009-02-25 22:02:03 +00003118 // Check whether we can declare a class template specialization in
3119 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003120 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003121 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003122 TemplateNameLoc,
3123 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003124 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003125
Douglas Gregor15301382009-07-30 17:40:51 +00003126 // The canonical type
3127 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003128 if (PrevDecl &&
3129 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3130 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003131 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003132 // arguments was referenced but not declared, or we're only
3133 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003134 // declaration node as our own, updating its source location to
3135 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003136 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003137 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003138 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003139 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003140 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003141 // Build the canonical type that describes the converted template
3142 // arguments of the class template partial specialization.
3143 CanonType = Context.getTemplateSpecializationType(
3144 TemplateName(ClassTemplate),
3145 Converted.getFlatArguments(),
3146 Converted.flatSize());
3147
Douglas Gregor2373c592009-05-31 09:31:02 +00003148 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003149 ClassTemplatePartialSpecializationDecl *PrevPartial
3150 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003151 ClassTemplatePartialSpecializationDecl *Partial
3152 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003153 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003154 TemplateNameLoc,
3155 TemplateParams,
3156 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003157 Converted,
John McCall0ad16662009-10-29 08:12:44 +00003158 TemplateArgs.data(),
3159 TemplateArgs.size(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003160 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003161
3162 if (PrevPartial) {
3163 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3164 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3165 } else {
3166 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3167 }
3168 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003169
Douglas Gregor21610382009-10-29 00:04:11 +00003170 // If we are providing an explicit specialization of a member class
3171 // template specialization, make a note of that.
3172 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3173 PrevPartial->setMemberSpecialization();
3174
Douglas Gregor91772d12009-06-13 00:26:55 +00003175 // Check that all of the template parameters of the class template
3176 // partial specialization are deducible from the template
3177 // arguments. If not, this class template partial specialization
3178 // will never be used.
3179 llvm::SmallVector<bool, 8> DeducibleParams;
3180 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003181 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003182 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003183 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003184 unsigned NumNonDeducible = 0;
3185 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3186 if (!DeducibleParams[I])
3187 ++NumNonDeducible;
3188
3189 if (NumNonDeducible) {
3190 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3191 << (NumNonDeducible > 1)
3192 << SourceRange(TemplateNameLoc, RAngleLoc);
3193 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3194 if (!DeducibleParams[I]) {
3195 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3196 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003197 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003198 diag::note_partial_spec_unused_parameter)
3199 << Param->getDeclName();
3200 else
Mike Stump11289f42009-09-09 15:08:12 +00003201 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003202 diag::note_partial_spec_unused_parameter)
3203 << std::string("<anonymous>");
3204 }
3205 }
3206 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003207 } else {
3208 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003209 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003210 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003211 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003212 ClassTemplate->getDeclContext(),
3213 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003214 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003215 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003216 PrevDecl);
3217
3218 if (PrevDecl) {
3219 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3220 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3221 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003222 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003223 InsertPos);
3224 }
Douglas Gregor15301382009-07-30 17:40:51 +00003225
3226 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003227 }
3228
Douglas Gregor06db9f52009-10-12 20:18:28 +00003229 // C++ [temp.expl.spec]p6:
3230 // If a template, a member template or the member of a class template is
3231 // explicitly specialized then that specialization shall be declared
3232 // before the first use of that specialization that would cause an implicit
3233 // instantiation to take place, in every translation unit in which such a
3234 // use occurs; no diagnostic is required.
3235 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3236 SourceRange Range(TemplateNameLoc, RAngleLoc);
3237 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3238 << Context.getTypeDeclType(Specialization) << Range;
3239
3240 Diag(PrevDecl->getPointOfInstantiation(),
3241 diag::note_instantiation_required_here)
3242 << (PrevDecl->getTemplateSpecializationKind()
3243 != TSK_ImplicitInstantiation);
3244 return true;
3245 }
3246
Douglas Gregor2208a292009-09-26 20:57:03 +00003247 // If this is not a friend, note that this is an explicit specialization.
3248 if (TUK != TUK_Friend)
3249 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003250
3251 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003252 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003253 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003254 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003255 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003256 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003257 Diag(Def->getLocation(), diag::note_previous_definition);
3258 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003259 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003260 }
3261 }
3262
Douglas Gregord56a91e2009-02-26 22:19:44 +00003263 // Build the fully-sugared type for this class template
3264 // specialization as the user wrote in the specialization
3265 // itself. This means that we'll pretty-print the type retrieved
3266 // from the specialization's declaration the way that the user
3267 // actually wrote the specialization, rather than formatting the
3268 // name based on the "canonical" representation used to store the
3269 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003270 QualType WrittenTy
3271 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003272 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00003273 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00003274 CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003275 if (TUK != TUK_Friend)
3276 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003277 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003278
Douglas Gregor1e249f82009-02-25 22:18:32 +00003279 // C++ [temp.expl.spec]p9:
3280 // A template explicit specialization is in the scope of the
3281 // namespace in which the template was defined.
3282 //
3283 // We actually implement this paragraph where we set the semantic
3284 // context (in the creation of the ClassTemplateSpecializationDecl),
3285 // but we also maintain the lexical context where the actual
3286 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003287 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003288
Douglas Gregor67a65642009-02-17 23:15:12 +00003289 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003290 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003291 Specialization->startDefinition();
3292
Douglas Gregor2208a292009-09-26 20:57:03 +00003293 if (TUK == TUK_Friend) {
3294 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3295 TemplateNameLoc,
3296 WrittenTy.getTypePtr(),
3297 /*FIXME:*/KWLoc);
3298 Friend->setAccess(AS_public);
3299 CurContext->addDecl(Friend);
3300 } else {
3301 // Add the specialization into its lexical context, so that it can
3302 // be seen when iterating through the list of declarations in that
3303 // context. However, specializations are not found by name lookup.
3304 CurContext->addDecl(Specialization);
3305 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003306 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003307}
Douglas Gregor333489b2009-03-27 23:10:48 +00003308
Mike Stump11289f42009-09-09 15:08:12 +00003309Sema::DeclPtrTy
3310Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003311 MultiTemplateParamsArg TemplateParameterLists,
3312 Declarator &D) {
3313 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3314}
3315
Mike Stump11289f42009-09-09 15:08:12 +00003316Sema::DeclPtrTy
3317Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003318 MultiTemplateParamsArg TemplateParameterLists,
3319 Declarator &D) {
3320 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3321 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3322 "Not a function declarator!");
3323 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003324
Douglas Gregor17a7c122009-06-24 00:54:41 +00003325 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003326 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003327 }
Mike Stump11289f42009-09-09 15:08:12 +00003328
Douglas Gregor17a7c122009-06-24 00:54:41 +00003329 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003330
3331 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003332 move(TemplateParameterLists),
3333 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003334 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003335 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003336 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003337 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003338 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3339 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003340 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003341}
3342
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003343/// \brief Diagnose cases where we have an explicit template specialization
3344/// before/after an explicit template instantiation, producing diagnostics
3345/// for those cases where they are required and determining whether the
3346/// new specialization/instantiation will have any effect.
3347///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003348/// \param NewLoc the location of the new explicit specialization or
3349/// instantiation.
3350///
3351/// \param NewTSK the kind of the new explicit specialization or instantiation.
3352///
3353/// \param PrevDecl the previous declaration of the entity.
3354///
3355/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3356///
3357/// \param PrevPointOfInstantiation if valid, indicates where the previus
3358/// declaration was instantiated (either implicitly or explicitly).
3359///
3360/// \param SuppressNew will be set to true to indicate that the new
3361/// specialization or instantiation has no effect and should be ignored.
3362///
3363/// \returns true if there was an error that should prevent the introduction of
3364/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003365bool
3366Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3367 TemplateSpecializationKind NewTSK,
3368 NamedDecl *PrevDecl,
3369 TemplateSpecializationKind PrevTSK,
3370 SourceLocation PrevPointOfInstantiation,
3371 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003372 SuppressNew = false;
3373
3374 switch (NewTSK) {
3375 case TSK_Undeclared:
3376 case TSK_ImplicitInstantiation:
3377 assert(false && "Don't check implicit instantiations here");
3378 return false;
3379
3380 case TSK_ExplicitSpecialization:
3381 switch (PrevTSK) {
3382 case TSK_Undeclared:
3383 case TSK_ExplicitSpecialization:
3384 // Okay, we're just specializing something that is either already
3385 // explicitly specialized or has merely been mentioned without any
3386 // instantiation.
3387 return false;
3388
3389 case TSK_ImplicitInstantiation:
3390 if (PrevPointOfInstantiation.isInvalid()) {
3391 // The declaration itself has not actually been instantiated, so it is
3392 // still okay to specialize it.
3393 return false;
3394 }
3395 // Fall through
3396
3397 case TSK_ExplicitInstantiationDeclaration:
3398 case TSK_ExplicitInstantiationDefinition:
3399 assert((PrevTSK == TSK_ImplicitInstantiation ||
3400 PrevPointOfInstantiation.isValid()) &&
3401 "Explicit instantiation without point of instantiation?");
3402
3403 // C++ [temp.expl.spec]p6:
3404 // If a template, a member template or the member of a class template
3405 // is explicitly specialized then that specialization shall be declared
3406 // before the first use of that specialization that would cause an
3407 // implicit instantiation to take place, in every translation unit in
3408 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003409 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003410 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003411 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003412 << (PrevTSK != TSK_ImplicitInstantiation);
3413
3414 return true;
3415 }
3416 break;
3417
3418 case TSK_ExplicitInstantiationDeclaration:
3419 switch (PrevTSK) {
3420 case TSK_ExplicitInstantiationDeclaration:
3421 // This explicit instantiation declaration is redundant (that's okay).
3422 SuppressNew = true;
3423 return false;
3424
3425 case TSK_Undeclared:
3426 case TSK_ImplicitInstantiation:
3427 // We're explicitly instantiating something that may have already been
3428 // implicitly instantiated; that's fine.
3429 return false;
3430
3431 case TSK_ExplicitSpecialization:
3432 // C++0x [temp.explicit]p4:
3433 // For a given set of template parameters, if an explicit instantiation
3434 // of a template appears after a declaration of an explicit
3435 // specialization for that template, the explicit instantiation has no
3436 // effect.
3437 return false;
3438
3439 case TSK_ExplicitInstantiationDefinition:
3440 // C++0x [temp.explicit]p10:
3441 // If an entity is the subject of both an explicit instantiation
3442 // declaration and an explicit instantiation definition in the same
3443 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003444 Diag(NewLoc,
3445 diag::err_explicit_instantiation_declaration_after_definition);
3446 Diag(PrevPointOfInstantiation,
3447 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003448 assert(PrevPointOfInstantiation.isValid() &&
3449 "Explicit instantiation without point of instantiation?");
3450 SuppressNew = true;
3451 return false;
3452 }
3453 break;
3454
3455 case TSK_ExplicitInstantiationDefinition:
3456 switch (PrevTSK) {
3457 case TSK_Undeclared:
3458 case TSK_ImplicitInstantiation:
3459 // We're explicitly instantiating something that may have already been
3460 // implicitly instantiated; that's fine.
3461 return false;
3462
3463 case TSK_ExplicitSpecialization:
3464 // C++ DR 259, C++0x [temp.explicit]p4:
3465 // For a given set of template parameters, if an explicit
3466 // instantiation of a template appears after a declaration of
3467 // an explicit specialization for that template, the explicit
3468 // instantiation has no effect.
3469 //
3470 // In C++98/03 mode, we only give an extension warning here, because it
3471 // is not not harmful to try to explicitly instantiate something that
3472 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003473 if (!getLangOptions().CPlusPlus0x) {
3474 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003475 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003476 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003477 diag::note_previous_template_specialization);
3478 }
3479 SuppressNew = true;
3480 return false;
3481
3482 case TSK_ExplicitInstantiationDeclaration:
3483 // We're explicity instantiating a definition for something for which we
3484 // were previously asked to suppress instantiations. That's fine.
3485 return false;
3486
3487 case TSK_ExplicitInstantiationDefinition:
3488 // C++0x [temp.spec]p5:
3489 // For a given template and a given set of template-arguments,
3490 // - an explicit instantiation definition shall appear at most once
3491 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003492 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003493 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003494 Diag(PrevPointOfInstantiation,
3495 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003496 SuppressNew = true;
3497 return false;
3498 }
3499 break;
3500 }
3501
3502 assert(false && "Missing specialization/instantiation case?");
3503
3504 return false;
3505}
3506
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003507/// \brief Perform semantic analysis for the given function template
3508/// specialization.
3509///
3510/// This routine performs all of the semantic analysis required for an
3511/// explicit function template specialization. On successful completion,
3512/// the function declaration \p FD will become a function template
3513/// specialization.
3514///
3515/// \param FD the function declaration, which will be updated to become a
3516/// function template specialization.
3517///
3518/// \param HasExplicitTemplateArgs whether any template arguments were
3519/// explicitly provided.
3520///
3521/// \param LAngleLoc the location of the left angle bracket ('<'), if
3522/// template arguments were explicitly provided.
3523///
3524/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3525/// if any.
3526///
3527/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3528/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3529/// true as in, e.g., \c void sort<>(char*, char*);
3530///
3531/// \param RAngleLoc the location of the right angle bracket ('>'), if
3532/// template arguments were explicitly provided.
3533///
3534/// \param PrevDecl the set of declarations that
3535bool
3536Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3537 bool HasExplicitTemplateArgs,
3538 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00003539 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003540 unsigned NumExplicitTemplateArgs,
3541 SourceLocation RAngleLoc,
John McCall1f82f242009-11-18 22:49:29 +00003542 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003543 // The set of function template specializations that could match this
3544 // explicit function template specialization.
3545 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3546 CandidateSet Candidates;
3547
3548 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00003549 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3550 I != E; ++I) {
3551 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3552 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003553 // Only consider templates found within the same semantic lookup scope as
3554 // FD.
3555 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3556 continue;
3557
3558 // C++ [temp.expl.spec]p11:
3559 // A trailing template-argument can be left unspecified in the
3560 // template-id naming an explicit function template specialization
3561 // provided it can be deduced from the function argument type.
3562 // Perform template argument deduction to determine whether we may be
3563 // specializing this template.
3564 // FIXME: It is somewhat wasteful to build
3565 TemplateDeductionInfo Info(Context);
3566 FunctionDecl *Specialization = 0;
3567 if (TemplateDeductionResult TDK
3568 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3569 ExplicitTemplateArgs,
3570 NumExplicitTemplateArgs,
3571 FD->getType(),
3572 Specialization,
3573 Info)) {
3574 // FIXME: Template argument deduction failed; record why it failed, so
3575 // that we can provide nifty diagnostics.
3576 (void)TDK;
3577 continue;
3578 }
3579
3580 // Record this candidate.
3581 Candidates.push_back(Specialization);
3582 }
3583 }
3584
Douglas Gregor5de279c2009-09-26 03:41:46 +00003585 // Find the most specialized function template.
3586 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3587 Candidates.size(),
3588 TPOC_Other,
3589 FD->getLocation(),
3590 PartialDiagnostic(diag::err_function_template_spec_no_match)
3591 << FD->getDeclName(),
3592 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3593 << FD->getDeclName() << HasExplicitTemplateArgs,
3594 PartialDiagnostic(diag::note_function_template_spec_matched));
3595 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003596 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003597
3598 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003599 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003600
Douglas Gregor54888652009-10-07 00:13:32 +00003601 // Check the scope of this explicit specialization.
3602 if (CheckTemplateSpecializationScope(*this,
3603 Specialization->getPrimaryTemplate(),
3604 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003605 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003606 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003607
3608 // C++ [temp.expl.spec]p6:
3609 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003610 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003611 // before the first use of that specialization that would cause an implicit
3612 // instantiation to take place, in every translation unit in which such a
3613 // use occurs; no diagnostic is required.
3614 FunctionTemplateSpecializationInfo *SpecInfo
3615 = Specialization->getTemplateSpecializationInfo();
3616 assert(SpecInfo && "Function template specialization info missing?");
3617 if (SpecInfo->getPointOfInstantiation().isValid()) {
3618 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3619 << FD;
3620 Diag(SpecInfo->getPointOfInstantiation(),
3621 diag::note_instantiation_required_here)
3622 << (Specialization->getTemplateSpecializationKind()
3623 != TSK_ImplicitInstantiation);
3624 return true;
3625 }
Douglas Gregor54888652009-10-07 00:13:32 +00003626
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003627 // Mark the prior declaration as an explicit specialization, so that later
3628 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003629 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003630
3631 // Turn the given function declaration into a function template
3632 // specialization, with the template arguments from the previous
3633 // specialization.
3634 FD->setFunctionTemplateSpecialization(Context,
3635 Specialization->getPrimaryTemplate(),
3636 new (Context) TemplateArgumentList(
3637 *Specialization->getTemplateSpecializationArgs()),
3638 /*InsertPos=*/0,
3639 TSK_ExplicitSpecialization);
3640
3641 // The "previous declaration" for this function template specialization is
3642 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00003643 Previous.clear();
3644 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003645 return false;
3646}
3647
Douglas Gregor86d142a2009-10-08 07:24:58 +00003648/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003649/// specialization.
3650///
3651/// This routine performs all of the semantic analysis required for an
3652/// explicit member function specialization. On successful completion,
3653/// the function declaration \p FD will become a member function
3654/// specialization.
3655///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003656/// \param Member the member declaration, which will be updated to become a
3657/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003658///
John McCall1f82f242009-11-18 22:49:29 +00003659/// \param Previous the set of declarations, one of which may be specialized
3660/// by this function specialization; the set will be modified to contain the
3661/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003662bool
John McCall1f82f242009-11-18 22:49:29 +00003663Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003664 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3665
3666 // Try to find the member we are instantiating.
3667 NamedDecl *Instantiation = 0;
3668 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003669 MemberSpecializationInfo *MSInfo = 0;
3670
John McCall1f82f242009-11-18 22:49:29 +00003671 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003672 // Nowhere to look anyway.
3673 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003674 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3675 I != E; ++I) {
3676 NamedDecl *D = (*I)->getUnderlyingDecl();
3677 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003678 if (Context.hasSameType(Function->getType(), Method->getType())) {
3679 Instantiation = Method;
3680 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003681 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003682 break;
3683 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003684 }
3685 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003686 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003687 VarDecl *PrevVar;
3688 if (Previous.isSingleResult() &&
3689 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00003690 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00003691 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003692 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003693 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003694 }
3695 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003696 CXXRecordDecl *PrevRecord;
3697 if (Previous.isSingleResult() &&
3698 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3699 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003700 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003701 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003702 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003703 }
3704
3705 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003706 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003707 // specializations are always out-of-line, the caller will complain about
3708 // this mismatch later.
3709 return false;
3710 }
3711
Douglas Gregor86d142a2009-10-08 07:24:58 +00003712 // Make sure that this is a specialization of a member.
3713 if (!InstantiatedFrom) {
3714 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3715 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003716 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3717 return true;
3718 }
3719
Douglas Gregor06db9f52009-10-12 20:18:28 +00003720 // C++ [temp.expl.spec]p6:
3721 // If a template, a member template or the member of a class template is
3722 // explicitly specialized then that spe- cialization shall be declared
3723 // before the first use of that specialization that would cause an implicit
3724 // instantiation to take place, in every translation unit in which such a
3725 // use occurs; no diagnostic is required.
3726 assert(MSInfo && "Member specialization info missing?");
3727 if (MSInfo->getPointOfInstantiation().isValid()) {
3728 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3729 << Member;
3730 Diag(MSInfo->getPointOfInstantiation(),
3731 diag::note_instantiation_required_here)
3732 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3733 return true;
3734 }
3735
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003736 // Check the scope of this explicit specialization.
3737 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003738 InstantiatedFrom,
3739 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003740 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003741 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003742
Douglas Gregor86d142a2009-10-08 07:24:58 +00003743 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003744 // the original declaration to note that it is an explicit specialization
3745 // (if it was previously an implicit instantiation). This latter step
3746 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003747 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003748 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3749 if (InstantiationFunction->getTemplateSpecializationKind() ==
3750 TSK_ImplicitInstantiation) {
3751 InstantiationFunction->setTemplateSpecializationKind(
3752 TSK_ExplicitSpecialization);
3753 InstantiationFunction->setLocation(Member->getLocation());
3754 }
3755
Douglas Gregor86d142a2009-10-08 07:24:58 +00003756 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3757 cast<CXXMethodDecl>(InstantiatedFrom),
3758 TSK_ExplicitSpecialization);
3759 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003760 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3761 if (InstantiationVar->getTemplateSpecializationKind() ==
3762 TSK_ImplicitInstantiation) {
3763 InstantiationVar->setTemplateSpecializationKind(
3764 TSK_ExplicitSpecialization);
3765 InstantiationVar->setLocation(Member->getLocation());
3766 }
3767
Douglas Gregor86d142a2009-10-08 07:24:58 +00003768 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3769 cast<VarDecl>(InstantiatedFrom),
3770 TSK_ExplicitSpecialization);
3771 } else {
3772 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003773 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3774 if (InstantiationClass->getTemplateSpecializationKind() ==
3775 TSK_ImplicitInstantiation) {
3776 InstantiationClass->setTemplateSpecializationKind(
3777 TSK_ExplicitSpecialization);
3778 InstantiationClass->setLocation(Member->getLocation());
3779 }
3780
Douglas Gregor86d142a2009-10-08 07:24:58 +00003781 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003782 cast<CXXRecordDecl>(InstantiatedFrom),
3783 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003784 }
3785
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003786 // Save the caller the trouble of having to figure out which declaration
3787 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00003788 Previous.clear();
3789 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003790 return false;
3791}
3792
Douglas Gregore47f5a72009-10-14 23:41:34 +00003793/// \brief Check the scope of an explicit instantiation.
3794static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3795 SourceLocation InstLoc,
3796 bool WasQualifiedName) {
3797 DeclContext *ExpectedContext
3798 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3799 DeclContext *CurContext = S.CurContext->getLookupContext();
3800
3801 // C++0x [temp.explicit]p2:
3802 // An explicit instantiation shall appear in an enclosing namespace of its
3803 // template.
3804 //
3805 // This is DR275, which we do not retroactively apply to C++98/03.
3806 if (S.getLangOptions().CPlusPlus0x &&
3807 !CurContext->Encloses(ExpectedContext)) {
3808 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3809 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3810 << D << NS;
3811 else
3812 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3813 << D;
3814 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3815 return;
3816 }
3817
3818 // C++0x [temp.explicit]p2:
3819 // If the name declared in the explicit instantiation is an unqualified
3820 // name, the explicit instantiation shall appear in the namespace where
3821 // its template is declared or, if that namespace is inline (7.3.1), any
3822 // namespace from its enclosing namespace set.
3823 if (WasQualifiedName)
3824 return;
3825
3826 if (CurContext->Equals(ExpectedContext))
3827 return;
3828
3829 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3830 << D << ExpectedContext;
3831 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3832}
3833
3834/// \brief Determine whether the given scope specifier has a template-id in it.
3835static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3836 if (!SS.isSet())
3837 return false;
3838
3839 // C++0x [temp.explicit]p2:
3840 // If the explicit instantiation is for a member function, a member class
3841 // or a static data member of a class template specialization, the name of
3842 // the class template specialization in the qualified-id for the member
3843 // name shall be a simple-template-id.
3844 //
3845 // C++98 has the same restriction, just worded differently.
3846 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3847 NNS; NNS = NNS->getPrefix())
3848 if (Type *T = NNS->getAsType())
3849 if (isa<TemplateSpecializationType>(T))
3850 return true;
3851
3852 return false;
3853}
3854
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003855// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003856// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003857Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003858Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003859 SourceLocation ExternLoc,
3860 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003861 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003862 SourceLocation KWLoc,
3863 const CXXScopeSpec &SS,
3864 TemplateTy TemplateD,
3865 SourceLocation TemplateNameLoc,
3866 SourceLocation LAngleLoc,
3867 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00003868 SourceLocation RAngleLoc,
3869 AttributeList *Attr) {
3870 // Find the class template we're specializing
3871 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003872 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003873 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3874
3875 // Check that the specialization uses the same tag kind as the
3876 // original template.
3877 TagDecl::TagKind Kind;
3878 switch (TagSpec) {
3879 default: assert(0 && "Unknown tag type!");
3880 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3881 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3882 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3883 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003884 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003885 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003886 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003887 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003888 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003889 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003890 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003891 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003892 diag::note_previous_use);
3893 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3894 }
3895
Douglas Gregore47f5a72009-10-14 23:41:34 +00003896 // C++0x [temp.explicit]p2:
3897 // There are two forms of explicit instantiation: an explicit instantiation
3898 // definition and an explicit instantiation declaration. An explicit
3899 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00003900 TemplateSpecializationKind TSK
3901 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3902 : TSK_ExplicitInstantiationDeclaration;
3903
Douglas Gregora1f49972009-05-13 00:25:59 +00003904 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00003905 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003906 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00003907
3908 // Check that the template argument list is well-formed for this
3909 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003910 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3911 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003912 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003913 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003914 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003915 return true;
3916
Mike Stump11289f42009-09-09 15:08:12 +00003917 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003918 ClassTemplate->getTemplateParameters()->size()) &&
3919 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003920
Douglas Gregora1f49972009-05-13 00:25:59 +00003921 // Find the class template specialization declaration that
3922 // corresponds to these arguments.
3923 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003924 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003925 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003926 Converted.flatSize(),
3927 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003928 void *InsertPos = 0;
3929 ClassTemplateSpecializationDecl *PrevDecl
3930 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3931
Douglas Gregor54888652009-10-07 00:13:32 +00003932 // C++0x [temp.explicit]p2:
3933 // [...] An explicit instantiation shall appear in an enclosing
3934 // namespace of its template. [...]
3935 //
3936 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00003937 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
3938 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00003939
Douglas Gregora1f49972009-05-13 00:25:59 +00003940 ClassTemplateSpecializationDecl *Specialization = 0;
3941
3942 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00003943 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003944 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00003945 PrevDecl,
3946 PrevDecl->getSpecializationKind(),
3947 PrevDecl->getPointOfInstantiation(),
3948 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00003949 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003950
Douglas Gregor12e49d32009-10-15 22:53:21 +00003951 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003952 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00003953
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003954 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3955 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3956 // Since the only prior class template specialization with these
3957 // arguments was referenced but not declared, reuse that
3958 // declaration node as our own, updating its source location to
3959 // reflect our new declaration.
3960 Specialization = PrevDecl;
3961 Specialization->setLocation(TemplateNameLoc);
3962 PrevDecl = 0;
3963 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00003964 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003965
3966 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003967 // Create a new class template specialization declaration node for
3968 // this explicit specialization.
3969 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003970 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003971 ClassTemplate->getDeclContext(),
3972 TemplateNameLoc,
3973 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003974 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003975
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003976 if (PrevDecl) {
3977 // Remove the previous declaration from the folding set, since we want
3978 // to introduce a new declaration.
3979 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3980 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3981 }
3982
3983 // Insert the new specialization.
3984 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003985 }
3986
3987 // Build the fully-sugared type for this explicit instantiation as
3988 // the user wrote in the explicit instantiation itself. This means
3989 // that we'll pretty-print the type retrieved from the
3990 // specialization's declaration the way that the user actually wrote
3991 // the explicit instantiation, rather than formatting the name based
3992 // on the "canonical" representation used to store the template
3993 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003994 QualType WrittenTy
3995 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003996 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003997 TemplateArgs.size(),
3998 Context.getTypeDeclType(Specialization));
3999 Specialization->setTypeAsWritten(WrittenTy);
4000 TemplateArgsIn.release();
4001
4002 // Add the explicit instantiation into its lexical context. However,
4003 // since explicit instantiations are never found by name lookup, we
4004 // just put it into the declaration context directly.
4005 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004006 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00004007
4008 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004009 // A definition of a class template or class member template
4010 // shall be in scope at the point of the explicit instantiation of
4011 // the class template or class member template.
4012 //
4013 // This check comes when we actually try to perform the
4014 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004015 ClassTemplateSpecializationDecl *Def
4016 = cast_or_null<ClassTemplateSpecializationDecl>(
4017 Specialization->getDefinition(Context));
4018 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004019 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004020
4021 // Instantiate the members of this class template specialization.
4022 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4023 Specialization->getDefinition(Context));
4024 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00004025 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004026
4027 return DeclPtrTy::make(Specialization);
4028}
4029
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004030// Explicit instantiation of a member class of a class template.
4031Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004032Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004033 SourceLocation ExternLoc,
4034 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004035 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004036 SourceLocation KWLoc,
4037 const CXXScopeSpec &SS,
4038 IdentifierInfo *Name,
4039 SourceLocation NameLoc,
4040 AttributeList *Attr) {
4041
Douglas Gregord6ab8742009-05-28 23:31:59 +00004042 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004043 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004044 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004045 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004046 MultiTemplateParamsArg(*this, 0, 0),
4047 Owned, IsDependent);
4048 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4049
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004050 if (!TagD)
4051 return true;
4052
4053 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4054 if (Tag->isEnum()) {
4055 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4056 << Context.getTypeDeclType(Tag);
4057 return true;
4058 }
4059
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004060 if (Tag->isInvalidDecl())
4061 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004062
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004063 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4064 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4065 if (!Pattern) {
4066 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4067 << Context.getTypeDeclType(Record);
4068 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4069 return true;
4070 }
4071
Douglas Gregore47f5a72009-10-14 23:41:34 +00004072 // C++0x [temp.explicit]p2:
4073 // If the explicit instantiation is for a class or member class, the
4074 // elaborated-type-specifier in the declaration shall include a
4075 // simple-template-id.
4076 //
4077 // C++98 has the same restriction, just worded differently.
4078 if (!ScopeSpecifierHasTemplateId(SS))
4079 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4080 << Record << SS.getRange();
4081
4082 // C++0x [temp.explicit]p2:
4083 // There are two forms of explicit instantiation: an explicit instantiation
4084 // definition and an explicit instantiation declaration. An explicit
4085 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004086 TemplateSpecializationKind TSK
4087 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4088 : TSK_ExplicitInstantiationDeclaration;
4089
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004090 // C++0x [temp.explicit]p2:
4091 // [...] An explicit instantiation shall appear in an enclosing
4092 // namespace of its template. [...]
4093 //
4094 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004095 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004096
4097 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004098 CXXRecordDecl *PrevDecl
4099 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4100 if (!PrevDecl && Record->getDefinition(Context))
4101 PrevDecl = Record;
4102 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004103 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4104 bool SuppressNew = false;
4105 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004106 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004107 PrevDecl,
4108 MSInfo->getTemplateSpecializationKind(),
4109 MSInfo->getPointOfInstantiation(),
4110 SuppressNew))
4111 return true;
4112 if (SuppressNew)
4113 return TagD;
4114 }
4115
Douglas Gregor12e49d32009-10-15 22:53:21 +00004116 CXXRecordDecl *RecordDef
4117 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4118 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004119 // C++ [temp.explicit]p3:
4120 // A definition of a member class of a class template shall be in scope
4121 // at the point of an explicit instantiation of the member class.
4122 CXXRecordDecl *Def
4123 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4124 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004125 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4126 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004127 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4128 << Pattern;
4129 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004130 } else {
4131 if (InstantiateClass(NameLoc, Record, Def,
4132 getTemplateInstantiationArgs(Record),
4133 TSK))
4134 return true;
4135
4136 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4137 if (!RecordDef)
4138 return true;
4139 }
4140 }
4141
4142 // Instantiate all of the members of the class.
4143 InstantiateClassMembers(NameLoc, RecordDef,
4144 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004145
Mike Stump87c57ac2009-05-16 07:39:55 +00004146 // FIXME: We don't have any representation for explicit instantiations of
4147 // member classes. Such a representation is not needed for compilation, but it
4148 // should be available for clients that want to see all of the declarations in
4149 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004150 return TagD;
4151}
4152
Douglas Gregor450f00842009-09-25 18:43:00 +00004153Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4154 SourceLocation ExternLoc,
4155 SourceLocation TemplateLoc,
4156 Declarator &D) {
4157 // Explicit instantiations always require a name.
4158 DeclarationName Name = GetNameForDeclarator(D);
4159 if (!Name) {
4160 if (!D.isInvalidType())
4161 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4162 diag::err_explicit_instantiation_requires_name)
4163 << D.getDeclSpec().getSourceRange()
4164 << D.getSourceRange();
4165
4166 return true;
4167 }
4168
4169 // The scope passed in may not be a decl scope. Zip up the scope tree until
4170 // we find one that is.
4171 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4172 (S->getFlags() & Scope::TemplateParamScope) != 0)
4173 S = S->getParent();
4174
4175 // Determine the type of the declaration.
4176 QualType R = GetTypeForDeclarator(D, S, 0);
4177 if (R.isNull())
4178 return true;
4179
4180 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4181 // Cannot explicitly instantiate a typedef.
4182 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4183 << Name;
4184 return true;
4185 }
4186
Douglas Gregor3c74d412009-10-14 20:14:33 +00004187 // C++0x [temp.explicit]p1:
4188 // [...] An explicit instantiation of a function template shall not use the
4189 // inline or constexpr specifiers.
4190 // Presumably, this also applies to member functions of class templates as
4191 // well.
4192 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4193 Diag(D.getDeclSpec().getInlineSpecLoc(),
4194 diag::err_explicit_instantiation_inline)
4195 << CodeModificationHint::CreateRemoval(
4196 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
4197
4198 // FIXME: check for constexpr specifier.
4199
Douglas Gregore47f5a72009-10-14 23:41:34 +00004200 // C++0x [temp.explicit]p2:
4201 // There are two forms of explicit instantiation: an explicit instantiation
4202 // definition and an explicit instantiation declaration. An explicit
4203 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004204 TemplateSpecializationKind TSK
4205 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4206 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004207
John McCall27b18f82009-11-17 02:14:36 +00004208 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4209 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004210
4211 if (!R->isFunctionType()) {
4212 // C++ [temp.explicit]p1:
4213 // A [...] static data member of a class template can be explicitly
4214 // instantiated from the member definition associated with its class
4215 // template.
John McCall27b18f82009-11-17 02:14:36 +00004216 if (Previous.isAmbiguous())
4217 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004218
John McCall9f3059a2009-10-09 21:13:30 +00004219 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4220 Previous.getAsSingleDecl(Context));
Douglas Gregor450f00842009-09-25 18:43:00 +00004221 if (!Prev || !Prev->isStaticDataMember()) {
4222 // We expect to see a data data member here.
4223 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4224 << Name;
4225 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4226 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004227 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004228 return true;
4229 }
4230
4231 if (!Prev->getInstantiatedFromStaticDataMember()) {
4232 // FIXME: Check for explicit specialization?
4233 Diag(D.getIdentifierLoc(),
4234 diag::err_explicit_instantiation_data_member_not_instantiated)
4235 << Prev;
4236 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4237 // FIXME: Can we provide a note showing where this was declared?
4238 return true;
4239 }
4240
Douglas Gregore47f5a72009-10-14 23:41:34 +00004241 // C++0x [temp.explicit]p2:
4242 // If the explicit instantiation is for a member function, a member class
4243 // or a static data member of a class template specialization, the name of
4244 // the class template specialization in the qualified-id for the member
4245 // name shall be a simple-template-id.
4246 //
4247 // C++98 has the same restriction, just worded differently.
4248 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4249 Diag(D.getIdentifierLoc(),
4250 diag::err_explicit_instantiation_without_qualified_id)
4251 << Prev << D.getCXXScopeSpec().getRange();
4252
4253 // Check the scope of this explicit instantiation.
4254 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4255
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004256 // Verify that it is okay to explicitly instantiate here.
4257 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4258 assert(MSInfo && "Missing static data member specialization info?");
4259 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004260 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004261 MSInfo->getTemplateSpecializationKind(),
4262 MSInfo->getPointOfInstantiation(),
4263 SuppressNew))
4264 return true;
4265 if (SuppressNew)
4266 return DeclPtrTy();
4267
Douglas Gregor450f00842009-09-25 18:43:00 +00004268 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004269 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004270 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004271 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4272 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004273
4274 // FIXME: Create an ExplicitInstantiation node?
4275 return DeclPtrTy();
4276 }
4277
Douglas Gregor0e876e02009-09-25 23:53:26 +00004278 // If the declarator is a template-id, translate the parser's template
4279 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004280 bool HasExplicitTemplateArgs = false;
John McCall0ad16662009-10-29 08:12:44 +00004281 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004282 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4283 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Douglas Gregord90fd522009-09-25 21:45:23 +00004284 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4285 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004286 TemplateId->NumArgs);
4287 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregord90fd522009-09-25 21:45:23 +00004288 TemplateArgs);
4289 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004290 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004291 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004292
Douglas Gregor450f00842009-09-25 18:43:00 +00004293 // C++ [temp.explicit]p1:
4294 // A [...] function [...] can be explicitly instantiated from its template.
4295 // A member function [...] of a class template can be explicitly
4296 // instantiated from the member definition associated with its class
4297 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004298 llvm::SmallVector<FunctionDecl *, 8> Matches;
4299 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4300 P != PEnd; ++P) {
4301 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004302 if (!HasExplicitTemplateArgs) {
4303 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4304 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4305 Matches.clear();
4306 Matches.push_back(Method);
4307 break;
4308 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004309 }
4310 }
4311
4312 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4313 if (!FunTmpl)
4314 continue;
4315
4316 TemplateDeductionInfo Info(Context);
4317 FunctionDecl *Specialization = 0;
4318 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00004319 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
4320 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00004321 R, Specialization, Info)) {
4322 // FIXME: Keep track of almost-matches?
4323 (void)TDK;
4324 continue;
4325 }
4326
4327 Matches.push_back(Specialization);
4328 }
4329
4330 // Find the most specialized function template specialization.
4331 FunctionDecl *Specialization
4332 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4333 D.getIdentifierLoc(),
4334 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4335 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4336 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4337
4338 if (!Specialization)
4339 return true;
4340
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004341 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004342 Diag(D.getIdentifierLoc(),
4343 diag::err_explicit_instantiation_member_function_not_instantiated)
4344 << Specialization
4345 << (Specialization->getTemplateSpecializationKind() ==
4346 TSK_ExplicitSpecialization);
4347 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4348 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004349 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004350
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004351 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004352 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4353 PrevDecl = Specialization;
4354
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004355 if (PrevDecl) {
4356 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004357 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004358 PrevDecl,
4359 PrevDecl->getTemplateSpecializationKind(),
4360 PrevDecl->getPointOfInstantiation(),
4361 SuppressNew))
4362 return true;
4363
4364 // FIXME: We may still want to build some representation of this
4365 // explicit specialization.
4366 if (SuppressNew)
4367 return DeclPtrTy();
4368 }
4369
4370 if (TSK == TSK_ExplicitInstantiationDefinition)
4371 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4372 false, /*DefinitionRequired=*/true);
4373
4374 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4375
Douglas Gregore47f5a72009-10-14 23:41:34 +00004376 // C++0x [temp.explicit]p2:
4377 // If the explicit instantiation is for a member function, a member class
4378 // or a static data member of a class template specialization, the name of
4379 // the class template specialization in the qualified-id for the member
4380 // name shall be a simple-template-id.
4381 //
4382 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004383 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004384 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004385 D.getCXXScopeSpec().isSet() &&
4386 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4387 Diag(D.getIdentifierLoc(),
4388 diag::err_explicit_instantiation_without_qualified_id)
4389 << Specialization << D.getCXXScopeSpec().getRange();
4390
4391 CheckExplicitInstantiationScope(*this,
4392 FunTmpl? (NamedDecl *)FunTmpl
4393 : Specialization->getInstantiatedFromMemberFunction(),
4394 D.getIdentifierLoc(),
4395 D.getCXXScopeSpec().isSet());
4396
Douglas Gregor450f00842009-09-25 18:43:00 +00004397 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4398 return DeclPtrTy();
4399}
4400
Douglas Gregor333489b2009-03-27 23:10:48 +00004401Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004402Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4403 const CXXScopeSpec &SS, IdentifierInfo *Name,
4404 SourceLocation TagLoc, SourceLocation NameLoc) {
4405 // This has to hold, because SS is expected to be defined.
4406 assert(Name && "Expected a name in a dependent tag");
4407
4408 NestedNameSpecifier *NNS
4409 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4410 if (!NNS)
4411 return true;
4412
4413 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4414 if (T.isNull())
4415 return true;
4416
4417 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4418 QualType ElabType = Context.getElaboratedType(T, TagKind);
4419
4420 return ElabType.getAsOpaquePtr();
4421}
4422
4423Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004424Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4425 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004426 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004427 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4428 if (!NNS)
4429 return true;
4430
4431 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004432 if (T.isNull())
4433 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004434 return T.getAsOpaquePtr();
4435}
4436
Douglas Gregordce2b622009-04-01 00:28:59 +00004437Sema::TypeResult
4438Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4439 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004440 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004441 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004442 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004443 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004444 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004445 assert(TemplateId && "Expected a template specialization type");
4446
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004447 if (computeDeclContext(SS, false)) {
4448 // If we can compute a declaration context, then the "typename"
4449 // keyword was superfluous. Just build a QualifiedNameType to keep
4450 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004451
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004452 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4453 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4454 }
Mike Stump11289f42009-09-09 15:08:12 +00004455
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004456 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004457}
4458
Douglas Gregor333489b2009-03-27 23:10:48 +00004459/// \brief Build the type that describes a C++ typename specifier,
4460/// e.g., "typename T::type".
4461QualType
4462Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4463 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004464 CXXRecordDecl *CurrentInstantiation = 0;
4465 if (NNS->isDependent()) {
4466 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004467
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004468 // If the nested-name-specifier does not refer to the current
4469 // instantiation, then build a typename type.
4470 if (!CurrentInstantiation)
4471 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004472
Douglas Gregorc707da62009-09-02 13:12:51 +00004473 // The nested-name-specifier refers to the current instantiation, so the
4474 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004475 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004476 // extraneous "typename" keywords, and we retroactively apply this DR to
4477 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004478 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004479
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004480 DeclContext *Ctx = 0;
4481
4482 if (CurrentInstantiation)
4483 Ctx = CurrentInstantiation;
4484 else {
4485 CXXScopeSpec SS;
4486 SS.setScopeRep(NNS);
4487 SS.setRange(Range);
4488 if (RequireCompleteDeclContext(SS))
4489 return QualType();
4490
4491 Ctx = computeDeclContext(SS);
4492 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004493 assert(Ctx && "No declaration context?");
4494
4495 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00004496 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4497 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00004498 unsigned DiagID = 0;
4499 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00004500 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004501 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004502 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004503 break;
4504
4505 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004506 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004507 // We found a type. Build a QualifiedNameType, since the
4508 // typename-specifier was just sugar. FIXME: Tell
4509 // QualifiedNameType that it has a "typename" prefix.
4510 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4511 }
4512
4513 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004514 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004515 break;
4516
John McCalle61f2ba2009-11-18 02:36:19 +00004517 case LookupResult::FoundUnresolvedValue:
4518 llvm::llvm_unreachable("unresolved using decl in non-dependent context");
4519 return QualType();
4520
Douglas Gregor333489b2009-03-27 23:10:48 +00004521 case LookupResult::FoundOverloaded:
4522 DiagID = diag::err_typename_nested_not_type;
4523 Referenced = *Result.begin();
4524 break;
4525
John McCall6538c932009-10-10 05:48:19 +00004526 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004527 return QualType();
4528 }
4529
4530 // If we get here, it's because name lookup did not find a
4531 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004532 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004533 if (Referenced)
4534 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4535 << Name;
4536 return QualType();
4537}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004538
4539namespace {
4540 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00004541 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4542 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004543 SourceLocation Loc;
4544 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004545
Douglas Gregor15acfb92009-08-06 16:20:37 +00004546 public:
Mike Stump11289f42009-09-09 15:08:12 +00004547 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004548 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004549 DeclarationName Entity)
4550 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004551 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004552
4553 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004554 /// transformed.
4555 ///
4556 /// For the purposes of type reconstruction, a type has already been
4557 /// transformed if it is NULL or if it is not dependent.
4558 bool AlreadyTransformed(QualType T) {
4559 return T.isNull() || !T->isDependentType();
4560 }
Mike Stump11289f42009-09-09 15:08:12 +00004561
4562 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004563 /// rebuilt.
4564 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004565
Douglas Gregor15acfb92009-08-06 16:20:37 +00004566 /// \brief Returns the name of the entity whose type is being rebuilt.
4567 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004568
Douglas Gregoref6ab412009-10-27 06:26:26 +00004569 /// \brief Sets the "base" location and entity when that
4570 /// information is known based on another transformation.
4571 void setBase(SourceLocation Loc, DeclarationName Entity) {
4572 this->Loc = Loc;
4573 this->Entity = Entity;
4574 }
4575
Douglas Gregor15acfb92009-08-06 16:20:37 +00004576 /// \brief Transforms an expression by returning the expression itself
4577 /// (an identity function).
4578 ///
4579 /// FIXME: This is completely unsafe; we will need to actually clone the
4580 /// expressions.
4581 Sema::OwningExprResult TransformExpr(Expr *E) {
4582 return getSema().Owned(E);
4583 }
Mike Stump11289f42009-09-09 15:08:12 +00004584
Douglas Gregor15acfb92009-08-06 16:20:37 +00004585 /// \brief Transforms a typename type by determining whether the type now
4586 /// refers to a member of the current instantiation, and then
4587 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004588 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004589 };
4590}
4591
Mike Stump11289f42009-09-09 15:08:12 +00004592QualType
John McCall550e0c22009-10-21 00:40:46 +00004593CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4594 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004595 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004596
Douglas Gregor15acfb92009-08-06 16:20:37 +00004597 NestedNameSpecifier *NNS
4598 = TransformNestedNameSpecifier(T->getQualifier(),
4599 /*FIXME:*/SourceRange(getBaseLocation()));
4600 if (!NNS)
4601 return QualType();
4602
4603 // If the nested-name-specifier did not change, and we cannot compute the
4604 // context corresponding to the nested-name-specifier, then this
4605 // typename type will not change; exit early.
4606 CXXScopeSpec SS;
4607 SS.setRange(SourceRange(getBaseLocation()));
4608 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004609
4610 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004611 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004612 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004613
4614 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004615 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004616 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004617 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004618 = TransformType(QualType(TemplateId, 0));
4619 if (NewTemplateId.isNull())
4620 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004621
Douglas Gregor15acfb92009-08-06 16:20:37 +00004622 if (NNS == T->getQualifier() &&
4623 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004624 Result = QualType(T, 0);
4625 else
4626 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4627 } else
4628 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4629 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004630
John McCall0ad16662009-10-29 08:12:44 +00004631 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4632 NewTL.setNameLoc(TL.getNameLoc());
4633 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004634}
4635
4636/// \brief Rebuilds a type within the context of the current instantiation.
4637///
Mike Stump11289f42009-09-09 15:08:12 +00004638/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004639/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004640/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004641/// partial specialization thereof). This routine will rebuild that type now
4642/// that we have entered the declarator's scope, which may produce different
4643/// canonical types, e.g.,
4644///
4645/// \code
4646/// template<typename T>
4647/// struct X {
4648/// typedef T* pointer;
4649/// pointer data();
4650/// };
4651///
4652/// template<typename T>
4653/// typename X<T>::pointer X<T>::data() { ... }
4654/// \endcode
4655///
4656/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4657/// since we do not know that we can look into X<T> when we parsed the type.
4658/// This function will rebuild the type, performing the lookup of "pointer"
4659/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4660/// as the canonical type of T*, allowing the return types of the out-of-line
4661/// definition and the declaration to match.
4662QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4663 DeclarationName Name) {
4664 if (T.isNull() || !T->isDependentType())
4665 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004666
Douglas Gregor15acfb92009-08-06 16:20:37 +00004667 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4668 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004669}
Douglas Gregorbe999392009-09-15 16:23:51 +00004670
4671/// \brief Produces a formatted string that describes the binding of
4672/// template parameters to template arguments.
4673std::string
4674Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4675 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004676 // FIXME: For variadic templates, we'll need to get the structured list.
4677 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4678 Args.flat_size());
4679}
4680
4681std::string
4682Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4683 const TemplateArgument *Args,
4684 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004685 std::string Result;
4686
Douglas Gregore62e6a02009-11-11 19:13:48 +00004687 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00004688 return Result;
4689
4690 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004691 if (I >= NumArgs)
4692 break;
4693
Douglas Gregorbe999392009-09-15 16:23:51 +00004694 if (I == 0)
4695 Result += "[with ";
4696 else
4697 Result += ", ";
4698
4699 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4700 Result += Id->getName();
4701 } else {
4702 Result += '$';
4703 Result += llvm::utostr(I);
4704 }
4705
4706 Result += " = ";
4707
4708 switch (Args[I].getKind()) {
4709 case TemplateArgument::Null:
4710 Result += "<no value>";
4711 break;
4712
4713 case TemplateArgument::Type: {
4714 std::string TypeStr;
4715 Args[I].getAsType().getAsStringInternal(TypeStr,
4716 Context.PrintingPolicy);
4717 Result += TypeStr;
4718 break;
4719 }
4720
4721 case TemplateArgument::Declaration: {
4722 bool Unnamed = true;
4723 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4724 if (ND->getDeclName()) {
4725 Unnamed = false;
4726 Result += ND->getNameAsString();
4727 }
4728 }
4729
4730 if (Unnamed) {
4731 Result += "<anonymous>";
4732 }
4733 break;
4734 }
4735
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004736 case TemplateArgument::Template: {
4737 std::string Str;
4738 llvm::raw_string_ostream OS(Str);
4739 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4740 Result += OS.str();
4741 break;
4742 }
4743
Douglas Gregorbe999392009-09-15 16:23:51 +00004744 case TemplateArgument::Integral: {
4745 Result += Args[I].getAsIntegral()->toString(10);
4746 break;
4747 }
4748
4749 case TemplateArgument::Expression: {
4750 assert(false && "No expressions in deduced template arguments!");
4751 Result += "<expression>";
4752 break;
4753 }
4754
4755 case TemplateArgument::Pack:
4756 // FIXME: Format template argument packs
4757 Result += "<template argument pack>";
4758 break;
4759 }
4760 }
4761
4762 Result += ']';
4763 return Result;
4764}