blob: ce2ffc1ac1850c4e75759b5d9e9d758ba79d43fe [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"
Douglas Gregor15acfb92009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000019#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000020#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000021#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000022#include "llvm/Support/Compiler.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000023#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000024using namespace clang;
25
Douglas Gregorb7bfe792009-09-02 22:59:36 +000026/// \brief Determine whether the declaration found is acceptable as the name
27/// of a template and, if so, return that template declaration. Otherwise,
28/// returns NULL.
29static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
30 if (!D)
31 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000032
Douglas Gregorb7bfe792009-09-02 22:59:36 +000033 if (isa<TemplateDecl>(D))
34 return D;
Mike Stump11289f42009-09-09 15:08:12 +000035
Douglas Gregorb7bfe792009-09-02 22:59:36 +000036 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
37 // C++ [temp.local]p1:
38 // Like normal (non-template) classes, class templates have an
39 // injected-class-name (Clause 9). The injected-class-name
40 // can be used with or without a template-argument-list. When
41 // it is used without a template-argument-list, it is
42 // equivalent to the injected-class-name followed by the
43 // template-parameters of the class template enclosed in
44 // <>. When it is used with a template-argument-list, it
45 // refers to the specified class template specialization,
46 // which could be the current specialization or another
47 // specialization.
48 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000049 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000050 if (Record->getDescribedClassTemplate())
51 return Record->getDescribedClassTemplate();
52
53 if (ClassTemplateSpecializationDecl *Spec
54 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
55 return Spec->getSpecializedTemplate();
56 }
Mike Stump11289f42009-09-09 15:08:12 +000057
Douglas Gregorb7bfe792009-09-02 22:59:36 +000058 return 0;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Douglas Gregorb7bfe792009-09-02 22:59:36 +000061 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
62 if (!Ovl)
63 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000064
Douglas Gregorb7bfe792009-09-02 22:59:36 +000065 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
66 FEnd = Ovl->function_end();
67 F != FEnd; ++F) {
68 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
69 // We've found a function template. Determine whether there are
70 // any other function templates we need to bundle together in an
71 // OverloadedFunctionDecl
72 for (++F; F != FEnd; ++F) {
73 if (isa<FunctionTemplateDecl>(*F))
74 break;
75 }
Mike Stump11289f42009-09-09 15:08:12 +000076
Douglas Gregorb7bfe792009-09-02 22:59:36 +000077 if (F != FEnd) {
78 // Build an overloaded function decl containing only the
79 // function templates in Ovl.
Mike Stump11289f42009-09-09 15:08:12 +000080 OverloadedFunctionDecl *OvlTemplate
Douglas Gregorb7bfe792009-09-02 22:59:36 +000081 = OverloadedFunctionDecl::Create(Context,
82 Ovl->getDeclContext(),
83 Ovl->getDeclName());
84 OvlTemplate->addOverload(FuncTmpl);
85 OvlTemplate->addOverload(*F);
86 for (++F; F != FEnd; ++F) {
87 if (isa<FunctionTemplateDecl>(*F))
88 OvlTemplate->addOverload(*F);
89 }
Mike Stump11289f42009-09-09 15:08:12 +000090
Douglas Gregorb7bfe792009-09-02 22:59:36 +000091 return OvlTemplate;
92 }
93
94 return FuncTmpl;
95 }
96 }
Mike Stump11289f42009-09-09 15:08:12 +000097
Douglas Gregorb7bfe792009-09-02 22:59:36 +000098 return 0;
99}
100
101TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000102 const CXXScopeSpec &SS,
103 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000104 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000105 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000106 TemplateTy &TemplateResult) {
Douglas Gregor3cf81312009-11-03 23:16:33 +0000107 DeclarationName TName;
108
109 switch (Name.getKind()) {
110 case UnqualifiedId::IK_Identifier:
111 TName = DeclarationName(Name.Identifier);
112 break;
113
114 case UnqualifiedId::IK_OperatorFunctionId:
115 TName = Context.DeclarationNames.getCXXOperatorName(
116 Name.OperatorFunctionId.Operator);
117 break;
118
119 default:
120 return TNK_Non_template;
121 }
122
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000123 // Determine where to perform name lookup
124 DeclContext *LookupCtx = 0;
125 bool isDependent = false;
126 if (ObjectTypePtr) {
127 // This nested-name-specifier occurs in a member access expression, e.g.,
128 // x->B::f, and we are looking into the type of the object.
Douglas Gregor3cf81312009-11-03 23:16:33 +0000129 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000130 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
131 LookupCtx = computeDeclContext(ObjectType);
132 isDependent = ObjectType->isDependentType();
Douglas Gregor3cf81312009-11-03 23:16:33 +0000133 } else if (SS.isSet()) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000134 // This nested-name-specifier occurs after another nested-name-specifier,
135 // so long into the context associated with the prior nested-name-specifier.
136
Douglas Gregor3cf81312009-11-03 23:16:33 +0000137 LookupCtx = computeDeclContext(SS, EnteringContext);
138 isDependent = isDependentScopeSpecifier(SS);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000139 }
Mike Stump11289f42009-09-09 15:08:12 +0000140
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000141 LookupResult Found;
142 bool ObjectTypeSearchedInScope = false;
143 if (LookupCtx) {
144 // Perform "qualified" name lookup into the declaration context we
145 // computed, which is either the type of the base of a member access
Mike Stump11289f42009-09-09 15:08:12 +0000146 // expression or the declaration context associated with a prior
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000147 // nested-name-specifier.
148
149 // The declaration context must be complete.
Douglas Gregor3cf81312009-11-03 23:16:33 +0000150 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(SS))
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000151 return TNK_Non_template;
Mike Stump11289f42009-09-09 15:08:12 +0000152
Douglas Gregor3cf81312009-11-03 23:16:33 +0000153 LookupQualifiedName(Found, LookupCtx, TName, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +0000154
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000155 if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
156 // C++ [basic.lookup.classref]p1:
157 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump11289f42009-09-09 15:08:12 +0000158 // immediately followed by an identifier followed by a <, the
159 // identifier must be looked up to determine whether the < is the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000160 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump11289f42009-09-09 15:08:12 +0000161 // The identifier is first looked up in the class of the object
162 // expression. If the identifier is not found, it is then looked up in
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000163 // the context of the entire postfix-expression and shall name a class
164 // or function template.
165 //
166 // FIXME: When we're instantiating a template, do we actually have to
167 // look in the scope of the template? Seems fishy...
Douglas Gregor3cf81312009-11-03 23:16:33 +0000168 LookupName(Found, S, TName, LookupOrdinaryName);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000169 ObjectTypeSearchedInScope = true;
170 }
171 } else if (isDependent) {
Mike Stump11289f42009-09-09 15:08:12 +0000172 // We cannot look into a dependent object type or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000173 return TNK_Non_template;
174 } else {
175 // Perform unqualified name lookup in the current scope.
Douglas Gregor3cf81312009-11-03 23:16:33 +0000176 LookupName(Found, S, TName, LookupOrdinaryName);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000177 }
Mike Stump11289f42009-09-09 15:08:12 +0000178
Douglas Gregore861bac2009-08-25 22:51:20 +0000179 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump11289f42009-09-09 15:08:12 +0000180 assert(!Found.isAmbiguous() &&
Douglas Gregore861bac2009-08-25 22:51:20 +0000181 "Cannot handle template name-lookup ambiguities");
Douglas Gregordc572a32009-03-30 22:58:21 +0000182
John McCall9f3059a2009-10-09 21:13:30 +0000183 NamedDecl *Template
184 = isAcceptableTemplateName(Context, Found.getAsSingleDecl(Context));
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000185 if (!Template)
186 return TNK_Non_template;
187
188 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
189 // C++ [basic.lookup.classref]p1:
Mike Stump11289f42009-09-09 15:08:12 +0000190 // [...] If the lookup in the class of the object expression finds a
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000191 // template, the name is also looked up in the context of the entire
192 // postfix-expression and [...]
193 //
John McCall9f3059a2009-10-09 21:13:30 +0000194 LookupResult FoundOuter;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000195 LookupName(FoundOuter, S, TName, LookupOrdinaryName);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000196 // FIXME: Handle ambiguities in this lookup better
John McCall9f3059a2009-10-09 21:13:30 +0000197 NamedDecl *OuterTemplate
198 = isAcceptableTemplateName(Context, FoundOuter.getAsSingleDecl(Context));
Mike Stump11289f42009-09-09 15:08:12 +0000199
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000200 if (!OuterTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +0000201 // - if the name is not found, the name found in the class of the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000202 // object expression is used, otherwise
203 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump11289f42009-09-09 15:08:12 +0000204 // - if the name is found in the context of the entire
205 // postfix-expression and does not name a class template, the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000206 // found in the class of the object expression is used, otherwise
207 } else {
208 // - if the name found is a class template, it must refer to the same
Mike Stump11289f42009-09-09 15:08:12 +0000209 // entity as the one found in the class of the object expression,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000210 // otherwise the program is ill-formed.
211 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
Douglas Gregor3cf81312009-11-03 23:16:33 +0000212 Diag(Name.getSourceRange().getBegin(),
213 diag::err_nested_name_member_ref_lookup_ambiguous)
214 << TName
215 << Name.getSourceRange();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000216 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
217 << QualType::getFromOpaquePtr(ObjectTypePtr);
218 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump11289f42009-09-09 15:08:12 +0000219
220 // Recover by taking the template that we found in the object
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000221 // expression's type.
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000222 }
Mike Stump11289f42009-09-09 15:08:12 +0000223 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000224 }
Mike Stump11289f42009-09-09 15:08:12 +0000225
Douglas Gregor3cf81312009-11-03 23:16:33 +0000226 if (SS.isSet() && !SS.isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000227 NestedNameSpecifier *Qualifier
Douglas Gregor3cf81312009-11-03 23:16:33 +0000228 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000229 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000230 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000231 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000232 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
233 Ovl));
234 else
Mike Stump11289f42009-09-09 15:08:12 +0000235 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000236 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000237 cast<TemplateDecl>(Template)));
238 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000239 = dyn_cast<OverloadedFunctionDecl>(Template)) {
240 TemplateResult = TemplateTy::make(TemplateName(Ovl));
241 } else {
242 TemplateResult = TemplateTy::make(
243 TemplateName(cast<TemplateDecl>(Template)));
244 }
Mike Stump11289f42009-09-09 15:08:12 +0000245
246 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000247 isa<TemplateTemplateParmDecl>(Template))
248 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000249
250 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000251 isa<OverloadedFunctionDecl>(Template)) &&
252 "Unhandled template kind in Sema::isTemplateName");
253 return TNK_Function_template;
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000254}
255
Douglas Gregor5101c242008-12-05 18:15:24 +0000256/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
257/// that the template parameter 'PrevDecl' is being shadowed by a new
258/// declaration at location Loc. Returns true to indicate that this is
259/// an error, and false otherwise.
260bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000261 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000262
263 // Microsoft Visual C++ permits template parameters to be shadowed.
264 if (getLangOptions().Microsoft)
265 return false;
266
267 // C++ [temp.local]p4:
268 // A template-parameter shall not be redeclared within its
269 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000270 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000271 << cast<NamedDecl>(PrevDecl)->getDeclName();
272 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
273 return true;
274}
275
Douglas Gregor463421d2009-03-03 04:44:36 +0000276/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000277/// the parameter D to reference the templated declaration and return a pointer
278/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000279TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000280 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000281 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000282 return Temp;
283 }
284 return 0;
285}
286
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000287static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
288 const ParsedTemplateArgument &Arg) {
289
290 switch (Arg.getKind()) {
291 case ParsedTemplateArgument::Type: {
292 DeclaratorInfo *DI;
293 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
294 if (!DI)
295 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation());
296 return TemplateArgumentLoc(TemplateArgument(T), DI);
297 }
298
299 case ParsedTemplateArgument::NonType: {
300 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
301 return TemplateArgumentLoc(TemplateArgument(E), E);
302 }
303
304 case ParsedTemplateArgument::Template: {
305 TemplateName Template
306 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
307 return TemplateArgumentLoc(TemplateArgument(Template),
308 Arg.getScopeSpec().getRange(),
309 Arg.getLocation());
310 }
311 }
312
313 llvm::llvm_unreachable("Unhandled parsed template argument");
314 return TemplateArgumentLoc();
315}
316
317/// \brief Translates template arguments as provided by the parser
318/// into template arguments used by semantic analysis.
319void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
320 llvm::SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs) {
321 TemplateArgs.reserve(TemplateArgsIn.size());
322
323 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
324 TemplateArgs.push_back(translateTemplateArgument(*this, TemplateArgsIn[I]));
325}
326
Douglas Gregor5101c242008-12-05 18:15:24 +0000327/// ActOnTypeParameter - Called when a C++ template type parameter
328/// (e.g., "typename T") has been parsed. Typename specifies whether
329/// the keyword "typename" was used to declare the type parameter
330/// (otherwise, "class" was used), and KeyLoc is the location of the
331/// "class" or "typename" keyword. ParamName is the name of the
332/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000333/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000334/// If the type parameter has a default argument, it will be added
335/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000336Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000337 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000338 SourceLocation KeyLoc,
339 IdentifierInfo *ParamName,
340 SourceLocation ParamNameLoc,
341 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000342 assert(S->isTemplateParamScope() &&
343 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000344 bool Invalid = false;
345
346 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000347 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000348 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000349 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000350 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000351 }
352
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000353 SourceLocation Loc = ParamNameLoc;
354 if (!ParamName)
355 Loc = KeyLoc;
356
Douglas Gregor5101c242008-12-05 18:15:24 +0000357 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000358 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
359 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000360 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000361 if (Invalid)
362 Param->setInvalidDecl();
363
364 if (ParamName) {
365 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000366 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000367 IdResolver.AddDecl(Param);
368 }
369
Chris Lattner83f095c2009-03-28 19:18:32 +0000370 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000371}
372
Douglas Gregordba32632009-02-10 19:49:53 +0000373/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000374/// Default) to the given template type parameter (TypeParam).
375void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000376 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000377 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000378 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000379 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000380 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000381
382 DeclaratorInfo *DefaultDInfo;
383 GetTypeFromParser(DefaultT, &DefaultDInfo);
384
385 assert(DefaultDInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000386
Anders Carlssond3824352009-06-12 22:30:13 +0000387 // C++0x [temp.param]p9:
388 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000389 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000390 if (Parm->isParameterPack()) {
391 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000392 return;
393 }
Mike Stump11289f42009-09-09 15:08:12 +0000394
Douglas Gregordba32632009-02-10 19:49:53 +0000395 // C++ [temp.param]p14:
396 // A template-parameter shall not be used in its own default argument.
397 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000398
Douglas Gregordba32632009-02-10 19:49:53 +0000399 // Check the template argument itself.
John McCall0ad16662009-10-29 08:12:44 +0000400 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000401 Parm->setInvalidDecl();
402 return;
403 }
404
John McCall0ad16662009-10-29 08:12:44 +0000405 Parm->setDefaultArgument(DefaultDInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000406}
407
Douglas Gregor463421d2009-03-03 04:44:36 +0000408/// \brief Check that the type of a non-type template parameter is
409/// well-formed.
410///
411/// \returns the (possibly-promoted) parameter type if valid;
412/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000413QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000414Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
415 // C++ [temp.param]p4:
416 //
417 // A non-type template-parameter shall have one of the following
418 // (optionally cv-qualified) types:
419 //
420 // -- integral or enumeration type,
421 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000422 // -- pointer to object or pointer to function,
423 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000424 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
425 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000426 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000427 T->isReferenceType() ||
428 // -- pointer to member.
429 T->isMemberPointerType() ||
430 // If T is a dependent type, we can't do the check now, so we
431 // assume that it is well-formed.
432 T->isDependentType())
433 return T;
434 // C++ [temp.param]p8:
435 //
436 // A non-type template-parameter of type "array of T" or
437 // "function returning T" is adjusted to be of type "pointer to
438 // T" or "pointer to function returning T", respectively.
439 else if (T->isArrayType())
440 // FIXME: Keep the type prior to promotion?
441 return Context.getArrayDecayedType(T);
442 else if (T->isFunctionType())
443 // FIXME: Keep the type prior to promotion?
444 return Context.getPointerType(T);
445
446 Diag(Loc, diag::err_template_nontype_parm_bad_type)
447 << T;
448
449 return QualType();
450}
451
Douglas Gregor5101c242008-12-05 18:15:24 +0000452/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
453/// template parameter (e.g., "int Size" in "template<int Size>
454/// class Array") has been parsed. S is the current scope and D is
455/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000456Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000457 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000458 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000459 DeclaratorInfo *DInfo = 0;
460 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000461
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000462 assert(S->isTemplateParamScope() &&
463 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000464 bool Invalid = false;
465
466 IdentifierInfo *ParamName = D.getIdentifier();
467 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000468 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000469 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000470 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000471 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000472 }
473
Douglas Gregor463421d2009-03-03 04:44:36 +0000474 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000475 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000476 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000477 Invalid = true;
478 }
Douglas Gregor81338792009-02-10 17:43:50 +0000479
Douglas Gregor5101c242008-12-05 18:15:24 +0000480 NonTypeTemplateParmDecl *Param
481 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000482 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000483 if (Invalid)
484 Param->setInvalidDecl();
485
486 if (D.getIdentifier()) {
487 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000488 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000489 IdResolver.AddDecl(Param);
490 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000491 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000492}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000493
Douglas Gregordba32632009-02-10 19:49:53 +0000494/// \brief Adds a default argument to the given non-type template
495/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000496void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000497 SourceLocation EqualLoc,
498 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000499 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000500 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000501 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000502
Douglas Gregordba32632009-02-10 19:49:53 +0000503 // C++ [temp.param]p14:
504 // A template-parameter shall not be used in its own default argument.
505 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000506
Douglas Gregordba32632009-02-10 19:49:53 +0000507 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000508 TemplateArgument Converted;
509 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
510 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000511 TemplateParm->setInvalidDecl();
512 return;
513 }
514
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000515 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000516}
517
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000518
519/// ActOnTemplateTemplateParameter - Called when a C++ template template
520/// parameter (e.g. T in template <template <typename> class T> class array)
521/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000522Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
523 SourceLocation TmpLoc,
524 TemplateParamsTy *Params,
525 IdentifierInfo *Name,
526 SourceLocation NameLoc,
527 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000528 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000529 assert(S->isTemplateParamScope() &&
530 "Template template parameter not in template parameter scope!");
531
532 // Construct the parameter object.
533 TemplateTemplateParmDecl *Param =
534 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
535 Position, Name,
536 (TemplateParameterList*)Params);
537
538 // Make sure the parameter is valid.
539 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
540 // do anything yet. However, if the template parameter list or (eventual)
541 // default value is ever invalidated, that will propagate here.
542 bool Invalid = false;
543 if (Invalid) {
544 Param->setInvalidDecl();
545 }
546
547 // If the tt-param has a name, then link the identifier into the scope
548 // and lookup mechanisms.
549 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000550 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000551 IdResolver.AddDecl(Param);
552 }
553
Chris Lattner83f095c2009-03-28 19:18:32 +0000554 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000555}
556
Douglas Gregordba32632009-02-10 19:49:53 +0000557/// \brief Adds a default argument to the given template template
558/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000559void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000560 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000561 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000562 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000563 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000564
Douglas Gregordba32632009-02-10 19:49:53 +0000565 // C++ [temp.param]p14:
566 // A template-parameter shall not be used in its own default argument.
567 // FIXME: Implement this check! Needs a recursive walk over the types.
568
569 // Check the well-formedness of the template argument.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000570 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
571 if (CheckTemplateArgument(TemplateParm, DefaultArg)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000572 TemplateParm->setInvalidDecl();
573 return;
574 }
575
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000576 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000577}
578
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000579/// ActOnTemplateParameterList - Builds a TemplateParameterList that
580/// contains the template parameters in Params/NumParams.
581Sema::TemplateParamsTy *
582Sema::ActOnTemplateParameterList(unsigned Depth,
583 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000584 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000585 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000586 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000587 SourceLocation RAngleLoc) {
588 if (ExportLoc.isValid())
589 Diag(ExportLoc, diag::note_template_export_unsupported);
590
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000591 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000592 (NamedDecl**)Params, NumParams,
593 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000594}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000595
Douglas Gregorc08f4892009-03-25 00:13:59 +0000596Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000597Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000598 SourceLocation KWLoc, const CXXScopeSpec &SS,
599 IdentifierInfo *Name, SourceLocation NameLoc,
600 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000601 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000602 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000603 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000604 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000605 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000606 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000607
608 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000609 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000610 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000611
John McCall27b5c252009-09-14 21:59:20 +0000612 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
613 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000614
615 // There is no such thing as an unnamed class template.
616 if (!Name) {
617 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000618 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000619 }
620
621 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000622 DeclContext *SemanticContext;
623 LookupResult Previous;
624 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000625 if (RequireCompleteDeclContext(SS))
626 return true;
627
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000628 SemanticContext = computeDeclContext(SS, true);
629 if (!SemanticContext) {
630 // FIXME: Produce a reasonable diagnostic here
631 return true;
632 }
Mike Stump11289f42009-09-09 15:08:12 +0000633
John McCall9f3059a2009-10-09 21:13:30 +0000634 LookupQualifiedName(Previous, SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000635 true);
636 } else {
637 SemanticContext = CurContext;
John McCall9f3059a2009-10-09 21:13:30 +0000638 LookupName(Previous, S, Name, LookupOrdinaryName, true);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000639 }
Mike Stump11289f42009-09-09 15:08:12 +0000640
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000641 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
642 NamedDecl *PrevDecl = 0;
643 if (Previous.begin() != Previous.end())
644 PrevDecl = *Previous.begin();
645
Douglas Gregor9acb6902009-09-26 07:05:09 +0000646 if (PrevDecl && TUK == TUK_Friend) {
647 // C++ [namespace.memdef]p3:
648 // [...] When looking for a prior declaration of a class or a function
649 // declared as a friend, and when the name of the friend class or
650 // function is neither a qualified name nor a template-id, scopes outside
651 // the innermost enclosing namespace scope are not considered.
652 DeclContext *OutermostContext = CurContext;
653 while (!OutermostContext->isFileContext())
654 OutermostContext = OutermostContext->getLookupParent();
655
656 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
657 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
658 SemanticContext = PrevDecl->getDeclContext();
659 } else {
660 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000661 // context we computed is the semantic context for our new
Douglas Gregor9acb6902009-09-26 07:05:09 +0000662 // declaration.
663 PrevDecl = 0;
664 SemanticContext = OutermostContext;
665 }
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000666
667 if (CurContext->isDependentContext()) {
668 // If this is a dependent context, we don't want to link the friend
669 // class template to the template in scope, because that would perform
670 // checking of the template parameter lists that can't be performed
671 // until the outer context is instantiated.
672 PrevDecl = 0;
673 }
Douglas Gregor9acb6902009-09-26 07:05:09 +0000674 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000675 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000676
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000677 // If there is a previous declaration with the same name, check
678 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000679 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000680 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000681
682 // We may have found the injected-class-name of a class template,
683 // class template partial specialization, or class template specialization.
684 // In these cases, grab the template that is being defined or specialized.
685 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
686 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
687 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
688 PrevClassTemplate
689 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
690 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
691 PrevClassTemplate
692 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
693 ->getSpecializedTemplate();
694 }
695 }
696
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000697 if (PrevClassTemplate) {
698 // Ensure that the template parameter lists are compatible.
699 if (!TemplateParameterListsAreEqual(TemplateParams,
700 PrevClassTemplate->getTemplateParameters(),
701 /*Complain=*/true))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000702 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000703
704 // C++ [temp.class]p4:
705 // In a redeclaration, partial specialization, explicit
706 // specialization or explicit instantiation of a class template,
707 // the class-key shall agree in kind with the original class
708 // template declaration (7.1.5.3).
709 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000710 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000711 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000712 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000713 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000714 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000715 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000716 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000717 }
718
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000719 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000720 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000721 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
722 Diag(NameLoc, diag::err_redefinition) << Name;
723 Diag(Def->getLocation(), diag::note_previous_definition);
724 // FIXME: Would it make sense to try to "forget" the previous
725 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000726 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000727 }
728 }
729 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
730 // Maybe we will complain about the shadowed template parameter.
731 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
732 // Just pretend that we didn't see the previous declaration.
733 PrevDecl = 0;
734 } else if (PrevDecl) {
735 // C++ [temp]p5:
736 // A class template shall not have the same name as any other
737 // template, class, function, object, enumeration, enumerator,
738 // namespace, or type in the same scope (3.3), except as specified
739 // in (14.5.4).
740 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
741 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000742 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000743 }
744
Douglas Gregordba32632009-02-10 19:49:53 +0000745 // Check the template parameter list of this declaration, possibly
746 // merging in the template parameter list from the previous class
747 // template declaration.
748 if (CheckTemplateParameterList(TemplateParams,
749 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
750 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000751
Douglas Gregore362cea2009-05-10 22:57:19 +0000752 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000753 // declaration!
754
Mike Stump11289f42009-09-09 15:08:12 +0000755 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000756 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000757 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000758 PrevClassTemplate->getTemplatedDecl() : 0,
759 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000760
761 ClassTemplateDecl *NewTemplate
762 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
763 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000764 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000765 NewClass->setDescribedClassTemplate(NewTemplate);
766
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000767 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000768 QualType T =
769 Context.getTypeDeclType(NewClass,
770 PrevClassTemplate?
771 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000772 assert(T->isDependentType() && "Class template type is not dependent?");
773 (void)T;
774
Douglas Gregorcf915552009-10-13 16:30:37 +0000775 // If we are providing an explicit specialization of a member that is a
776 // class template, make a note of that.
777 if (PrevClassTemplate &&
778 PrevClassTemplate->getInstantiatedFromMemberTemplate())
779 PrevClassTemplate->setMemberSpecialization();
780
Anders Carlsson137108d2009-03-26 01:24:28 +0000781 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000782 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000783 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000784
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000785 // Set the lexical context of these templates
786 NewClass->setLexicalDeclContext(CurContext);
787 NewTemplate->setLexicalDeclContext(CurContext);
788
John McCall9bb74a52009-07-31 02:45:11 +0000789 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000790 NewClass->startDefinition();
791
792 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000793 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000794
John McCall27b5c252009-09-14 21:59:20 +0000795 if (TUK != TUK_Friend)
796 PushOnScopeChains(NewTemplate, S);
797 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000798 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000799 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000800 NewClass->setAccess(PrevClassTemplate->getAccess());
801 }
John McCall27b5c252009-09-14 21:59:20 +0000802
Douglas Gregor3dad8422009-09-26 06:47:28 +0000803 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
804 PrevClassTemplate != NULL);
805
John McCall27b5c252009-09-14 21:59:20 +0000806 // Friend templates are visible in fairly strange ways.
807 if (!CurContext->isDependentContext()) {
808 DeclContext *DC = SemanticContext->getLookupContext();
809 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
810 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
811 PushOnScopeChains(NewTemplate, EnclosingScope,
812 /* AddToContext = */ false);
813 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000814
815 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
816 NewClass->getLocation(),
817 NewTemplate,
818 /*FIXME:*/NewClass->getLocation());
819 Friend->setAccess(AS_public);
820 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000821 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000822
Douglas Gregordba32632009-02-10 19:49:53 +0000823 if (Invalid) {
824 NewTemplate->setInvalidDecl();
825 NewClass->setInvalidDecl();
826 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000827 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000828}
829
Douglas Gregordba32632009-02-10 19:49:53 +0000830/// \brief Checks the validity of a template parameter list, possibly
831/// considering the template parameter list from a previous
832/// declaration.
833///
834/// If an "old" template parameter list is provided, it must be
835/// equivalent (per TemplateParameterListsAreEqual) to the "new"
836/// template parameter list.
837///
838/// \param NewParams Template parameter list for a new template
839/// declaration. This template parameter list will be updated with any
840/// default arguments that are carried through from the previous
841/// template parameter list.
842///
843/// \param OldParams If provided, template parameter list from a
844/// previous declaration of the same template. Default template
845/// arguments will be merged from the old template parameter list to
846/// the new template parameter list.
847///
848/// \returns true if an error occurred, false otherwise.
849bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
850 TemplateParameterList *OldParams) {
851 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000852
Douglas Gregordba32632009-02-10 19:49:53 +0000853 // C++ [temp.param]p10:
854 // The set of default template-arguments available for use with a
855 // template declaration or definition is obtained by merging the
856 // default arguments from the definition (if in scope) and all
857 // declarations in scope in the same way default function
858 // arguments are (8.3.6).
859 bool SawDefaultArgument = false;
860 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000861
Anders Carlsson327865d2009-06-12 23:20:15 +0000862 bool SawParameterPack = false;
863 SourceLocation ParameterPackLoc;
864
Mike Stumpc89c8e32009-02-11 23:03:27 +0000865 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000866 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000867 if (OldParams)
868 OldParam = OldParams->begin();
869
870 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
871 NewParamEnd = NewParams->end();
872 NewParam != NewParamEnd; ++NewParam) {
873 // Variables used to diagnose redundant default arguments
874 bool RedundantDefaultArg = false;
875 SourceLocation OldDefaultLoc;
876 SourceLocation NewDefaultLoc;
877
878 // Variables used to diagnose missing default arguments
879 bool MissingDefaultArg = false;
880
Anders Carlsson327865d2009-06-12 23:20:15 +0000881 // C++0x [temp.param]p11:
882 // If a template parameter of a class template is a template parameter pack,
883 // it must be the last template parameter.
884 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +0000885 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +0000886 diag::err_template_param_pack_must_be_last_template_parameter);
887 Invalid = true;
888 }
889
Douglas Gregordba32632009-02-10 19:49:53 +0000890 // Merge default arguments for template type parameters.
891 if (TemplateTypeParmDecl *NewTypeParm
892 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump11289f42009-09-09 15:08:12 +0000893 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000894 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000895
Anders Carlsson327865d2009-06-12 23:20:15 +0000896 if (NewTypeParm->isParameterPack()) {
897 assert(!NewTypeParm->hasDefaultArgument() &&
898 "Parameter packs can't have a default argument!");
899 SawParameterPack = true;
900 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000901 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +0000902 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +0000903 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
904 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
905 SawDefaultArgument = true;
906 RedundantDefaultArg = true;
907 PreviousDefaultArgLoc = NewDefaultLoc;
908 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
909 // Merge the default argument from the old declaration to the
910 // new declaration.
911 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +0000912 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +0000913 true);
914 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
915 } else if (NewTypeParm->hasDefaultArgument()) {
916 SawDefaultArgument = true;
917 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
918 } else if (SawDefaultArgument)
919 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000920 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000921 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000922 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000923 NonTypeTemplateParmDecl *OldNonTypeParm
924 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000925 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000926 NewNonTypeParm->hasDefaultArgument()) {
927 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
928 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
929 SawDefaultArgument = true;
930 RedundantDefaultArg = true;
931 PreviousDefaultArgLoc = NewDefaultLoc;
932 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
933 // Merge the default argument from the old declaration to the
934 // new declaration.
935 SawDefaultArgument = true;
936 // FIXME: We need to create a new kind of "default argument"
937 // expression that points to a previous template template
938 // parameter.
939 NewNonTypeParm->setDefaultArgument(
940 OldNonTypeParm->getDefaultArgument());
941 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
942 } else if (NewNonTypeParm->hasDefaultArgument()) {
943 SawDefaultArgument = true;
944 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
945 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000946 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000947 } else {
Douglas Gregordba32632009-02-10 19:49:53 +0000948 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000949 TemplateTemplateParmDecl *NewTemplateParm
950 = cast<TemplateTemplateParmDecl>(*NewParam);
951 TemplateTemplateParmDecl *OldTemplateParm
952 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000953 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000954 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000955 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
956 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +0000957 SawDefaultArgument = true;
958 RedundantDefaultArg = true;
959 PreviousDefaultArgLoc = NewDefaultLoc;
960 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
961 // Merge the default argument from the old declaration to the
962 // new declaration.
963 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +0000964 // FIXME: We need to create a new kind of "default argument" expression
965 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +0000966 NewTemplateParm->setDefaultArgument(
967 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000968 PreviousDefaultArgLoc
969 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +0000970 } else if (NewTemplateParm->hasDefaultArgument()) {
971 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000972 PreviousDefaultArgLoc
973 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +0000974 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000975 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +0000976 }
977
978 if (RedundantDefaultArg) {
979 // C++ [temp.param]p12:
980 // A template-parameter shall not be given default arguments
981 // by two different declarations in the same scope.
982 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
983 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
984 Invalid = true;
985 } else if (MissingDefaultArg) {
986 // C++ [temp.param]p11:
987 // If a template-parameter has a default template-argument,
988 // all subsequent template-parameters shall have a default
989 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +0000990 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +0000991 diag::err_template_param_default_arg_missing);
992 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
993 Invalid = true;
994 }
995
996 // If we have an old template parameter list that we're merging
997 // in, move on to the next parameter.
998 if (OldParams)
999 ++OldParam;
1000 }
1001
1002 return Invalid;
1003}
Douglas Gregord32e0282009-02-09 23:23:08 +00001004
Mike Stump11289f42009-09-09 15:08:12 +00001005/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001006/// specifier, returning the template parameter list that applies to the
1007/// name.
1008///
1009/// \param DeclStartLoc the start of the declaration that has a scope
1010/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001011///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001012/// \param SS the scope specifier that will be matched to the given template
1013/// parameter lists. This scope specifier precedes a qualified name that is
1014/// being declared.
1015///
1016/// \param ParamLists the template parameter lists, from the outermost to the
1017/// innermost template parameter lists.
1018///
1019/// \param NumParamLists the number of template parameter lists in ParamLists.
1020///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001021/// \param IsExplicitSpecialization will be set true if the entity being
1022/// declared is an explicit specialization, false otherwise.
1023///
Mike Stump11289f42009-09-09 15:08:12 +00001024/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001025/// name that is preceded by the scope specifier @p SS. This template
1026/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001027/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001028/// template specialization), or may be NULL (if we were's declaring isn't
1029/// itself a template).
1030TemplateParameterList *
1031Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1032 const CXXScopeSpec &SS,
1033 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001034 unsigned NumParamLists,
1035 bool &IsExplicitSpecialization) {
1036 IsExplicitSpecialization = false;
1037
Douglas Gregord8d297c2009-07-21 23:53:31 +00001038 // Find the template-ids that occur within the nested-name-specifier. These
1039 // template-ids will match up with the template parameter lists.
1040 llvm::SmallVector<const TemplateSpecializationType *, 4>
1041 TemplateIdsInSpecifier;
1042 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1043 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +00001044 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +00001045 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1046 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1047 if (!Template)
1048 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001049
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001050 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001051 ClassTemplateSpecializationDecl *SpecDecl
1052 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1053 // If the nested name specifier refers to an explicit specialization,
1054 // we don't need a template<> header.
Douglas Gregor82e22862009-09-16 00:01:48 +00001055 // FIXME: revisit this approach once we cope with specializations
Douglas Gregor15301382009-07-30 17:40:51 +00001056 // properly.
Douglas Gregord8d297c2009-07-21 23:53:31 +00001057 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
1058 continue;
1059 }
Mike Stump11289f42009-09-09 15:08:12 +00001060
Douglas Gregord8d297c2009-07-21 23:53:31 +00001061 TemplateIdsInSpecifier.push_back(SpecType);
1062 }
1063 }
Mike Stump11289f42009-09-09 15:08:12 +00001064
Douglas Gregord8d297c2009-07-21 23:53:31 +00001065 // Reverse the list of template-ids in the scope specifier, so that we can
1066 // more easily match up the template-ids and the template parameter lists.
1067 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001068
Douglas Gregord8d297c2009-07-21 23:53:31 +00001069 SourceLocation FirstTemplateLoc = DeclStartLoc;
1070 if (NumParamLists)
1071 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001072
Douglas Gregord8d297c2009-07-21 23:53:31 +00001073 // Match the template-ids found in the specifier to the template parameter
1074 // lists.
1075 unsigned Idx = 0;
1076 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1077 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001078 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1079 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001080 if (Idx >= NumParamLists) {
1081 // We have a template-id without a corresponding template parameter
1082 // list.
1083 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001084 // FIXME: the location information here isn't great.
1085 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001086 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001087 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001088 << SS.getRange();
1089 } else {
1090 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1091 << SS.getRange()
1092 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1093 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001094 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001095 }
1096 return 0;
1097 }
Mike Stump11289f42009-09-09 15:08:12 +00001098
Douglas Gregord8d297c2009-07-21 23:53:31 +00001099 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001100 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001101 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001102 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1103
Mike Stump11289f42009-09-09 15:08:12 +00001104 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001105 = dyn_cast<ClassTemplateDecl>(Template)) {
1106 TemplateParameterList *ExpectedTemplateParams = 0;
1107 // Is this template-id naming the primary template?
1108 if (Context.hasSameType(TemplateId,
1109 ClassTemplate->getInjectedClassNameType(Context)))
1110 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1111 // ... or a partial specialization?
1112 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1113 = ClassTemplate->findPartialSpecialization(TemplateId))
1114 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1115
1116 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001117 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001118 ExpectedTemplateParams,
1119 true);
Mike Stump11289f42009-09-09 15:08:12 +00001120 }
Douglas Gregor15301382009-07-30 17:40:51 +00001121 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001122 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001123 diag::err_template_param_list_matches_nontemplate)
1124 << TemplateId
1125 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001126 else
1127 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001128 }
Mike Stump11289f42009-09-09 15:08:12 +00001129
Douglas Gregord8d297c2009-07-21 23:53:31 +00001130 // If there were at least as many template-ids as there were template
1131 // parameter lists, then there are no template parameter lists remaining for
1132 // the declaration itself.
1133 if (Idx >= NumParamLists)
1134 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001135
Douglas Gregord8d297c2009-07-21 23:53:31 +00001136 // If there were too many template parameter lists, complain about that now.
1137 if (Idx != NumParamLists - 1) {
1138 while (Idx < NumParamLists - 1) {
Mike Stump11289f42009-09-09 15:08:12 +00001139 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001140 diag::err_template_spec_extra_headers)
1141 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1142 ParamLists[Idx]->getRAngleLoc());
1143 ++Idx;
1144 }
1145 }
Mike Stump11289f42009-09-09 15:08:12 +00001146
Douglas Gregord8d297c2009-07-21 23:53:31 +00001147 // Return the last template parameter list, which corresponds to the
1148 // entity being declared.
1149 return ParamLists[NumParamLists - 1];
1150}
1151
Douglas Gregordc572a32009-03-30 22:58:21 +00001152QualType Sema::CheckTemplateIdType(TemplateName Name,
1153 SourceLocation TemplateLoc,
1154 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001155 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregordc572a32009-03-30 22:58:21 +00001156 unsigned NumTemplateArgs,
1157 SourceLocation RAngleLoc) {
1158 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001159 if (!Template) {
1160 // The template name does not resolve to a template, so we just
1161 // build a dependent template-id type.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001162 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001163 NumTemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001164 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001165
Douglas Gregorc40290e2009-03-09 23:48:35 +00001166 // Check that the template argument list is well-formed for this
1167 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001168 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1169 NumTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001170 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001171 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001172 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001173 return QualType();
1174
Mike Stump11289f42009-09-09 15:08:12 +00001175 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001176 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001177 "Converted template argument list is too short!");
1178
1179 QualType CanonType;
1180
Douglas Gregordc572a32009-03-30 22:58:21 +00001181 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorc40290e2009-03-09 23:48:35 +00001182 TemplateArgs,
1183 NumTemplateArgs)) {
1184 // This class template specialization is a dependent
1185 // type. Therefore, its canonical type is another class template
1186 // specialization type that contains all of the converted
1187 // arguments in canonical form. This ensures that, e.g., A<T> and
1188 // A<T, T> have identical types when A is declared as:
1189 //
1190 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001191 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001192 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001193 Converted.getFlatArguments(),
1194 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001195
Douglas Gregora8e02e72009-07-28 23:00:59 +00001196 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001197 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001198 // In the future, we need to teach getTemplateSpecializationType to only
1199 // build the canonical type and return that to us.
1200 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001201 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001202 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001203 // Find the class template specialization declaration that
1204 // corresponds to these arguments.
1205 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001206 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001207 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001208 Converted.flatSize(),
1209 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001210 void *InsertPos = 0;
1211 ClassTemplateSpecializationDecl *Decl
1212 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1213 if (!Decl) {
1214 // This is the first time we have referenced this class template
1215 // specialization. Create the canonical declaration and add it to
1216 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001217 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001218 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001219 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001220 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001221 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001222 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1223 Decl->setLexicalDeclContext(CurContext);
1224 }
1225
1226 CanonType = Context.getTypeDeclType(Decl);
1227 }
Mike Stump11289f42009-09-09 15:08:12 +00001228
Douglas Gregorc40290e2009-03-09 23:48:35 +00001229 // Build the fully-sugared type for this class template
1230 // specialization, which refers back to the class template
1231 // specialization we created or found.
Douglas Gregordc572a32009-03-30 22:58:21 +00001232 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1233 NumTemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001234}
1235
Douglas Gregor67a65642009-02-17 23:15:12 +00001236Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001237Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001238 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001239 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001240 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001241 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001242
Douglas Gregorc40290e2009-03-09 23:48:35 +00001243 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00001244 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001245 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001246
Douglas Gregordc572a32009-03-30 22:58:21 +00001247 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +00001248 TemplateArgs.data(),
1249 TemplateArgs.size(),
Douglas Gregordc572a32009-03-30 22:58:21 +00001250 RAngleLoc);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001251 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001252
1253 if (Result.isNull())
1254 return true;
1255
John McCall0ad16662009-10-29 08:12:44 +00001256 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1257 TemplateSpecializationTypeLoc TL
1258 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1259 TL.setTemplateNameLoc(TemplateLoc);
1260 TL.setLAngleLoc(LAngleLoc);
1261 TL.setRAngleLoc(RAngleLoc);
1262 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1263 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1264
1265 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001266}
John McCall06f6fe8d2009-09-04 01:14:41 +00001267
John McCalld8fe9af2009-09-08 17:47:29 +00001268Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1269 TagUseKind TUK,
1270 DeclSpec::TST TagSpec,
1271 SourceLocation TagLoc) {
1272 if (TypeResult.isInvalid())
1273 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001274
John McCall0ad16662009-10-29 08:12:44 +00001275 // FIXME: preserve source info, ideally without copying the DI.
1276 DeclaratorInfo *DI;
1277 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001278
John McCalld8fe9af2009-09-08 17:47:29 +00001279 // Verify the tag specifier.
1280 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001281
John McCalld8fe9af2009-09-08 17:47:29 +00001282 if (const RecordType *RT = Type->getAs<RecordType>()) {
1283 RecordDecl *D = RT->getDecl();
1284
1285 IdentifierInfo *Id = D->getIdentifier();
1286 assert(Id && "templated class must have an identifier");
1287
1288 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1289 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001290 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001291 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1292 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001293 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001294 }
1295 }
1296
John McCalld8fe9af2009-09-08 17:47:29 +00001297 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1298
1299 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001300}
1301
Douglas Gregord019ff62009-10-22 17:20:55 +00001302Sema::OwningExprResult Sema::BuildTemplateIdExpr(NestedNameSpecifier *Qualifier,
1303 SourceRange QualifierRange,
1304 TemplateName Template,
Douglas Gregora727cb92009-06-30 22:34:41 +00001305 SourceLocation TemplateNameLoc,
1306 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001307 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001308 unsigned NumTemplateArgs,
1309 SourceLocation RAngleLoc) {
1310 // FIXME: Can we do any checking at this point? I guess we could check the
1311 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001312 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001313 // though.
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001314
1315 // Cope with an implicit member access in a C++ non-static member function.
1316 NamedDecl *D = Template.getAsTemplateDecl();
1317 if (!D)
1318 D = Template.getAsOverloadedFunctionDecl();
1319
Douglas Gregord019ff62009-10-22 17:20:55 +00001320 CXXScopeSpec SS;
1321 SS.setRange(QualifierRange);
1322 SS.setScopeRep(Qualifier);
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001323 QualType ThisType, MemberType;
Douglas Gregord019ff62009-10-22 17:20:55 +00001324 if (D && isImplicitMemberReference(&SS, D, TemplateNameLoc,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001325 ThisType, MemberType)) {
1326 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
1327 return Owned(MemberExpr::Create(Context, This, true,
Douglas Gregord019ff62009-10-22 17:20:55 +00001328 Qualifier, QualifierRange,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001329 D, TemplateNameLoc, true,
1330 LAngleLoc, TemplateArgs,
1331 NumTemplateArgs, RAngleLoc,
1332 Context.OverloadTy));
1333 }
1334
Douglas Gregord019ff62009-10-22 17:20:55 +00001335 return Owned(TemplateIdRefExpr::Create(Context, Context.OverloadTy,
1336 Qualifier, QualifierRange,
Douglas Gregora727cb92009-06-30 22:34:41 +00001337 Template, TemplateNameLoc, LAngleLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001338 TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001339 NumTemplateArgs, RAngleLoc));
1340}
1341
Douglas Gregord019ff62009-10-22 17:20:55 +00001342Sema::OwningExprResult Sema::ActOnTemplateIdExpr(const CXXScopeSpec &SS,
1343 TemplateTy TemplateD,
Douglas Gregora727cb92009-06-30 22:34:41 +00001344 SourceLocation TemplateNameLoc,
1345 SourceLocation LAngleLoc,
1346 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora727cb92009-06-30 22:34:41 +00001347 SourceLocation RAngleLoc) {
1348 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001349
Douglas Gregora727cb92009-06-30 22:34:41 +00001350 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00001351 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001352 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001353 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001354
Douglas Gregord019ff62009-10-22 17:20:55 +00001355 return BuildTemplateIdExpr((NestedNameSpecifier *)SS.getScopeRep(),
1356 SS.getRange(),
1357 Template, TemplateNameLoc, LAngleLoc,
Douglas Gregora727cb92009-06-30 22:34:41 +00001358 TemplateArgs.data(), TemplateArgs.size(),
1359 RAngleLoc);
1360}
1361
Douglas Gregorb67535d2009-03-31 00:43:58 +00001362/// \brief Form a dependent template name.
1363///
1364/// This action forms a dependent template name given the template
1365/// name and its (presumably dependent) scope specifier. For
1366/// example, given "MetaFun::template apply", the scope specifier \p
1367/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1368/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001369Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001370Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001371 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001372 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001373 TypeTy *ObjectType) {
Mike Stump11289f42009-09-09 15:08:12 +00001374 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001375 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1376 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001377 // C++0x [temp.names]p5:
1378 // If a name prefixed by the keyword template is not the name of
1379 // a template, the program is ill-formed. [Note: the keyword
1380 // template may not be applied to non-template members of class
1381 // templates. -end note ] [ Note: as is the case with the
1382 // typename prefix, the template prefix is allowed in cases
1383 // where it is not strictly necessary; i.e., when the
1384 // nested-name-specifier or the expression on the left of the ->
1385 // or . is not dependent on a template-parameter, or the use
1386 // does not appear in the scope of a template. -end note]
1387 //
1388 // Note: C++03 was more strict here, because it banned the use of
1389 // the "template" keyword prior to a template-name that was not a
1390 // dependent name. C++ DR468 relaxed this requirement (the
1391 // "template" keyword is now permitted). We follow the C++0x
1392 // rules, even in C++03 mode, retroactively applying the DR.
1393 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001394 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001395 false, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001396 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001397 Diag(Name.getSourceRange().getBegin(),
1398 diag::err_template_kw_refers_to_non_template)
1399 << GetNameFromUnqualifiedId(Name)
1400 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001401 return TemplateTy();
1402 }
1403
1404 return Template;
1405 }
1406
Mike Stump11289f42009-09-09 15:08:12 +00001407 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001408 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001409
1410 switch (Name.getKind()) {
1411 case UnqualifiedId::IK_Identifier:
1412 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1413 Name.Identifier));
1414
Douglas Gregor71395fa2009-11-04 00:56:37 +00001415 case UnqualifiedId::IK_OperatorFunctionId:
1416 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1417 Name.OperatorFunctionId.Operator));
1418
Douglas Gregor3cf81312009-11-03 23:16:33 +00001419 default:
1420 break;
1421 }
1422
1423 Diag(Name.getSourceRange().getBegin(),
1424 diag::err_template_kw_refers_to_non_template)
1425 << GetNameFromUnqualifiedId(Name)
1426 << Name.getSourceRange();
1427 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001428}
1429
Mike Stump11289f42009-09-09 15:08:12 +00001430bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001431 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001432 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001433 const TemplateArgument &Arg = AL.getArgument();
1434
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001435 // Check template type parameter.
1436 if (Arg.getKind() != TemplateArgument::Type) {
1437 // C++ [temp.arg.type]p1:
1438 // A template-argument for a template-parameter which is a
1439 // type shall be a type-id.
1440
1441 // We have a template type parameter but the template argument
1442 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001443 SourceRange SR = AL.getSourceRange();
1444 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001445 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001446
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001447 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001448 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001449
John McCall0ad16662009-10-29 08:12:44 +00001450 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001451 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001452
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001453 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001454 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001455 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001456 return false;
1457}
1458
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001459/// \brief Substitute template arguments into the default template argument for
1460/// the given template type parameter.
1461///
1462/// \param SemaRef the semantic analysis object for which we are performing
1463/// the substitution.
1464///
1465/// \param Template the template that we are synthesizing template arguments
1466/// for.
1467///
1468/// \param TemplateLoc the location of the template name that started the
1469/// template-id we are checking.
1470///
1471/// \param RAngleLoc the location of the right angle bracket ('>') that
1472/// terminates the template-id.
1473///
1474/// \param Param the template template parameter whose default we are
1475/// substituting into.
1476///
1477/// \param Converted the list of template arguments provided for template
1478/// parameters that precede \p Param in the template parameter list.
1479///
1480/// \returns the substituted template argument, or NULL if an error occurred.
1481static DeclaratorInfo *
1482SubstDefaultTemplateArgument(Sema &SemaRef,
1483 TemplateDecl *Template,
1484 SourceLocation TemplateLoc,
1485 SourceLocation RAngleLoc,
1486 TemplateTypeParmDecl *Param,
1487 TemplateArgumentListBuilder &Converted) {
1488 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1489
1490 // If the argument type is dependent, instantiate it now based
1491 // on the previously-computed template arguments.
1492 if (ArgType->getType()->isDependentType()) {
1493 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1494 /*TakeArgs=*/false);
1495
1496 MultiLevelTemplateArgumentList AllTemplateArgs
1497 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1498
1499 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1500 Template, Converted.getFlatArguments(),
1501 Converted.flatSize(),
1502 SourceRange(TemplateLoc, RAngleLoc));
1503
1504 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1505 Param->getDefaultArgumentLoc(),
1506 Param->getDeclName());
1507 }
1508
1509 return ArgType;
1510}
1511
1512/// \brief Substitute template arguments into the default template argument for
1513/// the given non-type template parameter.
1514///
1515/// \param SemaRef the semantic analysis object for which we are performing
1516/// the substitution.
1517///
1518/// \param Template the template that we are synthesizing template arguments
1519/// for.
1520///
1521/// \param TemplateLoc the location of the template name that started the
1522/// template-id we are checking.
1523///
1524/// \param RAngleLoc the location of the right angle bracket ('>') that
1525/// terminates the template-id.
1526///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001527/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001528/// substituting into.
1529///
1530/// \param Converted the list of template arguments provided for template
1531/// parameters that precede \p Param in the template parameter list.
1532///
1533/// \returns the substituted template argument, or NULL if an error occurred.
1534static Sema::OwningExprResult
1535SubstDefaultTemplateArgument(Sema &SemaRef,
1536 TemplateDecl *Template,
1537 SourceLocation TemplateLoc,
1538 SourceLocation RAngleLoc,
1539 NonTypeTemplateParmDecl *Param,
1540 TemplateArgumentListBuilder &Converted) {
1541 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1542 /*TakeArgs=*/false);
1543
1544 MultiLevelTemplateArgumentList AllTemplateArgs
1545 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1546
1547 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1548 Template, Converted.getFlatArguments(),
1549 Converted.flatSize(),
1550 SourceRange(TemplateLoc, RAngleLoc));
1551
1552 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1553}
1554
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001555/// \brief Substitute template arguments into the default template argument for
1556/// the given template template parameter.
1557///
1558/// \param SemaRef the semantic analysis object for which we are performing
1559/// the substitution.
1560///
1561/// \param Template the template that we are synthesizing template arguments
1562/// for.
1563///
1564/// \param TemplateLoc the location of the template name that started the
1565/// template-id we are checking.
1566///
1567/// \param RAngleLoc the location of the right angle bracket ('>') that
1568/// terminates the template-id.
1569///
1570/// \param Param the template template parameter whose default we are
1571/// substituting into.
1572///
1573/// \param Converted the list of template arguments provided for template
1574/// parameters that precede \p Param in the template parameter list.
1575///
1576/// \returns the substituted template argument, or NULL if an error occurred.
1577static TemplateName
1578SubstDefaultTemplateArgument(Sema &SemaRef,
1579 TemplateDecl *Template,
1580 SourceLocation TemplateLoc,
1581 SourceLocation RAngleLoc,
1582 TemplateTemplateParmDecl *Param,
1583 TemplateArgumentListBuilder &Converted) {
1584 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1585 /*TakeArgs=*/false);
1586
1587 MultiLevelTemplateArgumentList AllTemplateArgs
1588 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1589
1590 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1591 Template, Converted.getFlatArguments(),
1592 Converted.flatSize(),
1593 SourceRange(TemplateLoc, RAngleLoc));
1594
1595 return SemaRef.SubstTemplateName(
1596 Param->getDefaultArgument().getArgument().getAsTemplate(),
1597 Param->getDefaultArgument().getTemplateNameLoc(),
1598 AllTemplateArgs);
1599}
1600
Douglas Gregord32e0282009-02-09 23:23:08 +00001601/// \brief Check that the given template argument list is well-formed
1602/// for specializing the given template.
1603bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1604 SourceLocation TemplateLoc,
1605 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001606 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001607 unsigned NumTemplateArgs,
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001608 SourceLocation RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001609 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001610 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001611 TemplateParameterList *Params = Template->getTemplateParameters();
1612 unsigned NumParams = Params->size();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001613 unsigned NumArgs = NumTemplateArgs;
Douglas Gregord32e0282009-02-09 23:23:08 +00001614 bool Invalid = false;
1615
Mike Stump11289f42009-09-09 15:08:12 +00001616 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001617 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001618
Anders Carlsson15201f12009-06-13 02:08:00 +00001619 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001620 (NumArgs < Params->getMinRequiredArguments() &&
1621 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001622 // FIXME: point at either the first arg beyond what we can handle,
1623 // or the '>', depending on whether we have too many or too few
1624 // arguments.
1625 SourceRange Range;
1626 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001627 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001628 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1629 << (NumArgs > NumParams)
1630 << (isa<ClassTemplateDecl>(Template)? 0 :
1631 isa<FunctionTemplateDecl>(Template)? 1 :
1632 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1633 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001634 Diag(Template->getLocation(), diag::note_template_decl_here)
1635 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001636 Invalid = true;
1637 }
Mike Stump11289f42009-09-09 15:08:12 +00001638
1639 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001640 // [...] The type and form of each template-argument specified in
1641 // a template-id shall match the type and form specified for the
1642 // corresponding parameter declared by the template in its
1643 // template-parameter-list.
1644 unsigned ArgIdx = 0;
1645 for (TemplateParameterList::iterator Param = Params->begin(),
1646 ParamEnd = Params->end();
1647 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001648 if (ArgIdx > NumArgs && PartialTemplateArgs)
1649 break;
Mike Stump11289f42009-09-09 15:08:12 +00001650
Douglas Gregord32e0282009-02-09 23:23:08 +00001651 // Decode the template argument
John McCall0ad16662009-10-29 08:12:44 +00001652 TemplateArgumentLoc Arg;
1653
Douglas Gregord32e0282009-02-09 23:23:08 +00001654 if (ArgIdx >= NumArgs) {
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001655 // Retrieve the default template argument from the template
1656 // parameter.
1657 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001658 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001659 // We have an empty argument pack.
1660 Converted.BeginPack();
1661 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001662 break;
1663 }
Mike Stump11289f42009-09-09 15:08:12 +00001664
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001665 if (!TTP->hasDefaultArgument())
1666 break;
1667
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001668 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
1669 Template,
1670 TemplateLoc,
1671 RAngleLoc,
1672 TTP,
1673 Converted);
John McCall0ad16662009-10-29 08:12:44 +00001674 if (!ArgType)
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001675 return true;
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001676
1677 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
1678 ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001679 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001680 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1681 if (!NTTP->hasDefaultArgument())
1682 break;
1683
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001684 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
1685 TemplateLoc,
1686 RAngleLoc,
1687 NTTP,
1688 Converted);
Anders Carlsson40ed3442009-06-11 16:06:49 +00001689 if (E.isInvalid())
1690 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001691
John McCall0ad16662009-10-29 08:12:44 +00001692 Expr *Ex = E.takeAs<Expr>();
1693 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001694 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001695 TemplateTemplateParmDecl *TempParm
1696 = cast<TemplateTemplateParmDecl>(*Param);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001697
1698 if (!TempParm->hasDefaultArgument())
1699 break;
1700
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001701 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
1702 TemplateLoc,
1703 RAngleLoc,
1704 TempParm,
1705 Converted);
1706 if (Name.isNull())
1707 return true;
1708
1709 Arg = TemplateArgumentLoc(TemplateArgument(Name),
1710 TempParm->getDefaultArgument().getTemplateQualifierRange(),
1711 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001712 }
1713 } else {
1714 // Retrieve the template argument produced by the user.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001715 Arg = TemplateArgs[ArgIdx];
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001716 }
1717
Douglas Gregord32e0282009-02-09 23:23:08 +00001718
1719 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001720 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001721 Converted.BeginPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001722 // Check all the remaining arguments (if any).
1723 for (; ArgIdx < NumArgs; ++ArgIdx) {
1724 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1725 Invalid = true;
1726 }
Mike Stump11289f42009-09-09 15:08:12 +00001727
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001728 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001729 } else {
1730 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1731 Invalid = true;
1732 }
Mike Stump11289f42009-09-09 15:08:12 +00001733 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord32e0282009-02-09 23:23:08 +00001734 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1735 // Check non-type template parameters.
Douglas Gregor463421d2009-03-03 04:44:36 +00001736
John McCall76d824f2009-08-25 22:02:44 +00001737 // Do substitution on the type of the non-type template parameter
1738 // with the template arguments we've seen thus far.
Douglas Gregor463421d2009-03-03 04:44:36 +00001739 QualType NTTPType = NTTP->getType();
1740 if (NTTPType->isDependentType()) {
John McCall76d824f2009-08-25 22:02:44 +00001741 // Do substitution on the type of the non-type template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001742 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001743 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001744 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001745 SourceRange(TemplateLoc, RAngleLoc));
1746
Anders Carlssonc8e71132009-06-05 04:47:51 +00001747 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001748 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001749 NTTPType = SubstType(NTTPType,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00001750 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001751 NTTP->getLocation(),
1752 NTTP->getDeclName());
Douglas Gregor463421d2009-03-03 04:44:36 +00001753 // If that worked, check the non-type template parameter type
1754 // for validity.
1755 if (!NTTPType.isNull())
Mike Stump11289f42009-09-09 15:08:12 +00001756 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
Douglas Gregor463421d2009-03-03 04:44:36 +00001757 NTTP->getLocation());
Douglas Gregor463421d2009-03-03 04:44:36 +00001758 if (NTTPType.isNull()) {
1759 Invalid = true;
1760 break;
1761 }
1762 }
1763
John McCall0ad16662009-10-29 08:12:44 +00001764 switch (Arg.getArgument().getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001765 case TemplateArgument::Null:
1766 assert(false && "Should never see a NULL template argument here");
1767 break;
Mike Stump11289f42009-09-09 15:08:12 +00001768
Douglas Gregorc40290e2009-03-09 23:48:35 +00001769 case TemplateArgument::Expression: {
John McCall0ad16662009-10-29 08:12:44 +00001770 Expr *E = Arg.getArgument().getAsExpr();
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001771 TemplateArgument Result;
1772 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregord32e0282009-02-09 23:23:08 +00001773 Invalid = true;
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001774 else
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001775 Converted.Append(Result);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001776 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001777 }
1778
Douglas Gregorc40290e2009-03-09 23:48:35 +00001779 case TemplateArgument::Declaration:
1780 case TemplateArgument::Integral:
1781 // We've already checked this template argument, so just copy
1782 // it to the list of converted arguments.
John McCall0ad16662009-10-29 08:12:44 +00001783 Converted.Append(Arg.getArgument());
Douglas Gregorc40290e2009-03-09 23:48:35 +00001784 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001785
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001786 case TemplateArgument::Template:
1787 // We were given a template template argument. It may not be ill-formed;
1788 // see below.
1789 if (DependentTemplateName *DTN
1790 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1791 // We have a template argument such as \c T::template X, which we
1792 // parsed as a template template argument. However, since we now
1793 // know that we need a non-type template argument, convert this
1794 // template name into an expression.
1795 Expr *E = new (Context) UnresolvedDeclRefExpr(DTN->getIdentifier(),
1796 Context.DependentTy,
1797 Arg.getTemplateNameLoc(),
1798 Arg.getTemplateQualifierRange(),
1799 DTN->getQualifier(),
1800 /*isAddressOfOperand=*/false);
1801
1802 TemplateArgument Result;
1803 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1804 Invalid = true;
1805 else
1806 Converted.Append(Result);
1807
1808 break;
1809 }
1810
1811 // We have a template argument that actually does refer to a class
1812 // template, template alias, or template template parameter, and
1813 // therefore cannot be a non-type template argument.
1814 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1815 << Arg.getSourceRange();
1816
1817 Diag((*Param)->getLocation(), diag::note_template_param_here);
1818 Invalid = true;
1819 break;
1820
John McCall0ad16662009-10-29 08:12:44 +00001821 case TemplateArgument::Type: {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001822 // We have a non-type template parameter but the template
1823 // argument is a type.
Mike Stump11289f42009-09-09 15:08:12 +00001824
Douglas Gregorc40290e2009-03-09 23:48:35 +00001825 // C++ [temp.arg]p2:
1826 // In a template-argument, an ambiguity between a type-id and
1827 // an expression is resolved to a type-id, regardless of the
1828 // form of the corresponding template-parameter.
1829 //
1830 // We warn specifically about this case, since it can be rather
1831 // confusing for users.
John McCall0ad16662009-10-29 08:12:44 +00001832 QualType T = Arg.getArgument().getAsType();
John McCall0d07eb32009-10-29 18:45:58 +00001833 SourceRange SR = Arg.getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00001834 if (T->isFunctionType())
John McCall0d07eb32009-10-29 18:45:58 +00001835 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig)
1836 << SR << T;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001837 else
John McCall0d07eb32009-10-29 18:45:58 +00001838 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001839 Diag((*Param)->getLocation(), diag::note_template_param_here);
1840 Invalid = true;
Anders Carlssonbc343912009-06-15 17:04:53 +00001841 break;
John McCall0ad16662009-10-29 08:12:44 +00001842 }
Mike Stump11289f42009-09-09 15:08:12 +00001843
Anders Carlssonbc343912009-06-15 17:04:53 +00001844 case TemplateArgument::Pack:
1845 assert(0 && "FIXME: Implement!");
1846 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001847 }
Mike Stump11289f42009-09-09 15:08:12 +00001848 } else {
Douglas Gregord32e0282009-02-09 23:23:08 +00001849 // Check template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001850 TemplateTemplateParmDecl *TempParm
Douglas Gregord32e0282009-02-09 23:23:08 +00001851 = cast<TemplateTemplateParmDecl>(*Param);
Mike Stump11289f42009-09-09 15:08:12 +00001852
John McCall0ad16662009-10-29 08:12:44 +00001853 switch (Arg.getArgument().getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001854 case TemplateArgument::Null:
1855 assert(false && "Should never see a NULL template argument here");
1856 break;
Mike Stump11289f42009-09-09 15:08:12 +00001857
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001858 case TemplateArgument::Template:
1859 if (CheckTemplateArgument(TempParm, Arg))
1860 Invalid = true;
1861 else
1862 Converted.Append(Arg.getArgument());
1863 break;
1864
1865 case TemplateArgument::Expression:
1866 case TemplateArgument::Type:
Douglas Gregorc40290e2009-03-09 23:48:35 +00001867 // We have a template template parameter but the template
1868 // argument does not refer to a template.
1869 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1870 Invalid = true;
1871 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001872
Douglas Gregorc40290e2009-03-09 23:48:35 +00001873 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001874 llvm::llvm_unreachable(
1875 "Declaration argument with template template parameter");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001876 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001877 case TemplateArgument::Integral:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001878 llvm::llvm_unreachable(
1879 "Integral argument with template template parameter");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001880 break;
Mike Stump11289f42009-09-09 15:08:12 +00001881
Anders Carlssonbc343912009-06-15 17:04:53 +00001882 case TemplateArgument::Pack:
1883 assert(0 && "FIXME: Implement!");
1884 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001885 }
Douglas Gregord32e0282009-02-09 23:23:08 +00001886 }
1887 }
1888
1889 return Invalid;
1890}
1891
1892/// \brief Check a template argument against its corresponding
1893/// template type parameter.
1894///
1895/// This routine implements the semantics of C++ [temp.arg.type]. It
1896/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001897bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001898 DeclaratorInfo *ArgInfo) {
1899 assert(ArgInfo && "invalid DeclaratorInfo");
1900 QualType Arg = ArgInfo->getType();
1901
Douglas Gregord32e0282009-02-09 23:23:08 +00001902 // C++ [temp.arg.type]p2:
1903 // A local type, a type with no linkage, an unnamed type or a type
1904 // compounded from any of these types shall not be used as a
1905 // template-argument for a template type-parameter.
1906 //
1907 // FIXME: Perform the recursive and no-linkage type checks.
1908 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001909 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001910 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001911 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001912 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00001913 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
1914 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1915 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
1916 << QualType(Tag, 0) << SR;
1917 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001918 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00001919 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1920 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00001921 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1922 return true;
1923 }
1924
1925 return false;
1926}
1927
Douglas Gregorccb07762009-02-11 19:52:55 +00001928/// \brief Checks whether the given template argument is the address
1929/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001930bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1931 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001932 bool Invalid = false;
1933
1934 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00001935 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00001936 Arg = Cast->getSubExpr();
1937
Sebastian Redl576fd422009-05-10 18:38:11 +00001938 // C++0x allows nullptr, and there's no further checking to be done for that.
1939 if (Arg->getType()->isNullPtrType())
1940 return false;
1941
Douglas Gregorccb07762009-02-11 19:52:55 +00001942 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001943 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001944 // A template-argument for a non-type, non-template
1945 // template-parameter shall be one of: [...]
1946 //
1947 // -- the address of an object or function with external
1948 // linkage, including function templates and function
1949 // template-ids but excluding non-static class members,
1950 // expressed as & id-expression where the & is optional if
1951 // the name refers to a function or array, or if the
1952 // corresponding template-parameter is a reference; or
1953 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001954
Douglas Gregorccb07762009-02-11 19:52:55 +00001955 // Ignore (and complain about) any excess parentheses.
1956 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1957 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001958 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001959 diag::err_template_arg_extra_parens)
1960 << Arg->getSourceRange();
1961 Invalid = true;
1962 }
1963
1964 Arg = Parens->getSubExpr();
1965 }
1966
1967 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1968 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1969 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1970 } else
1971 DRE = dyn_cast<DeclRefExpr>(Arg);
1972
1973 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00001974 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001975 diag::err_template_arg_not_object_or_func_form)
1976 << Arg->getSourceRange();
1977
1978 // Cannot refer to non-static data members
1979 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1980 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1981 << Field << Arg->getSourceRange();
1982
1983 // Cannot refer to non-static member functions
1984 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1985 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00001986 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001987 diag::err_template_arg_method)
1988 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001989
Douglas Gregorccb07762009-02-11 19:52:55 +00001990 // Functions must have external linkage.
1991 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1992 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00001993 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001994 diag::err_template_arg_function_not_extern)
1995 << Func << Arg->getSourceRange();
1996 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1997 << true;
1998 return true;
1999 }
2000
2001 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002002 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002003 return Invalid;
2004 }
2005
2006 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2007 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00002008 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002009 diag::err_template_arg_object_not_extern)
2010 << Var << Arg->getSourceRange();
2011 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2012 << true;
2013 return true;
2014 }
2015
2016 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002017 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002018 return Invalid;
2019 }
Mike Stump11289f42009-09-09 15:08:12 +00002020
Douglas Gregorccb07762009-02-11 19:52:55 +00002021 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002022 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002023 diag::err_template_arg_not_object_or_func)
2024 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002025 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002026 diag::note_template_arg_refers_here);
2027 return true;
2028}
2029
2030/// \brief Checks whether the given template argument is a pointer to
2031/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump11289f42009-09-09 15:08:12 +00002032bool
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002033Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002034 bool Invalid = false;
2035
2036 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002037 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002038 Arg = Cast->getSubExpr();
2039
Sebastian Redl576fd422009-05-10 18:38:11 +00002040 // C++0x allows nullptr, and there's no further checking to be done for that.
2041 if (Arg->getType()->isNullPtrType())
2042 return false;
2043
Douglas Gregorccb07762009-02-11 19:52:55 +00002044 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002045 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002046 // A template-argument for a non-type, non-template
2047 // template-parameter shall be one of: [...]
2048 //
2049 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002050 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002051
2052 // Ignore (and complain about) any excess parentheses.
2053 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2054 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002055 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002056 diag::err_template_arg_extra_parens)
2057 << Arg->getSourceRange();
2058 Invalid = true;
2059 }
2060
2061 Arg = Parens->getSubExpr();
2062 }
2063
2064 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002065 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2066 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2067 if (DRE && !DRE->getQualifier())
2068 DRE = 0;
2069 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002070
2071 if (!DRE)
2072 return Diag(Arg->getSourceRange().getBegin(),
2073 diag::err_template_arg_not_pointer_to_member_form)
2074 << Arg->getSourceRange();
2075
2076 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2077 assert((isa<FieldDecl>(DRE->getDecl()) ||
2078 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2079 "Only non-static member pointers can make it here");
2080
2081 // Okay: this is the address of a non-static member, and therefore
2082 // a member pointer constant.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002083 Member = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00002084 return Invalid;
2085 }
2086
2087 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002088 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002089 diag::err_template_arg_not_pointer_to_member_form)
2090 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002091 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002092 diag::note_template_arg_refers_here);
2093 return true;
2094}
2095
Douglas Gregord32e0282009-02-09 23:23:08 +00002096/// \brief Check a template argument against its corresponding
2097/// non-type template parameter.
2098///
Douglas Gregor463421d2009-03-03 04:44:36 +00002099/// This routine implements the semantics of C++ [temp.arg.nontype].
2100/// It returns true if an error occurred, and false otherwise. \p
2101/// InstantiatedParamType is the type of the non-type template
2102/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002103///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002104/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002105bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002106 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002107 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002108 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2109
Douglas Gregor86560402009-02-10 23:36:10 +00002110 // If either the parameter has a dependent type or the argument is
2111 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002112 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002113 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2114 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002115 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002116 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002117 }
Douglas Gregor86560402009-02-10 23:36:10 +00002118
2119 // C++ [temp.arg.nontype]p5:
2120 // The following conversions are performed on each expression used
2121 // as a non-type template-argument. If a non-type
2122 // template-argument cannot be converted to the type of the
2123 // corresponding template-parameter then the program is
2124 // ill-formed.
2125 //
2126 // -- for a non-type template-parameter of integral or
2127 // enumeration type, integral promotions (4.5) and integral
2128 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002129 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002130 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002131 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002132 // C++ [temp.arg.nontype]p1:
2133 // A template-argument for a non-type, non-template
2134 // template-parameter shall be one of:
2135 //
2136 // -- an integral constant-expression of integral or enumeration
2137 // type; or
2138 // -- the name of a non-type template-parameter; or
2139 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002140 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002141 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002142 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002143 diag::err_template_arg_not_integral_or_enumeral)
2144 << ArgType << Arg->getSourceRange();
2145 Diag(Param->getLocation(), diag::note_template_param_here);
2146 return true;
2147 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002148 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002149 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2150 << ArgType << Arg->getSourceRange();
2151 return true;
2152 }
2153
2154 // FIXME: We need some way to more easily get the unqualified form
2155 // of the types without going all the way to the
2156 // canonical type.
2157 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2158 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2159 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2160 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2161
2162 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002163 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002164 // Okay: no conversion necessary
2165 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2166 !ParamType->isEnumeralType()) {
2167 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002168 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002169 } else {
2170 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002171 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002172 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002173 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002174 Diag(Param->getLocation(), diag::note_template_param_here);
2175 return true;
2176 }
2177
Douglas Gregor52aba872009-03-14 00:20:21 +00002178 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002179 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002180 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002181
2182 if (!Arg->isValueDependent()) {
2183 // Check that an unsigned parameter does not receive a negative
2184 // value.
2185 if (IntegerType->isUnsignedIntegerType()
2186 && (Value.isSigned() && Value.isNegative())) {
2187 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2188 << Value.toString(10) << Param->getType()
2189 << Arg->getSourceRange();
2190 Diag(Param->getLocation(), diag::note_template_param_here);
2191 return true;
2192 }
2193
2194 // Check that we don't overflow the template parameter type.
2195 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2196 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002197 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002198 diag::err_template_arg_too_large)
2199 << Value.toString(10) << Param->getType()
2200 << Arg->getSourceRange();
2201 Diag(Param->getLocation(), diag::note_template_param_here);
2202 return true;
2203 }
2204
2205 if (Value.getBitWidth() != AllowedBits)
2206 Value.extOrTrunc(AllowedBits);
2207 Value.setIsSigned(IntegerType->isSignedIntegerType());
2208 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002209
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002210 // Add the value of this argument to the list of converted
2211 // arguments. We use the bitwidth and signedness of the template
2212 // parameter.
2213 if (Arg->isValueDependent()) {
2214 // The argument is value-dependent. Create a new
2215 // TemplateArgument with the converted expression.
2216 Converted = TemplateArgument(Arg);
2217 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002218 }
2219
John McCall0ad16662009-10-29 08:12:44 +00002220 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002221 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002222 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002223 return false;
2224 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002225
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002226 // Handle pointer-to-function, reference-to-function, and
2227 // pointer-to-member-function all in (roughly) the same way.
2228 if (// -- For a non-type template-parameter of type pointer to
2229 // function, only the function-to-pointer conversion (4.3) is
2230 // applied. If the template-argument represents a set of
2231 // overloaded functions (or a pointer to such), the matching
2232 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002233 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002234 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002235 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002236 // -- For a non-type template-parameter of type reference to
2237 // function, no conversions apply. If the template-argument
2238 // represents a set of overloaded functions, the matching
2239 // function is selected from the set (13.4).
2240 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002241 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002242 // -- For a non-type template-parameter of type pointer to
2243 // member function, no conversions apply. If the
2244 // template-argument represents a set of overloaded member
2245 // functions, the matching member function is selected from
2246 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002247 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002248 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002249 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002250 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002251 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002252 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002253 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002254 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2255 ParamType->isMemberPointerType())) {
2256 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002257 if (ParamType->isMemberPointerType())
2258 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2259 else
2260 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002261 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002262 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002263 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002264 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002265 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002266 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2267 return true;
2268
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002269 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002270 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002271 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002272 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002273 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002274 }
2275 }
2276
Mike Stump11289f42009-09-09 15:08:12 +00002277 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002278 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002279 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002280 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002281 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002282 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002283 Diag(Param->getLocation(), diag::note_template_param_here);
2284 return true;
2285 }
Mike Stump11289f42009-09-09 15:08:12 +00002286
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002287 if (ParamType->isMemberPointerType()) {
2288 NamedDecl *Member = 0;
2289 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2290 return true;
2291
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002292 if (Member)
2293 Member = cast<NamedDecl>(Member->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002294 Converted = TemplateArgument(Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002295 return false;
2296 }
Mike Stump11289f42009-09-09 15:08:12 +00002297
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002298 NamedDecl *Entity = 0;
2299 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2300 return true;
2301
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002302 if (Entity)
2303 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002304 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002305 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002306 }
2307
Chris Lattner696197c2009-02-20 21:37:53 +00002308 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002309 // -- for a non-type template-parameter of type pointer to
2310 // object, qualification conversions (4.4) and the
2311 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002312 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002313 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002314 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002315
Sebastian Redl576fd422009-05-10 18:38:11 +00002316 if (ArgType->isNullPtrType()) {
2317 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002318 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002319 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002320 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002321 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002322 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002323
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002324 if (IsQualificationConversion(ArgType, ParamType)) {
2325 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002326 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002327 }
Mike Stump11289f42009-09-09 15:08:12 +00002328
Douglas Gregor1515f762009-02-11 18:22:40 +00002329 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002330 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002331 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002332 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002333 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002334 Diag(Param->getLocation(), diag::note_template_param_here);
2335 return true;
2336 }
Mike Stump11289f42009-09-09 15:08:12 +00002337
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002338 NamedDecl *Entity = 0;
2339 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2340 return true;
2341
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002342 if (Entity)
2343 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002344 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002345 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002346 }
Mike Stump11289f42009-09-09 15:08:12 +00002347
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002348 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002349 // -- For a non-type template-parameter of type reference to
2350 // object, no conversions apply. The type referred to by the
2351 // reference may be more cv-qualified than the (otherwise
2352 // identical) type of the template-argument. The
2353 // template-parameter is bound directly to the
2354 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002355 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002356 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002357
Douglas Gregor1515f762009-02-11 18:22:40 +00002358 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002359 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002360 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002361 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002362 << Arg->getSourceRange();
2363 Diag(Param->getLocation(), diag::note_template_param_here);
2364 return true;
2365 }
2366
Mike Stump11289f42009-09-09 15:08:12 +00002367 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002368 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2369 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002370
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002371 if ((ParamQuals | ArgQuals) != ParamQuals) {
2372 Diag(Arg->getSourceRange().getBegin(),
2373 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002374 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002375 << Arg->getSourceRange();
2376 Diag(Param->getLocation(), diag::note_template_param_here);
2377 return true;
2378 }
Mike Stump11289f42009-09-09 15:08:12 +00002379
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002380 NamedDecl *Entity = 0;
2381 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2382 return true;
2383
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002384 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002385 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002386 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002387 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002388
2389 // -- For a non-type template-parameter of type pointer to data
2390 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002391 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002392 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2393
Douglas Gregor1515f762009-02-11 18:22:40 +00002394 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002395 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002396 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002397 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002398 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002399 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002400 } else {
2401 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002402 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002403 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002404 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002405 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002406 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002407 }
2408
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002409 NamedDecl *Member = 0;
2410 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2411 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002412
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002413 if (Member)
2414 Member = cast<NamedDecl>(Member->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002415 Converted = TemplateArgument(Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002416 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00002417}
2418
2419/// \brief Check a template argument against its corresponding
2420/// template template parameter.
2421///
2422/// This routine implements the semantics of C++ [temp.arg.template].
2423/// It returns true if an error occurred, and false otherwise.
2424bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002425 const TemplateArgumentLoc &Arg) {
2426 TemplateName Name = Arg.getArgument().getAsTemplate();
2427 TemplateDecl *Template = Name.getAsTemplateDecl();
2428 if (!Template) {
2429 // Any dependent template name is fine.
2430 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2431 return false;
2432 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002433
2434 // C++ [temp.arg.template]p1:
2435 // A template-argument for a template template-parameter shall be
2436 // the name of a class template, expressed as id-expression. Only
2437 // primary class templates are considered when matching the
2438 // template template argument with the corresponding parameter;
2439 // partial specializations are not considered even if their
2440 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002441 //
2442 // Note that we also allow template template parameters here, which
2443 // will happen when we are dealing with, e.g., class template
2444 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002445 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002446 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002447 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002448 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002449 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002450 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002451 << Template;
2452 }
2453
2454 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2455 Param->getTemplateParameters(),
2456 true, true,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002457 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002458}
2459
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002460/// \brief Determine whether the given template parameter lists are
2461/// equivalent.
2462///
Mike Stump11289f42009-09-09 15:08:12 +00002463/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002464/// source code as part of a new template declaration.
2465///
2466/// \param Old The old template parameter list, typically found via
2467/// name lookup of the template declared with this template parameter
2468/// list.
2469///
2470/// \param Complain If true, this routine will produce a diagnostic if
2471/// the template parameter lists are not equivalent.
2472///
Douglas Gregor85e0f662009-02-10 00:24:35 +00002473/// \param IsTemplateTemplateParm If true, this routine is being
2474/// called to compare the template parameter lists of a template
2475/// template parameter.
2476///
2477/// \param TemplateArgLoc If this source location is valid, then we
2478/// are actually checking the template parameter list of a template
2479/// argument (New) against the template parameter list of its
2480/// corresponding template template parameter (Old). We produce
2481/// slightly different diagnostics in this scenario.
2482///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002483/// \returns True if the template parameter lists are equal, false
2484/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002485bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002486Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2487 TemplateParameterList *Old,
2488 bool Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002489 bool IsTemplateTemplateParm,
2490 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002491 if (Old->size() != New->size()) {
2492 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002493 unsigned NextDiag = diag::err_template_param_list_different_arity;
2494 if (TemplateArgLoc.isValid()) {
2495 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2496 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002497 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002498 Diag(New->getTemplateLoc(), NextDiag)
2499 << (New->size() > Old->size())
2500 << IsTemplateTemplateParm
2501 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002502 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2503 << IsTemplateTemplateParm
2504 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2505 }
2506
2507 return false;
2508 }
2509
2510 for (TemplateParameterList::iterator OldParm = Old->begin(),
2511 OldParmEnd = Old->end(), NewParm = New->begin();
2512 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2513 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002514 if (Complain) {
2515 unsigned NextDiag = diag::err_template_param_different_kind;
2516 if (TemplateArgLoc.isValid()) {
2517 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2518 NextDiag = diag::note_template_param_different_kind;
2519 }
2520 Diag((*NewParm)->getLocation(), NextDiag)
2521 << IsTemplateTemplateParm;
2522 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2523 << IsTemplateTemplateParm;
Douglas Gregor85e0f662009-02-10 00:24:35 +00002524 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002525 return false;
2526 }
2527
2528 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2529 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002530 // know we're at the same index).
2531#if 0
Mike Stump87c57ac2009-05-16 07:39:55 +00002532 // FIXME: Enable this code in debug mode *after* we properly go through
2533 // and "instantiate" the template parameter lists of template template
2534 // parameters. It's only after this instantiation that (1) any dependent
2535 // types within the template parameter list of the template template
2536 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregor85e0f662009-02-10 00:24:35 +00002537 // will match up.
Mike Stump11289f42009-09-09 15:08:12 +00002538 QualType OldParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002539 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
Mike Stump11289f42009-09-09 15:08:12 +00002540 QualType NewParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002541 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
Mike Stump11289f42009-09-09 15:08:12 +00002542 assert(Context.getCanonicalType(OldParmType) ==
2543 Context.getCanonicalType(NewParmType) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002544 "type parameter mismatch?");
2545#endif
Mike Stump11289f42009-09-09 15:08:12 +00002546 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002547 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2548 // The types of non-type template parameters must agree.
2549 NonTypeTemplateParmDecl *NewNTTP
2550 = cast<NonTypeTemplateParmDecl>(*NewParm);
2551 if (Context.getCanonicalType(OldNTTP->getType()) !=
2552 Context.getCanonicalType(NewNTTP->getType())) {
2553 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002554 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2555 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002556 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002557 diag::err_template_arg_template_params_mismatch);
2558 NextDiag = diag::note_template_nontype_parm_different_type;
2559 }
2560 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002561 << NewNTTP->getType()
2562 << IsTemplateTemplateParm;
Mike Stump11289f42009-09-09 15:08:12 +00002563 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002564 diag::note_template_nontype_parm_prev_declaration)
2565 << OldNTTP->getType();
2566 }
2567 return false;
2568 }
2569 } else {
2570 // The template parameter lists of template template
2571 // parameters must agree.
2572 // FIXME: Could we perform a faster "type" comparison here?
Mike Stump11289f42009-09-09 15:08:12 +00002573 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002574 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002575 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002576 = cast<TemplateTemplateParmDecl>(*OldParm);
2577 TemplateTemplateParmDecl *NewTTP
2578 = cast<TemplateTemplateParmDecl>(*NewParm);
2579 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2580 OldTTP->getTemplateParameters(),
2581 Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002582 /*IsTemplateTemplateParm=*/true,
2583 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002584 return false;
2585 }
2586 }
2587
2588 return true;
2589}
2590
2591/// \brief Check whether a template can be declared within this scope.
2592///
2593/// If the template declaration is valid in this scope, returns
2594/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002595bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002596Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002597 // Find the nearest enclosing declaration scope.
2598 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2599 (S->getFlags() & Scope::TemplateParamScope) != 0)
2600 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002601
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002602 // C++ [temp]p2:
2603 // A template-declaration can appear only as a namespace scope or
2604 // class scope declaration.
2605 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002606 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2607 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002608 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002609 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002610
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002611 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002612 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002613
2614 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2615 return false;
2616
Mike Stump11289f42009-09-09 15:08:12 +00002617 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002618 diag::err_template_outside_namespace_or_class_scope)
2619 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002620}
Douglas Gregor67a65642009-02-17 23:15:12 +00002621
Douglas Gregor54888652009-10-07 00:13:32 +00002622/// \brief Determine what kind of template specialization the given declaration
2623/// is.
2624static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2625 if (!D)
2626 return TSK_Undeclared;
2627
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002628 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2629 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002630 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2631 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002632 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2633 return Var->getTemplateSpecializationKind();
2634
Douglas Gregor54888652009-10-07 00:13:32 +00002635 return TSK_Undeclared;
2636}
2637
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002638/// \brief Check whether a specialization is well-formed in the current
2639/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002640///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002641/// This routine determines whether a template specialization can be declared
2642/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002643///
2644/// \param S the semantic analysis object for which this check is being
2645/// performed.
2646///
2647/// \param Specialized the entity being specialized or instantiated, which
2648/// may be a kind of template (class template, function template, etc.) or
2649/// a member of a class template (member function, static data member,
2650/// member class).
2651///
2652/// \param PrevDecl the previous declaration of this entity, if any.
2653///
2654/// \param Loc the location of the explicit specialization or instantiation of
2655/// this entity.
2656///
2657/// \param IsPartialSpecialization whether this is a partial specialization of
2658/// a class template.
2659///
Douglas Gregor54888652009-10-07 00:13:32 +00002660/// \returns true if there was an error that we cannot recover from, false
2661/// otherwise.
2662static bool CheckTemplateSpecializationScope(Sema &S,
2663 NamedDecl *Specialized,
2664 NamedDecl *PrevDecl,
2665 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002666 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002667 // Keep these "kind" numbers in sync with the %select statements in the
2668 // various diagnostics emitted by this routine.
2669 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002670 bool isTemplateSpecialization = false;
2671 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002672 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002673 isTemplateSpecialization = true;
2674 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002675 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002676 isTemplateSpecialization = true;
2677 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002678 EntityKind = 3;
2679 else if (isa<VarDecl>(Specialized))
2680 EntityKind = 4;
2681 else if (isa<RecordDecl>(Specialized))
2682 EntityKind = 5;
2683 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002684 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2685 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00002686 return true;
2687 }
2688
Douglas Gregorf47b9112009-02-25 22:02:03 +00002689 // C++ [temp.expl.spec]p2:
2690 // An explicit specialization shall be declared in the namespace
2691 // of which the template is a member, or, for member templates, in
2692 // the namespace of which the enclosing class or enclosing class
2693 // template is a member. An explicit specialization of a member
2694 // function, member class or static data member of a class
2695 // template shall be declared in the namespace of which the class
2696 // template is a member. Such a declaration may also be a
2697 // definition. If the declaration is not a definition, the
2698 // specialization may be defined later in the name- space in which
2699 // the explicit specialization was declared, or in a namespace
2700 // that encloses the one in which the explicit specialization was
2701 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002702 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2703 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002704 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002705 return true;
2706 }
Douglas Gregore4b05162009-10-07 17:21:34 +00002707
Douglas Gregor40fb7442009-10-07 17:30:37 +00002708 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2709 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002710 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00002711 return true;
2712 }
2713
Douglas Gregore4b05162009-10-07 17:21:34 +00002714 // C++ [temp.class.spec]p6:
2715 // A class template partial specialization may be declared or redeclared
2716 // in any namespace scope in which its definition may be defined (14.5.1
2717 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002718 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002719 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002720 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002721 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002722 if ((!PrevDecl ||
2723 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2724 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2725 // There is no prior declaration of this entity, so this
2726 // specialization must be in the same context as the template
2727 // itself.
2728 if (!DC->Equals(SpecializedContext)) {
2729 if (isa<TranslationUnitDecl>(SpecializedContext))
2730 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2731 << EntityKind << Specialized;
2732 else if (isa<NamespaceDecl>(SpecializedContext))
2733 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2734 << EntityKind << Specialized
2735 << cast<NamedDecl>(SpecializedContext);
2736
2737 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2738 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002739 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002740 }
Douglas Gregor54888652009-10-07 00:13:32 +00002741
2742 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002743 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00002744 // Note that HandleDeclarator() performs this check for explicit
2745 // specializations of function templates, static data members, and member
2746 // functions, so we skip the check here for those kinds of entities.
2747 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00002748 // Should we refactor that check, so that it occurs later?
2749 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002750 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2751 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00002752 if (isa<TranslationUnitDecl>(SpecializedContext))
2753 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2754 << EntityKind << Specialized;
2755 else if (isa<NamespaceDecl>(SpecializedContext))
2756 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2757 << EntityKind << Specialized
2758 << cast<NamedDecl>(SpecializedContext);
2759
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002760 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002761 }
Douglas Gregor54888652009-10-07 00:13:32 +00002762
2763 // FIXME: check for specialization-after-instantiation errors and such.
2764
Douglas Gregorf47b9112009-02-25 22:02:03 +00002765 return false;
2766}
Douglas Gregor54888652009-10-07 00:13:32 +00002767
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002768/// \brief Check the non-type template arguments of a class template
2769/// partial specialization according to C++ [temp.class.spec]p9.
2770///
Douglas Gregor09a30232009-06-12 22:08:06 +00002771/// \param TemplateParams the template parameters of the primary class
2772/// template.
2773///
2774/// \param TemplateArg the template arguments of the class template
2775/// partial specialization.
2776///
2777/// \param MirrorsPrimaryTemplate will be set true if the class
2778/// template partial specialization arguments are identical to the
2779/// implicit template arguments of the primary template. This is not
2780/// necessarily an error (C++0x), and it is left to the caller to diagnose
2781/// this condition when it is an error.
2782///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002783/// \returns true if there was an error, false otherwise.
2784bool Sema::CheckClassTemplatePartialSpecializationArgs(
2785 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002786 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002787 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002788 // FIXME: the interface to this function will have to change to
2789 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002790 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002791
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002792 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002793
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002794 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002795 // Determine whether the template argument list of the partial
2796 // specialization is identical to the implicit argument list of
2797 // the primary template. The caller may need to diagnostic this as
2798 // an error per C++ [temp.class.spec]p9b3.
2799 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002800 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002801 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2802 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002803 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002804 MirrorsPrimaryTemplate = false;
2805 } else if (TemplateTemplateParmDecl *TTP
2806 = dyn_cast<TemplateTemplateParmDecl>(
2807 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002808 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00002809 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002810 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002811 if (!ArgDecl ||
2812 ArgDecl->getIndex() != TTP->getIndex() ||
2813 ArgDecl->getDepth() != TTP->getDepth())
2814 MirrorsPrimaryTemplate = false;
2815 }
2816 }
2817
Mike Stump11289f42009-09-09 15:08:12 +00002818 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002819 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002820 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002821 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002822 }
2823
Anders Carlsson40c1d492009-06-13 18:20:51 +00002824 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002825 if (!ArgExpr) {
2826 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002827 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002828 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002829
2830 // C++ [temp.class.spec]p8:
2831 // A non-type argument is non-specialized if it is the name of a
2832 // non-type parameter. All other non-type arguments are
2833 // specialized.
2834 //
2835 // Below, we check the two conditions that only apply to
2836 // specialized non-type arguments, so skip any non-specialized
2837 // arguments.
2838 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002839 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002840 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002841 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002842 (Param->getIndex() != NTTP->getIndex() ||
2843 Param->getDepth() != NTTP->getDepth()))
2844 MirrorsPrimaryTemplate = false;
2845
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002846 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002847 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002848
2849 // C++ [temp.class.spec]p9:
2850 // Within the argument list of a class template partial
2851 // specialization, the following restrictions apply:
2852 // -- A partially specialized non-type argument expression
2853 // shall not involve a template parameter of the partial
2854 // specialization except when the argument expression is a
2855 // simple identifier.
2856 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002857 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002858 diag::err_dependent_non_type_arg_in_partial_spec)
2859 << ArgExpr->getSourceRange();
2860 return true;
2861 }
2862
2863 // -- The type of a template parameter corresponding to a
2864 // specialized non-type argument shall not be dependent on a
2865 // parameter of the specialization.
2866 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002867 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002868 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2869 << Param->getType()
2870 << ArgExpr->getSourceRange();
2871 Diag(Param->getLocation(), diag::note_template_param_here);
2872 return true;
2873 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002874
2875 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002876 }
2877
2878 return false;
2879}
2880
Douglas Gregorc08f4892009-03-25 00:13:59 +00002881Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002882Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2883 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002884 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002885 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002886 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002887 SourceLocation TemplateNameLoc,
2888 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002889 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002890 SourceLocation RAngleLoc,
2891 AttributeList *Attr,
2892 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00002893 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00002894
Douglas Gregor67a65642009-02-17 23:15:12 +00002895 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002896 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002897 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002898 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002899
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002900 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00002901 bool isPartialSpecialization = false;
2902
Douglas Gregorf47b9112009-02-25 22:02:03 +00002903 // Check the validity of the template headers that introduce this
2904 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00002905 // FIXME: We probably shouldn't complain about these headers for
2906 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002907 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002908 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2909 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002910 TemplateParameterLists.size(),
2911 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002912 if (TemplateParams && TemplateParams->size() > 0) {
2913 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002914
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002915 // C++ [temp.class.spec]p10:
2916 // The template parameter list of a specialization shall not
2917 // contain default template argument values.
2918 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2919 Decl *Param = TemplateParams->getParam(I);
2920 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2921 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002922 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002923 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00002924 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002925 }
2926 } else if (NonTypeTemplateParmDecl *NTTP
2927 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2928 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002929 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002930 diag::err_default_arg_in_partial_spec)
2931 << DefArg->getSourceRange();
2932 NTTP->setDefaultArgument(0);
2933 DefArg->Destroy(Context);
2934 }
2935 } else {
2936 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002937 if (TTP->hasDefaultArgument()) {
2938 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002939 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002940 << TTP->getDefaultArgument().getSourceRange();
2941 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00002942 }
2943 }
2944 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00002945 } else if (TemplateParams) {
2946 if (TUK == TUK_Friend)
2947 Diag(KWLoc, diag::err_template_spec_friend)
2948 << CodeModificationHint::CreateRemoval(
2949 SourceRange(TemplateParams->getTemplateLoc(),
2950 TemplateParams->getRAngleLoc()))
2951 << SourceRange(LAngleLoc, RAngleLoc);
2952 else
2953 isExplicitSpecialization = true;
2954 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002955 Diag(KWLoc, diag::err_template_spec_needs_header)
2956 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002957 isExplicitSpecialization = true;
2958 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002959
Douglas Gregor67a65642009-02-17 23:15:12 +00002960 // Check that the specialization uses the same tag kind as the
2961 // original template.
2962 TagDecl::TagKind Kind;
2963 switch (TagSpec) {
2964 default: assert(0 && "Unknown tag type!");
2965 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2966 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2967 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2968 }
Douglas Gregord9034f02009-05-14 16:41:31 +00002969 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00002970 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00002971 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00002972 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00002973 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00002974 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00002975 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00002976 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00002977 diag::note_previous_use);
2978 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2979 }
2980
Douglas Gregorc40290e2009-03-09 23:48:35 +00002981 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00002982 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002983 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002984
Douglas Gregor67a65642009-02-17 23:15:12 +00002985 // Check that the template argument list is well-formed for this
2986 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002987 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2988 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00002989 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002990 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00002991 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002992 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002993
Mike Stump11289f42009-09-09 15:08:12 +00002994 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00002995 ClassTemplate->getTemplateParameters()->size()) &&
2996 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00002997
Douglas Gregor2373c592009-05-31 09:31:02 +00002998 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00002999 // corresponds to these arguments.
3000 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003001 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003002 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003003 if (CheckClassTemplatePartialSpecializationArgs(
3004 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003005 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003006 return true;
3007
Douglas Gregor09a30232009-06-12 22:08:06 +00003008 if (MirrorsPrimaryTemplate) {
3009 // C++ [temp.class.spec]p9b3:
3010 //
Mike Stump11289f42009-09-09 15:08:12 +00003011 // -- The argument list of the specialization shall not be identical
3012 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003013 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003014 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003015 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003016 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003017 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003018 ClassTemplate->getIdentifier(),
3019 TemplateNameLoc,
3020 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003021 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003022 AS_none);
3023 }
3024
Douglas Gregor2208a292009-09-26 20:57:03 +00003025 // FIXME: Diagnose friend partial specializations
3026
Douglas Gregor2373c592009-05-31 09:31:02 +00003027 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00003028 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003029 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003030 Converted.flatSize(),
3031 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003032 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003033 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003034 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003035 Converted.flatSize(),
3036 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003037 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003038 ClassTemplateSpecializationDecl *PrevDecl = 0;
3039
3040 if (isPartialSpecialization)
3041 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003042 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003043 InsertPos);
3044 else
3045 PrevDecl
3046 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003047
3048 ClassTemplateSpecializationDecl *Specialization = 0;
3049
Douglas Gregorf47b9112009-02-25 22:02:03 +00003050 // Check whether we can declare a class template specialization in
3051 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003052 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003053 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003054 TemplateNameLoc,
3055 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003056 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003057
Douglas Gregor15301382009-07-30 17:40:51 +00003058 // The canonical type
3059 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003060 if (PrevDecl &&
3061 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3062 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003063 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003064 // arguments was referenced but not declared, or we're only
3065 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003066 // declaration node as our own, updating its source location to
3067 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003068 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003069 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003070 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003071 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003072 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003073 // Build the canonical type that describes the converted template
3074 // arguments of the class template partial specialization.
3075 CanonType = Context.getTemplateSpecializationType(
3076 TemplateName(ClassTemplate),
3077 Converted.getFlatArguments(),
3078 Converted.flatSize());
3079
Douglas Gregor2373c592009-05-31 09:31:02 +00003080 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003081 ClassTemplatePartialSpecializationDecl *PrevPartial
3082 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003083 ClassTemplatePartialSpecializationDecl *Partial
3084 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003085 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003086 TemplateNameLoc,
3087 TemplateParams,
3088 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003089 Converted,
John McCall0ad16662009-10-29 08:12:44 +00003090 TemplateArgs.data(),
3091 TemplateArgs.size(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003092 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003093
3094 if (PrevPartial) {
3095 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3096 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3097 } else {
3098 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3099 }
3100 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003101
Douglas Gregor21610382009-10-29 00:04:11 +00003102 // If we are providing an explicit specialization of a member class
3103 // template specialization, make a note of that.
3104 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3105 PrevPartial->setMemberSpecialization();
3106
Douglas Gregor91772d12009-06-13 00:26:55 +00003107 // Check that all of the template parameters of the class template
3108 // partial specialization are deducible from the template
3109 // arguments. If not, this class template partial specialization
3110 // will never be used.
3111 llvm::SmallVector<bool, 8> DeducibleParams;
3112 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003113 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003114 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003115 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003116 unsigned NumNonDeducible = 0;
3117 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3118 if (!DeducibleParams[I])
3119 ++NumNonDeducible;
3120
3121 if (NumNonDeducible) {
3122 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3123 << (NumNonDeducible > 1)
3124 << SourceRange(TemplateNameLoc, RAngleLoc);
3125 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3126 if (!DeducibleParams[I]) {
3127 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3128 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003129 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003130 diag::note_partial_spec_unused_parameter)
3131 << Param->getDeclName();
3132 else
Mike Stump11289f42009-09-09 15:08:12 +00003133 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003134 diag::note_partial_spec_unused_parameter)
3135 << std::string("<anonymous>");
3136 }
3137 }
3138 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003139 } else {
3140 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003141 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003142 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003143 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003144 ClassTemplate->getDeclContext(),
3145 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003146 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003147 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003148 PrevDecl);
3149
3150 if (PrevDecl) {
3151 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3152 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3153 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003154 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003155 InsertPos);
3156 }
Douglas Gregor15301382009-07-30 17:40:51 +00003157
3158 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003159 }
3160
Douglas Gregor06db9f52009-10-12 20:18:28 +00003161 // C++ [temp.expl.spec]p6:
3162 // If a template, a member template or the member of a class template is
3163 // explicitly specialized then that specialization shall be declared
3164 // before the first use of that specialization that would cause an implicit
3165 // instantiation to take place, in every translation unit in which such a
3166 // use occurs; no diagnostic is required.
3167 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3168 SourceRange Range(TemplateNameLoc, RAngleLoc);
3169 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3170 << Context.getTypeDeclType(Specialization) << Range;
3171
3172 Diag(PrevDecl->getPointOfInstantiation(),
3173 diag::note_instantiation_required_here)
3174 << (PrevDecl->getTemplateSpecializationKind()
3175 != TSK_ImplicitInstantiation);
3176 return true;
3177 }
3178
Douglas Gregor2208a292009-09-26 20:57:03 +00003179 // If this is not a friend, note that this is an explicit specialization.
3180 if (TUK != TUK_Friend)
3181 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003182
3183 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003184 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003185 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003186 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003187 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003188 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003189 Diag(Def->getLocation(), diag::note_previous_definition);
3190 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003191 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003192 }
3193 }
3194
Douglas Gregord56a91e2009-02-26 22:19:44 +00003195 // Build the fully-sugared type for this class template
3196 // specialization as the user wrote in the specialization
3197 // itself. This means that we'll pretty-print the type retrieved
3198 // from the specialization's declaration the way that the user
3199 // actually wrote the specialization, rather than formatting the
3200 // name based on the "canonical" representation used to store the
3201 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003202 QualType WrittenTy
3203 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003204 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00003205 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00003206 CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003207 if (TUK != TUK_Friend)
3208 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003209 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003210
Douglas Gregor1e249f82009-02-25 22:18:32 +00003211 // C++ [temp.expl.spec]p9:
3212 // A template explicit specialization is in the scope of the
3213 // namespace in which the template was defined.
3214 //
3215 // We actually implement this paragraph where we set the semantic
3216 // context (in the creation of the ClassTemplateSpecializationDecl),
3217 // but we also maintain the lexical context where the actual
3218 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003219 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003220
Douglas Gregor67a65642009-02-17 23:15:12 +00003221 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003222 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003223 Specialization->startDefinition();
3224
Douglas Gregor2208a292009-09-26 20:57:03 +00003225 if (TUK == TUK_Friend) {
3226 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3227 TemplateNameLoc,
3228 WrittenTy.getTypePtr(),
3229 /*FIXME:*/KWLoc);
3230 Friend->setAccess(AS_public);
3231 CurContext->addDecl(Friend);
3232 } else {
3233 // Add the specialization into its lexical context, so that it can
3234 // be seen when iterating through the list of declarations in that
3235 // context. However, specializations are not found by name lookup.
3236 CurContext->addDecl(Specialization);
3237 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003238 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003239}
Douglas Gregor333489b2009-03-27 23:10:48 +00003240
Mike Stump11289f42009-09-09 15:08:12 +00003241Sema::DeclPtrTy
3242Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003243 MultiTemplateParamsArg TemplateParameterLists,
3244 Declarator &D) {
3245 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3246}
3247
Mike Stump11289f42009-09-09 15:08:12 +00003248Sema::DeclPtrTy
3249Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003250 MultiTemplateParamsArg TemplateParameterLists,
3251 Declarator &D) {
3252 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3253 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3254 "Not a function declarator!");
3255 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003256
Douglas Gregor17a7c122009-06-24 00:54:41 +00003257 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003258 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003259 }
Mike Stump11289f42009-09-09 15:08:12 +00003260
Douglas Gregor17a7c122009-06-24 00:54:41 +00003261 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003262
3263 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003264 move(TemplateParameterLists),
3265 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003266 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003267 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003268 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003269 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003270 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3271 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003272 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003273}
3274
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003275/// \brief Diagnose cases where we have an explicit template specialization
3276/// before/after an explicit template instantiation, producing diagnostics
3277/// for those cases where they are required and determining whether the
3278/// new specialization/instantiation will have any effect.
3279///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003280/// \param NewLoc the location of the new explicit specialization or
3281/// instantiation.
3282///
3283/// \param NewTSK the kind of the new explicit specialization or instantiation.
3284///
3285/// \param PrevDecl the previous declaration of the entity.
3286///
3287/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3288///
3289/// \param PrevPointOfInstantiation if valid, indicates where the previus
3290/// declaration was instantiated (either implicitly or explicitly).
3291///
3292/// \param SuppressNew will be set to true to indicate that the new
3293/// specialization or instantiation has no effect and should be ignored.
3294///
3295/// \returns true if there was an error that should prevent the introduction of
3296/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003297bool
3298Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3299 TemplateSpecializationKind NewTSK,
3300 NamedDecl *PrevDecl,
3301 TemplateSpecializationKind PrevTSK,
3302 SourceLocation PrevPointOfInstantiation,
3303 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003304 SuppressNew = false;
3305
3306 switch (NewTSK) {
3307 case TSK_Undeclared:
3308 case TSK_ImplicitInstantiation:
3309 assert(false && "Don't check implicit instantiations here");
3310 return false;
3311
3312 case TSK_ExplicitSpecialization:
3313 switch (PrevTSK) {
3314 case TSK_Undeclared:
3315 case TSK_ExplicitSpecialization:
3316 // Okay, we're just specializing something that is either already
3317 // explicitly specialized or has merely been mentioned without any
3318 // instantiation.
3319 return false;
3320
3321 case TSK_ImplicitInstantiation:
3322 if (PrevPointOfInstantiation.isInvalid()) {
3323 // The declaration itself has not actually been instantiated, so it is
3324 // still okay to specialize it.
3325 return false;
3326 }
3327 // Fall through
3328
3329 case TSK_ExplicitInstantiationDeclaration:
3330 case TSK_ExplicitInstantiationDefinition:
3331 assert((PrevTSK == TSK_ImplicitInstantiation ||
3332 PrevPointOfInstantiation.isValid()) &&
3333 "Explicit instantiation without point of instantiation?");
3334
3335 // C++ [temp.expl.spec]p6:
3336 // If a template, a member template or the member of a class template
3337 // is explicitly specialized then that specialization shall be declared
3338 // before the first use of that specialization that would cause an
3339 // implicit instantiation to take place, in every translation unit in
3340 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003341 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003342 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003343 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003344 << (PrevTSK != TSK_ImplicitInstantiation);
3345
3346 return true;
3347 }
3348 break;
3349
3350 case TSK_ExplicitInstantiationDeclaration:
3351 switch (PrevTSK) {
3352 case TSK_ExplicitInstantiationDeclaration:
3353 // This explicit instantiation declaration is redundant (that's okay).
3354 SuppressNew = true;
3355 return false;
3356
3357 case TSK_Undeclared:
3358 case TSK_ImplicitInstantiation:
3359 // We're explicitly instantiating something that may have already been
3360 // implicitly instantiated; that's fine.
3361 return false;
3362
3363 case TSK_ExplicitSpecialization:
3364 // C++0x [temp.explicit]p4:
3365 // For a given set of template parameters, if an explicit instantiation
3366 // of a template appears after a declaration of an explicit
3367 // specialization for that template, the explicit instantiation has no
3368 // effect.
3369 return false;
3370
3371 case TSK_ExplicitInstantiationDefinition:
3372 // C++0x [temp.explicit]p10:
3373 // If an entity is the subject of both an explicit instantiation
3374 // declaration and an explicit instantiation definition in the same
3375 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003376 Diag(NewLoc,
3377 diag::err_explicit_instantiation_declaration_after_definition);
3378 Diag(PrevPointOfInstantiation,
3379 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003380 assert(PrevPointOfInstantiation.isValid() &&
3381 "Explicit instantiation without point of instantiation?");
3382 SuppressNew = true;
3383 return false;
3384 }
3385 break;
3386
3387 case TSK_ExplicitInstantiationDefinition:
3388 switch (PrevTSK) {
3389 case TSK_Undeclared:
3390 case TSK_ImplicitInstantiation:
3391 // We're explicitly instantiating something that may have already been
3392 // implicitly instantiated; that's fine.
3393 return false;
3394
3395 case TSK_ExplicitSpecialization:
3396 // C++ DR 259, C++0x [temp.explicit]p4:
3397 // For a given set of template parameters, if an explicit
3398 // instantiation of a template appears after a declaration of
3399 // an explicit specialization for that template, the explicit
3400 // instantiation has no effect.
3401 //
3402 // In C++98/03 mode, we only give an extension warning here, because it
3403 // is not not harmful to try to explicitly instantiate something that
3404 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003405 if (!getLangOptions().CPlusPlus0x) {
3406 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003407 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003408 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003409 diag::note_previous_template_specialization);
3410 }
3411 SuppressNew = true;
3412 return false;
3413
3414 case TSK_ExplicitInstantiationDeclaration:
3415 // We're explicity instantiating a definition for something for which we
3416 // were previously asked to suppress instantiations. That's fine.
3417 return false;
3418
3419 case TSK_ExplicitInstantiationDefinition:
3420 // C++0x [temp.spec]p5:
3421 // For a given template and a given set of template-arguments,
3422 // - an explicit instantiation definition shall appear at most once
3423 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003424 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003425 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003426 Diag(PrevPointOfInstantiation,
3427 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003428 SuppressNew = true;
3429 return false;
3430 }
3431 break;
3432 }
3433
3434 assert(false && "Missing specialization/instantiation case?");
3435
3436 return false;
3437}
3438
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003439/// \brief Perform semantic analysis for the given function template
3440/// specialization.
3441///
3442/// This routine performs all of the semantic analysis required for an
3443/// explicit function template specialization. On successful completion,
3444/// the function declaration \p FD will become a function template
3445/// specialization.
3446///
3447/// \param FD the function declaration, which will be updated to become a
3448/// function template specialization.
3449///
3450/// \param HasExplicitTemplateArgs whether any template arguments were
3451/// explicitly provided.
3452///
3453/// \param LAngleLoc the location of the left angle bracket ('<'), if
3454/// template arguments were explicitly provided.
3455///
3456/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3457/// if any.
3458///
3459/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3460/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3461/// true as in, e.g., \c void sort<>(char*, char*);
3462///
3463/// \param RAngleLoc the location of the right angle bracket ('>'), if
3464/// template arguments were explicitly provided.
3465///
3466/// \param PrevDecl the set of declarations that
3467bool
3468Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3469 bool HasExplicitTemplateArgs,
3470 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00003471 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003472 unsigned NumExplicitTemplateArgs,
3473 SourceLocation RAngleLoc,
3474 NamedDecl *&PrevDecl) {
3475 // The set of function template specializations that could match this
3476 // explicit function template specialization.
3477 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3478 CandidateSet Candidates;
3479
3480 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3481 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3482 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3483 // Only consider templates found within the same semantic lookup scope as
3484 // FD.
3485 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3486 continue;
3487
3488 // C++ [temp.expl.spec]p11:
3489 // A trailing template-argument can be left unspecified in the
3490 // template-id naming an explicit function template specialization
3491 // provided it can be deduced from the function argument type.
3492 // Perform template argument deduction to determine whether we may be
3493 // specializing this template.
3494 // FIXME: It is somewhat wasteful to build
3495 TemplateDeductionInfo Info(Context);
3496 FunctionDecl *Specialization = 0;
3497 if (TemplateDeductionResult TDK
3498 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3499 ExplicitTemplateArgs,
3500 NumExplicitTemplateArgs,
3501 FD->getType(),
3502 Specialization,
3503 Info)) {
3504 // FIXME: Template argument deduction failed; record why it failed, so
3505 // that we can provide nifty diagnostics.
3506 (void)TDK;
3507 continue;
3508 }
3509
3510 // Record this candidate.
3511 Candidates.push_back(Specialization);
3512 }
3513 }
3514
Douglas Gregor5de279c2009-09-26 03:41:46 +00003515 // Find the most specialized function template.
3516 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3517 Candidates.size(),
3518 TPOC_Other,
3519 FD->getLocation(),
3520 PartialDiagnostic(diag::err_function_template_spec_no_match)
3521 << FD->getDeclName(),
3522 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3523 << FD->getDeclName() << HasExplicitTemplateArgs,
3524 PartialDiagnostic(diag::note_function_template_spec_matched));
3525 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003526 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003527
3528 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003529 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003530
Douglas Gregor54888652009-10-07 00:13:32 +00003531 // Check the scope of this explicit specialization.
3532 if (CheckTemplateSpecializationScope(*this,
3533 Specialization->getPrimaryTemplate(),
3534 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003535 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003536 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003537
3538 // C++ [temp.expl.spec]p6:
3539 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003540 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003541 // before the first use of that specialization that would cause an implicit
3542 // instantiation to take place, in every translation unit in which such a
3543 // use occurs; no diagnostic is required.
3544 FunctionTemplateSpecializationInfo *SpecInfo
3545 = Specialization->getTemplateSpecializationInfo();
3546 assert(SpecInfo && "Function template specialization info missing?");
3547 if (SpecInfo->getPointOfInstantiation().isValid()) {
3548 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3549 << FD;
3550 Diag(SpecInfo->getPointOfInstantiation(),
3551 diag::note_instantiation_required_here)
3552 << (Specialization->getTemplateSpecializationKind()
3553 != TSK_ImplicitInstantiation);
3554 return true;
3555 }
Douglas Gregor54888652009-10-07 00:13:32 +00003556
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003557 // Mark the prior declaration as an explicit specialization, so that later
3558 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003559 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003560
3561 // Turn the given function declaration into a function template
3562 // specialization, with the template arguments from the previous
3563 // specialization.
3564 FD->setFunctionTemplateSpecialization(Context,
3565 Specialization->getPrimaryTemplate(),
3566 new (Context) TemplateArgumentList(
3567 *Specialization->getTemplateSpecializationArgs()),
3568 /*InsertPos=*/0,
3569 TSK_ExplicitSpecialization);
3570
3571 // The "previous declaration" for this function template specialization is
3572 // the prior function template specialization.
3573 PrevDecl = Specialization;
3574 return false;
3575}
3576
Douglas Gregor86d142a2009-10-08 07:24:58 +00003577/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003578/// specialization.
3579///
3580/// This routine performs all of the semantic analysis required for an
3581/// explicit member function specialization. On successful completion,
3582/// the function declaration \p FD will become a member function
3583/// specialization.
3584///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003585/// \param Member the member declaration, which will be updated to become a
3586/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003587///
3588/// \param PrevDecl the set of declarations, one of which may be specialized
3589/// by this function specialization.
3590bool
Douglas Gregor86d142a2009-10-08 07:24:58 +00003591Sema::CheckMemberSpecialization(NamedDecl *Member, NamedDecl *&PrevDecl) {
3592 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3593
3594 // Try to find the member we are instantiating.
3595 NamedDecl *Instantiation = 0;
3596 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003597 MemberSpecializationInfo *MSInfo = 0;
3598
Douglas Gregor86d142a2009-10-08 07:24:58 +00003599 if (!PrevDecl) {
3600 // Nowhere to look anyway.
3601 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3602 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3603 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl)) {
3604 if (Context.hasSameType(Function->getType(), Method->getType())) {
3605 Instantiation = Method;
3606 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003607 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003608 break;
3609 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003610 }
3611 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003612 } else if (isa<VarDecl>(Member)) {
3613 if (VarDecl *PrevVar = dyn_cast<VarDecl>(PrevDecl))
3614 if (PrevVar->isStaticDataMember()) {
3615 Instantiation = PrevDecl;
3616 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003617 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003618 }
3619 } else if (isa<RecordDecl>(Member)) {
3620 if (CXXRecordDecl *PrevRecord = dyn_cast<CXXRecordDecl>(PrevDecl)) {
3621 Instantiation = PrevDecl;
3622 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003623 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003624 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003625 }
3626
3627 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003628 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003629 // specializations are always out-of-line, the caller will complain about
3630 // this mismatch later.
3631 return false;
3632 }
3633
Douglas Gregor86d142a2009-10-08 07:24:58 +00003634 // Make sure that this is a specialization of a member.
3635 if (!InstantiatedFrom) {
3636 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3637 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003638 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3639 return true;
3640 }
3641
Douglas Gregor06db9f52009-10-12 20:18:28 +00003642 // C++ [temp.expl.spec]p6:
3643 // If a template, a member template or the member of a class template is
3644 // explicitly specialized then that spe- cialization shall be declared
3645 // before the first use of that specialization that would cause an implicit
3646 // instantiation to take place, in every translation unit in which such a
3647 // use occurs; no diagnostic is required.
3648 assert(MSInfo && "Member specialization info missing?");
3649 if (MSInfo->getPointOfInstantiation().isValid()) {
3650 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3651 << Member;
3652 Diag(MSInfo->getPointOfInstantiation(),
3653 diag::note_instantiation_required_here)
3654 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3655 return true;
3656 }
3657
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003658 // Check the scope of this explicit specialization.
3659 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003660 InstantiatedFrom,
3661 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003662 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003663 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003664
Douglas Gregor86d142a2009-10-08 07:24:58 +00003665 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003666 // the original declaration to note that it is an explicit specialization
3667 // (if it was previously an implicit instantiation). This latter step
3668 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003669 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003670 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3671 if (InstantiationFunction->getTemplateSpecializationKind() ==
3672 TSK_ImplicitInstantiation) {
3673 InstantiationFunction->setTemplateSpecializationKind(
3674 TSK_ExplicitSpecialization);
3675 InstantiationFunction->setLocation(Member->getLocation());
3676 }
3677
Douglas Gregor86d142a2009-10-08 07:24:58 +00003678 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3679 cast<CXXMethodDecl>(InstantiatedFrom),
3680 TSK_ExplicitSpecialization);
3681 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003682 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3683 if (InstantiationVar->getTemplateSpecializationKind() ==
3684 TSK_ImplicitInstantiation) {
3685 InstantiationVar->setTemplateSpecializationKind(
3686 TSK_ExplicitSpecialization);
3687 InstantiationVar->setLocation(Member->getLocation());
3688 }
3689
Douglas Gregor86d142a2009-10-08 07:24:58 +00003690 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3691 cast<VarDecl>(InstantiatedFrom),
3692 TSK_ExplicitSpecialization);
3693 } else {
3694 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003695 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3696 if (InstantiationClass->getTemplateSpecializationKind() ==
3697 TSK_ImplicitInstantiation) {
3698 InstantiationClass->setTemplateSpecializationKind(
3699 TSK_ExplicitSpecialization);
3700 InstantiationClass->setLocation(Member->getLocation());
3701 }
3702
Douglas Gregor86d142a2009-10-08 07:24:58 +00003703 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003704 cast<CXXRecordDecl>(InstantiatedFrom),
3705 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003706 }
3707
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003708 // Save the caller the trouble of having to figure out which declaration
3709 // this specialization matches.
3710 PrevDecl = Instantiation;
3711 return false;
3712}
3713
Douglas Gregore47f5a72009-10-14 23:41:34 +00003714/// \brief Check the scope of an explicit instantiation.
3715static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3716 SourceLocation InstLoc,
3717 bool WasQualifiedName) {
3718 DeclContext *ExpectedContext
3719 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3720 DeclContext *CurContext = S.CurContext->getLookupContext();
3721
3722 // C++0x [temp.explicit]p2:
3723 // An explicit instantiation shall appear in an enclosing namespace of its
3724 // template.
3725 //
3726 // This is DR275, which we do not retroactively apply to C++98/03.
3727 if (S.getLangOptions().CPlusPlus0x &&
3728 !CurContext->Encloses(ExpectedContext)) {
3729 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3730 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3731 << D << NS;
3732 else
3733 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3734 << D;
3735 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3736 return;
3737 }
3738
3739 // C++0x [temp.explicit]p2:
3740 // If the name declared in the explicit instantiation is an unqualified
3741 // name, the explicit instantiation shall appear in the namespace where
3742 // its template is declared or, if that namespace is inline (7.3.1), any
3743 // namespace from its enclosing namespace set.
3744 if (WasQualifiedName)
3745 return;
3746
3747 if (CurContext->Equals(ExpectedContext))
3748 return;
3749
3750 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3751 << D << ExpectedContext;
3752 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3753}
3754
3755/// \brief Determine whether the given scope specifier has a template-id in it.
3756static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3757 if (!SS.isSet())
3758 return false;
3759
3760 // C++0x [temp.explicit]p2:
3761 // If the explicit instantiation is for a member function, a member class
3762 // or a static data member of a class template specialization, the name of
3763 // the class template specialization in the qualified-id for the member
3764 // name shall be a simple-template-id.
3765 //
3766 // C++98 has the same restriction, just worded differently.
3767 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3768 NNS; NNS = NNS->getPrefix())
3769 if (Type *T = NNS->getAsType())
3770 if (isa<TemplateSpecializationType>(T))
3771 return true;
3772
3773 return false;
3774}
3775
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003776// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003777// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003778Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003779Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003780 SourceLocation ExternLoc,
3781 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003782 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003783 SourceLocation KWLoc,
3784 const CXXScopeSpec &SS,
3785 TemplateTy TemplateD,
3786 SourceLocation TemplateNameLoc,
3787 SourceLocation LAngleLoc,
3788 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00003789 SourceLocation RAngleLoc,
3790 AttributeList *Attr) {
3791 // Find the class template we're specializing
3792 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003793 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003794 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3795
3796 // Check that the specialization uses the same tag kind as the
3797 // original template.
3798 TagDecl::TagKind Kind;
3799 switch (TagSpec) {
3800 default: assert(0 && "Unknown tag type!");
3801 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3802 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3803 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3804 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003805 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003806 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003807 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003808 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003809 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003810 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003811 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003812 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003813 diag::note_previous_use);
3814 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3815 }
3816
Douglas Gregore47f5a72009-10-14 23:41:34 +00003817 // C++0x [temp.explicit]p2:
3818 // There are two forms of explicit instantiation: an explicit instantiation
3819 // definition and an explicit instantiation declaration. An explicit
3820 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00003821 TemplateSpecializationKind TSK
3822 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3823 : TSK_ExplicitInstantiationDeclaration;
3824
Douglas Gregora1f49972009-05-13 00:25:59 +00003825 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00003826 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003827 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00003828
3829 // Check that the template argument list is well-formed for this
3830 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003831 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3832 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003833 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003834 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003835 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003836 return true;
3837
Mike Stump11289f42009-09-09 15:08:12 +00003838 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003839 ClassTemplate->getTemplateParameters()->size()) &&
3840 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003841
Douglas Gregora1f49972009-05-13 00:25:59 +00003842 // Find the class template specialization declaration that
3843 // corresponds to these arguments.
3844 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003845 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003846 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003847 Converted.flatSize(),
3848 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003849 void *InsertPos = 0;
3850 ClassTemplateSpecializationDecl *PrevDecl
3851 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3852
Douglas Gregor54888652009-10-07 00:13:32 +00003853 // C++0x [temp.explicit]p2:
3854 // [...] An explicit instantiation shall appear in an enclosing
3855 // namespace of its template. [...]
3856 //
3857 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00003858 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
3859 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00003860
Douglas Gregora1f49972009-05-13 00:25:59 +00003861 ClassTemplateSpecializationDecl *Specialization = 0;
3862
3863 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00003864 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003865 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00003866 PrevDecl,
3867 PrevDecl->getSpecializationKind(),
3868 PrevDecl->getPointOfInstantiation(),
3869 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00003870 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003871
Douglas Gregor12e49d32009-10-15 22:53:21 +00003872 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003873 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00003874
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003875 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3876 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3877 // Since the only prior class template specialization with these
3878 // arguments was referenced but not declared, reuse that
3879 // declaration node as our own, updating its source location to
3880 // reflect our new declaration.
3881 Specialization = PrevDecl;
3882 Specialization->setLocation(TemplateNameLoc);
3883 PrevDecl = 0;
3884 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00003885 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003886
3887 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003888 // Create a new class template specialization declaration node for
3889 // this explicit specialization.
3890 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003891 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003892 ClassTemplate->getDeclContext(),
3893 TemplateNameLoc,
3894 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003895 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003896
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003897 if (PrevDecl) {
3898 // Remove the previous declaration from the folding set, since we want
3899 // to introduce a new declaration.
3900 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3901 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3902 }
3903
3904 // Insert the new specialization.
3905 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003906 }
3907
3908 // Build the fully-sugared type for this explicit instantiation as
3909 // the user wrote in the explicit instantiation itself. This means
3910 // that we'll pretty-print the type retrieved from the
3911 // specialization's declaration the way that the user actually wrote
3912 // the explicit instantiation, rather than formatting the name based
3913 // on the "canonical" representation used to store the template
3914 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003915 QualType WrittenTy
3916 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003917 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003918 TemplateArgs.size(),
3919 Context.getTypeDeclType(Specialization));
3920 Specialization->setTypeAsWritten(WrittenTy);
3921 TemplateArgsIn.release();
3922
3923 // Add the explicit instantiation into its lexical context. However,
3924 // since explicit instantiations are never found by name lookup, we
3925 // just put it into the declaration context directly.
3926 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003927 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003928
3929 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003930 // A definition of a class template or class member template
3931 // shall be in scope at the point of the explicit instantiation of
3932 // the class template or class member template.
3933 //
3934 // This check comes when we actually try to perform the
3935 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00003936 ClassTemplateSpecializationDecl *Def
3937 = cast_or_null<ClassTemplateSpecializationDecl>(
3938 Specialization->getDefinition(Context));
3939 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00003940 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00003941
3942 // Instantiate the members of this class template specialization.
3943 Def = cast_or_null<ClassTemplateSpecializationDecl>(
3944 Specialization->getDefinition(Context));
3945 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00003946 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003947
3948 return DeclPtrTy::make(Specialization);
3949}
3950
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003951// Explicit instantiation of a member class of a class template.
3952Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003953Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003954 SourceLocation ExternLoc,
3955 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003956 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003957 SourceLocation KWLoc,
3958 const CXXScopeSpec &SS,
3959 IdentifierInfo *Name,
3960 SourceLocation NameLoc,
3961 AttributeList *Attr) {
3962
Douglas Gregord6ab8742009-05-28 23:31:59 +00003963 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003964 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00003965 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00003966 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00003967 MultiTemplateParamsArg(*this, 0, 0),
3968 Owned, IsDependent);
3969 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3970
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003971 if (!TagD)
3972 return true;
3973
3974 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3975 if (Tag->isEnum()) {
3976 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3977 << Context.getTypeDeclType(Tag);
3978 return true;
3979 }
3980
Douglas Gregorb8006faf2009-05-27 17:30:49 +00003981 if (Tag->isInvalidDecl())
3982 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00003983
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003984 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3985 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3986 if (!Pattern) {
3987 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3988 << Context.getTypeDeclType(Record);
3989 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3990 return true;
3991 }
3992
Douglas Gregore47f5a72009-10-14 23:41:34 +00003993 // C++0x [temp.explicit]p2:
3994 // If the explicit instantiation is for a class or member class, the
3995 // elaborated-type-specifier in the declaration shall include a
3996 // simple-template-id.
3997 //
3998 // C++98 has the same restriction, just worded differently.
3999 if (!ScopeSpecifierHasTemplateId(SS))
4000 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4001 << Record << SS.getRange();
4002
4003 // C++0x [temp.explicit]p2:
4004 // There are two forms of explicit instantiation: an explicit instantiation
4005 // definition and an explicit instantiation declaration. An explicit
4006 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004007 TemplateSpecializationKind TSK
4008 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4009 : TSK_ExplicitInstantiationDeclaration;
4010
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004011 // C++0x [temp.explicit]p2:
4012 // [...] An explicit instantiation shall appear in an enclosing
4013 // namespace of its template. [...]
4014 //
4015 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004016 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004017
4018 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004019 CXXRecordDecl *PrevDecl
4020 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4021 if (!PrevDecl && Record->getDefinition(Context))
4022 PrevDecl = Record;
4023 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004024 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4025 bool SuppressNew = false;
4026 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004027 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004028 PrevDecl,
4029 MSInfo->getTemplateSpecializationKind(),
4030 MSInfo->getPointOfInstantiation(),
4031 SuppressNew))
4032 return true;
4033 if (SuppressNew)
4034 return TagD;
4035 }
4036
Douglas Gregor12e49d32009-10-15 22:53:21 +00004037 CXXRecordDecl *RecordDef
4038 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4039 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004040 // C++ [temp.explicit]p3:
4041 // A definition of a member class of a class template shall be in scope
4042 // at the point of an explicit instantiation of the member class.
4043 CXXRecordDecl *Def
4044 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4045 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004046 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4047 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004048 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4049 << Pattern;
4050 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004051 } else {
4052 if (InstantiateClass(NameLoc, Record, Def,
4053 getTemplateInstantiationArgs(Record),
4054 TSK))
4055 return true;
4056
4057 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4058 if (!RecordDef)
4059 return true;
4060 }
4061 }
4062
4063 // Instantiate all of the members of the class.
4064 InstantiateClassMembers(NameLoc, RecordDef,
4065 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004066
Mike Stump87c57ac2009-05-16 07:39:55 +00004067 // FIXME: We don't have any representation for explicit instantiations of
4068 // member classes. Such a representation is not needed for compilation, but it
4069 // should be available for clients that want to see all of the declarations in
4070 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004071 return TagD;
4072}
4073
Douglas Gregor450f00842009-09-25 18:43:00 +00004074Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4075 SourceLocation ExternLoc,
4076 SourceLocation TemplateLoc,
4077 Declarator &D) {
4078 // Explicit instantiations always require a name.
4079 DeclarationName Name = GetNameForDeclarator(D);
4080 if (!Name) {
4081 if (!D.isInvalidType())
4082 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4083 diag::err_explicit_instantiation_requires_name)
4084 << D.getDeclSpec().getSourceRange()
4085 << D.getSourceRange();
4086
4087 return true;
4088 }
4089
4090 // The scope passed in may not be a decl scope. Zip up the scope tree until
4091 // we find one that is.
4092 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4093 (S->getFlags() & Scope::TemplateParamScope) != 0)
4094 S = S->getParent();
4095
4096 // Determine the type of the declaration.
4097 QualType R = GetTypeForDeclarator(D, S, 0);
4098 if (R.isNull())
4099 return true;
4100
4101 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4102 // Cannot explicitly instantiate a typedef.
4103 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4104 << Name;
4105 return true;
4106 }
4107
Douglas Gregor3c74d412009-10-14 20:14:33 +00004108 // C++0x [temp.explicit]p1:
4109 // [...] An explicit instantiation of a function template shall not use the
4110 // inline or constexpr specifiers.
4111 // Presumably, this also applies to member functions of class templates as
4112 // well.
4113 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4114 Diag(D.getDeclSpec().getInlineSpecLoc(),
4115 diag::err_explicit_instantiation_inline)
4116 << CodeModificationHint::CreateRemoval(
4117 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
4118
4119 // FIXME: check for constexpr specifier.
4120
Douglas Gregore47f5a72009-10-14 23:41:34 +00004121 // C++0x [temp.explicit]p2:
4122 // There are two forms of explicit instantiation: an explicit instantiation
4123 // definition and an explicit instantiation declaration. An explicit
4124 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004125 TemplateSpecializationKind TSK
4126 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4127 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004128
John McCall9f3059a2009-10-09 21:13:30 +00004129 LookupResult Previous;
4130 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
4131 Name, LookupOrdinaryName);
Douglas Gregor450f00842009-09-25 18:43:00 +00004132
4133 if (!R->isFunctionType()) {
4134 // C++ [temp.explicit]p1:
4135 // A [...] static data member of a class template can be explicitly
4136 // instantiated from the member definition associated with its class
4137 // template.
4138 if (Previous.isAmbiguous()) {
4139 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
4140 D.getSourceRange());
4141 }
4142
John McCall9f3059a2009-10-09 21:13:30 +00004143 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4144 Previous.getAsSingleDecl(Context));
Douglas Gregor450f00842009-09-25 18:43:00 +00004145 if (!Prev || !Prev->isStaticDataMember()) {
4146 // We expect to see a data data member here.
4147 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4148 << Name;
4149 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4150 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004151 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004152 return true;
4153 }
4154
4155 if (!Prev->getInstantiatedFromStaticDataMember()) {
4156 // FIXME: Check for explicit specialization?
4157 Diag(D.getIdentifierLoc(),
4158 diag::err_explicit_instantiation_data_member_not_instantiated)
4159 << Prev;
4160 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4161 // FIXME: Can we provide a note showing where this was declared?
4162 return true;
4163 }
4164
Douglas Gregore47f5a72009-10-14 23:41:34 +00004165 // C++0x [temp.explicit]p2:
4166 // If the explicit instantiation is for a member function, a member class
4167 // or a static data member of a class template specialization, the name of
4168 // the class template specialization in the qualified-id for the member
4169 // name shall be a simple-template-id.
4170 //
4171 // C++98 has the same restriction, just worded differently.
4172 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4173 Diag(D.getIdentifierLoc(),
4174 diag::err_explicit_instantiation_without_qualified_id)
4175 << Prev << D.getCXXScopeSpec().getRange();
4176
4177 // Check the scope of this explicit instantiation.
4178 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4179
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004180 // Verify that it is okay to explicitly instantiate here.
4181 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4182 assert(MSInfo && "Missing static data member specialization info?");
4183 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004184 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004185 MSInfo->getTemplateSpecializationKind(),
4186 MSInfo->getPointOfInstantiation(),
4187 SuppressNew))
4188 return true;
4189 if (SuppressNew)
4190 return DeclPtrTy();
4191
Douglas Gregor450f00842009-09-25 18:43:00 +00004192 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004193 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004194 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004195 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4196 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004197
4198 // FIXME: Create an ExplicitInstantiation node?
4199 return DeclPtrTy();
4200 }
4201
Douglas Gregor0e876e02009-09-25 23:53:26 +00004202 // If the declarator is a template-id, translate the parser's template
4203 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004204 bool HasExplicitTemplateArgs = false;
John McCall0ad16662009-10-29 08:12:44 +00004205 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004206 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4207 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Douglas Gregord90fd522009-09-25 21:45:23 +00004208 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4209 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004210 TemplateId->NumArgs);
4211 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregord90fd522009-09-25 21:45:23 +00004212 TemplateArgs);
4213 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004214 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004215 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004216
Douglas Gregor450f00842009-09-25 18:43:00 +00004217 // C++ [temp.explicit]p1:
4218 // A [...] function [...] can be explicitly instantiated from its template.
4219 // A member function [...] of a class template can be explicitly
4220 // instantiated from the member definition associated with its class
4221 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004222 llvm::SmallVector<FunctionDecl *, 8> Matches;
4223 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4224 P != PEnd; ++P) {
4225 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004226 if (!HasExplicitTemplateArgs) {
4227 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4228 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4229 Matches.clear();
4230 Matches.push_back(Method);
4231 break;
4232 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004233 }
4234 }
4235
4236 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4237 if (!FunTmpl)
4238 continue;
4239
4240 TemplateDeductionInfo Info(Context);
4241 FunctionDecl *Specialization = 0;
4242 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00004243 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
4244 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00004245 R, Specialization, Info)) {
4246 // FIXME: Keep track of almost-matches?
4247 (void)TDK;
4248 continue;
4249 }
4250
4251 Matches.push_back(Specialization);
4252 }
4253
4254 // Find the most specialized function template specialization.
4255 FunctionDecl *Specialization
4256 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4257 D.getIdentifierLoc(),
4258 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4259 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4260 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4261
4262 if (!Specialization)
4263 return true;
4264
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004265 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004266 Diag(D.getIdentifierLoc(),
4267 diag::err_explicit_instantiation_member_function_not_instantiated)
4268 << Specialization
4269 << (Specialization->getTemplateSpecializationKind() ==
4270 TSK_ExplicitSpecialization);
4271 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4272 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004273 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004274
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004275 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004276 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4277 PrevDecl = Specialization;
4278
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004279 if (PrevDecl) {
4280 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004281 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004282 PrevDecl,
4283 PrevDecl->getTemplateSpecializationKind(),
4284 PrevDecl->getPointOfInstantiation(),
4285 SuppressNew))
4286 return true;
4287
4288 // FIXME: We may still want to build some representation of this
4289 // explicit specialization.
4290 if (SuppressNew)
4291 return DeclPtrTy();
4292 }
4293
4294 if (TSK == TSK_ExplicitInstantiationDefinition)
4295 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4296 false, /*DefinitionRequired=*/true);
4297
4298 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4299
Douglas Gregore47f5a72009-10-14 23:41:34 +00004300 // C++0x [temp.explicit]p2:
4301 // If the explicit instantiation is for a member function, a member class
4302 // or a static data member of a class template specialization, the name of
4303 // the class template specialization in the qualified-id for the member
4304 // name shall be a simple-template-id.
4305 //
4306 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004307 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004308 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004309 D.getCXXScopeSpec().isSet() &&
4310 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4311 Diag(D.getIdentifierLoc(),
4312 diag::err_explicit_instantiation_without_qualified_id)
4313 << Specialization << D.getCXXScopeSpec().getRange();
4314
4315 CheckExplicitInstantiationScope(*this,
4316 FunTmpl? (NamedDecl *)FunTmpl
4317 : Specialization->getInstantiatedFromMemberFunction(),
4318 D.getIdentifierLoc(),
4319 D.getCXXScopeSpec().isSet());
4320
Douglas Gregor450f00842009-09-25 18:43:00 +00004321 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4322 return DeclPtrTy();
4323}
4324
Douglas Gregor333489b2009-03-27 23:10:48 +00004325Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004326Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4327 const CXXScopeSpec &SS, IdentifierInfo *Name,
4328 SourceLocation TagLoc, SourceLocation NameLoc) {
4329 // This has to hold, because SS is expected to be defined.
4330 assert(Name && "Expected a name in a dependent tag");
4331
4332 NestedNameSpecifier *NNS
4333 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4334 if (!NNS)
4335 return true;
4336
4337 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4338 if (T.isNull())
4339 return true;
4340
4341 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4342 QualType ElabType = Context.getElaboratedType(T, TagKind);
4343
4344 return ElabType.getAsOpaquePtr();
4345}
4346
4347Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004348Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4349 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004350 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004351 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4352 if (!NNS)
4353 return true;
4354
4355 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004356 if (T.isNull())
4357 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004358 return T.getAsOpaquePtr();
4359}
4360
Douglas Gregordce2b622009-04-01 00:28:59 +00004361Sema::TypeResult
4362Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4363 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004364 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004365 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004366 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004367 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004368 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004369 assert(TemplateId && "Expected a template specialization type");
4370
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004371 if (computeDeclContext(SS, false)) {
4372 // If we can compute a declaration context, then the "typename"
4373 // keyword was superfluous. Just build a QualifiedNameType to keep
4374 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004375
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004376 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4377 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4378 }
Mike Stump11289f42009-09-09 15:08:12 +00004379
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004380 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004381}
4382
Douglas Gregor333489b2009-03-27 23:10:48 +00004383/// \brief Build the type that describes a C++ typename specifier,
4384/// e.g., "typename T::type".
4385QualType
4386Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4387 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004388 CXXRecordDecl *CurrentInstantiation = 0;
4389 if (NNS->isDependent()) {
4390 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004391
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004392 // If the nested-name-specifier does not refer to the current
4393 // instantiation, then build a typename type.
4394 if (!CurrentInstantiation)
4395 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004396
Douglas Gregorc707da62009-09-02 13:12:51 +00004397 // The nested-name-specifier refers to the current instantiation, so the
4398 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004399 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004400 // extraneous "typename" keywords, and we retroactively apply this DR to
4401 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004402 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004403
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004404 DeclContext *Ctx = 0;
4405
4406 if (CurrentInstantiation)
4407 Ctx = CurrentInstantiation;
4408 else {
4409 CXXScopeSpec SS;
4410 SS.setScopeRep(NNS);
4411 SS.setRange(Range);
4412 if (RequireCompleteDeclContext(SS))
4413 return QualType();
4414
4415 Ctx = computeDeclContext(SS);
4416 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004417 assert(Ctx && "No declaration context?");
4418
4419 DeclarationName Name(&II);
John McCall9f3059a2009-10-09 21:13:30 +00004420 LookupResult Result;
4421 LookupQualifiedName(Result, Ctx, Name, LookupOrdinaryName, false);
Douglas Gregor333489b2009-03-27 23:10:48 +00004422 unsigned DiagID = 0;
4423 Decl *Referenced = 0;
4424 switch (Result.getKind()) {
4425 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004426 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004427 break;
4428
4429 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004430 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004431 // We found a type. Build a QualifiedNameType, since the
4432 // typename-specifier was just sugar. FIXME: Tell
4433 // QualifiedNameType that it has a "typename" prefix.
4434 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4435 }
4436
4437 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004438 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004439 break;
4440
4441 case LookupResult::FoundOverloaded:
4442 DiagID = diag::err_typename_nested_not_type;
4443 Referenced = *Result.begin();
4444 break;
4445
John McCall6538c932009-10-10 05:48:19 +00004446 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004447 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
4448 return QualType();
4449 }
4450
4451 // If we get here, it's because name lookup did not find a
4452 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004453 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004454 if (Referenced)
4455 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4456 << Name;
4457 return QualType();
4458}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004459
4460namespace {
4461 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00004462 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4463 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004464 SourceLocation Loc;
4465 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004466
Douglas Gregor15acfb92009-08-06 16:20:37 +00004467 public:
Mike Stump11289f42009-09-09 15:08:12 +00004468 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004469 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004470 DeclarationName Entity)
4471 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004472 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004473
4474 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004475 /// transformed.
4476 ///
4477 /// For the purposes of type reconstruction, a type has already been
4478 /// transformed if it is NULL or if it is not dependent.
4479 bool AlreadyTransformed(QualType T) {
4480 return T.isNull() || !T->isDependentType();
4481 }
Mike Stump11289f42009-09-09 15:08:12 +00004482
4483 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004484 /// rebuilt.
4485 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004486
Douglas Gregor15acfb92009-08-06 16:20:37 +00004487 /// \brief Returns the name of the entity whose type is being rebuilt.
4488 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004489
Douglas Gregoref6ab412009-10-27 06:26:26 +00004490 /// \brief Sets the "base" location and entity when that
4491 /// information is known based on another transformation.
4492 void setBase(SourceLocation Loc, DeclarationName Entity) {
4493 this->Loc = Loc;
4494 this->Entity = Entity;
4495 }
4496
Douglas Gregor15acfb92009-08-06 16:20:37 +00004497 /// \brief Transforms an expression by returning the expression itself
4498 /// (an identity function).
4499 ///
4500 /// FIXME: This is completely unsafe; we will need to actually clone the
4501 /// expressions.
4502 Sema::OwningExprResult TransformExpr(Expr *E) {
4503 return getSema().Owned(E);
4504 }
Mike Stump11289f42009-09-09 15:08:12 +00004505
Douglas Gregor15acfb92009-08-06 16:20:37 +00004506 /// \brief Transforms a typename type by determining whether the type now
4507 /// refers to a member of the current instantiation, and then
4508 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004509 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004510 };
4511}
4512
Mike Stump11289f42009-09-09 15:08:12 +00004513QualType
John McCall550e0c22009-10-21 00:40:46 +00004514CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4515 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004516 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004517
Douglas Gregor15acfb92009-08-06 16:20:37 +00004518 NestedNameSpecifier *NNS
4519 = TransformNestedNameSpecifier(T->getQualifier(),
4520 /*FIXME:*/SourceRange(getBaseLocation()));
4521 if (!NNS)
4522 return QualType();
4523
4524 // If the nested-name-specifier did not change, and we cannot compute the
4525 // context corresponding to the nested-name-specifier, then this
4526 // typename type will not change; exit early.
4527 CXXScopeSpec SS;
4528 SS.setRange(SourceRange(getBaseLocation()));
4529 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004530
4531 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004532 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004533 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004534
4535 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004536 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004537 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004538 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004539 = TransformType(QualType(TemplateId, 0));
4540 if (NewTemplateId.isNull())
4541 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004542
Douglas Gregor15acfb92009-08-06 16:20:37 +00004543 if (NNS == T->getQualifier() &&
4544 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004545 Result = QualType(T, 0);
4546 else
4547 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4548 } else
4549 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4550 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004551
John McCall0ad16662009-10-29 08:12:44 +00004552 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4553 NewTL.setNameLoc(TL.getNameLoc());
4554 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004555}
4556
4557/// \brief Rebuilds a type within the context of the current instantiation.
4558///
Mike Stump11289f42009-09-09 15:08:12 +00004559/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004560/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004561/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004562/// partial specialization thereof). This routine will rebuild that type now
4563/// that we have entered the declarator's scope, which may produce different
4564/// canonical types, e.g.,
4565///
4566/// \code
4567/// template<typename T>
4568/// struct X {
4569/// typedef T* pointer;
4570/// pointer data();
4571/// };
4572///
4573/// template<typename T>
4574/// typename X<T>::pointer X<T>::data() { ... }
4575/// \endcode
4576///
4577/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4578/// since we do not know that we can look into X<T> when we parsed the type.
4579/// This function will rebuild the type, performing the lookup of "pointer"
4580/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4581/// as the canonical type of T*, allowing the return types of the out-of-line
4582/// definition and the declaration to match.
4583QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4584 DeclarationName Name) {
4585 if (T.isNull() || !T->isDependentType())
4586 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004587
Douglas Gregor15acfb92009-08-06 16:20:37 +00004588 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4589 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004590}
Douglas Gregorbe999392009-09-15 16:23:51 +00004591
4592/// \brief Produces a formatted string that describes the binding of
4593/// template parameters to template arguments.
4594std::string
4595Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4596 const TemplateArgumentList &Args) {
4597 std::string Result;
4598
4599 if (!Params || Params->size() == 0)
4600 return Result;
4601
4602 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4603 if (I == 0)
4604 Result += "[with ";
4605 else
4606 Result += ", ";
4607
4608 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4609 Result += Id->getName();
4610 } else {
4611 Result += '$';
4612 Result += llvm::utostr(I);
4613 }
4614
4615 Result += " = ";
4616
4617 switch (Args[I].getKind()) {
4618 case TemplateArgument::Null:
4619 Result += "<no value>";
4620 break;
4621
4622 case TemplateArgument::Type: {
4623 std::string TypeStr;
4624 Args[I].getAsType().getAsStringInternal(TypeStr,
4625 Context.PrintingPolicy);
4626 Result += TypeStr;
4627 break;
4628 }
4629
4630 case TemplateArgument::Declaration: {
4631 bool Unnamed = true;
4632 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4633 if (ND->getDeclName()) {
4634 Unnamed = false;
4635 Result += ND->getNameAsString();
4636 }
4637 }
4638
4639 if (Unnamed) {
4640 Result += "<anonymous>";
4641 }
4642 break;
4643 }
4644
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004645 case TemplateArgument::Template: {
4646 std::string Str;
4647 llvm::raw_string_ostream OS(Str);
4648 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4649 Result += OS.str();
4650 break;
4651 }
4652
Douglas Gregorbe999392009-09-15 16:23:51 +00004653 case TemplateArgument::Integral: {
4654 Result += Args[I].getAsIntegral()->toString(10);
4655 break;
4656 }
4657
4658 case TemplateArgument::Expression: {
4659 assert(false && "No expressions in deduced template arguments!");
4660 Result += "<expression>";
4661 break;
4662 }
4663
4664 case TemplateArgument::Pack:
4665 // FIXME: Format template argument packs
4666 Result += "<template argument pack>";
4667 break;
4668 }
4669 }
4670
4671 Result += ']';
4672 return Result;
4673}