blob: a37a73119ddecaef4bfae9672656bafffe3206ec [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000020#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000023#include "llvm/Support/Compiler.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregorb7bfe792009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
31 if (!D)
32 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
Mike Stump11289f42009-09-09 15:08:12 +000036
Douglas Gregorb7bfe792009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregorb7bfe792009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
63 if (!Ovl)
64 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000065
Douglas Gregorb7bfe792009-09-02 22:59:36 +000066 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
67 FEnd = Ovl->function_end();
68 F != FEnd; ++F) {
69 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
70 // We've found a function template. Determine whether there are
71 // any other function templates we need to bundle together in an
72 // OverloadedFunctionDecl
73 for (++F; F != FEnd; ++F) {
74 if (isa<FunctionTemplateDecl>(*F))
75 break;
76 }
Mike Stump11289f42009-09-09 15:08:12 +000077
Douglas Gregorb7bfe792009-09-02 22:59:36 +000078 if (F != FEnd) {
79 // Build an overloaded function decl containing only the
80 // function templates in Ovl.
Mike Stump11289f42009-09-09 15:08:12 +000081 OverloadedFunctionDecl *OvlTemplate
Douglas Gregorb7bfe792009-09-02 22:59:36 +000082 = OverloadedFunctionDecl::Create(Context,
83 Ovl->getDeclContext(),
84 Ovl->getDeclName());
85 OvlTemplate->addOverload(FuncTmpl);
86 OvlTemplate->addOverload(*F);
87 for (++F; F != FEnd; ++F) {
88 if (isa<FunctionTemplateDecl>(*F))
89 OvlTemplate->addOverload(*F);
90 }
Mike Stump11289f42009-09-09 15:08:12 +000091
Douglas Gregorb7bfe792009-09-02 22:59:36 +000092 return OvlTemplate;
93 }
94
95 return FuncTmpl;
96 }
97 }
Mike Stump11289f42009-09-09 15:08:12 +000098
Douglas Gregorb7bfe792009-09-02 22:59:36 +000099 return 0;
100}
101
102TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000103 const CXXScopeSpec &SS,
104 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000105 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000106 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000107 TemplateTy &TemplateResult) {
Douglas Gregor3cf81312009-11-03 23:16:33 +0000108 DeclarationName TName;
109
110 switch (Name.getKind()) {
111 case UnqualifiedId::IK_Identifier:
112 TName = DeclarationName(Name.Identifier);
113 break;
114
115 case UnqualifiedId::IK_OperatorFunctionId:
116 TName = Context.DeclarationNames.getCXXOperatorName(
117 Name.OperatorFunctionId.Operator);
118 break;
119
120 default:
121 return TNK_Non_template;
122 }
123
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000124 // Determine where to perform name lookup
125 DeclContext *LookupCtx = 0;
126 bool isDependent = false;
127 if (ObjectTypePtr) {
128 // This nested-name-specifier occurs in a member access expression, e.g.,
129 // x->B::f, and we are looking into the type of the object.
Douglas Gregor3cf81312009-11-03 23:16:33 +0000130 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000131 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
132 LookupCtx = computeDeclContext(ObjectType);
133 isDependent = ObjectType->isDependentType();
Douglas Gregor3fad6172009-11-17 05:17:33 +0000134 assert((isDependent || !ObjectType->isIncompleteType()) &&
135 "Caller should have completed object type");
Douglas Gregor3cf81312009-11-03 23:16:33 +0000136 } else if (SS.isSet()) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000137 // This nested-name-specifier occurs after another nested-name-specifier,
138 // so long into the context associated with the prior nested-name-specifier.
Douglas Gregor3cf81312009-11-03 23:16:33 +0000139 LookupCtx = computeDeclContext(SS, EnteringContext);
140 isDependent = isDependentScopeSpecifier(SS);
Douglas Gregor3fad6172009-11-17 05:17:33 +0000141
142 // The declaration context must be complete.
143 if (LookupCtx && RequireCompleteDeclContext(SS))
144 return TNK_Non_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000145 }
Mike Stump11289f42009-09-09 15:08:12 +0000146
John McCall27b18f82009-11-17 02:14:36 +0000147 LookupResult Found(*this, TName, SourceLocation(), LookupOrdinaryName);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000148 bool ObjectTypeSearchedInScope = false;
149 if (LookupCtx) {
150 // Perform "qualified" name lookup into the declaration context we
151 // computed, which is either the type of the base of a member access
Mike Stump11289f42009-09-09 15:08:12 +0000152 // expression or the declaration context associated with a prior
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000153 // nested-name-specifier.
John McCall27b18f82009-11-17 02:14:36 +0000154 LookupQualifiedName(Found, LookupCtx);
Mike Stump11289f42009-09-09 15:08:12 +0000155
John McCall27b18f82009-11-17 02:14:36 +0000156 if (ObjectTypePtr && Found.empty()) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000157 // C++ [basic.lookup.classref]p1:
158 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump11289f42009-09-09 15:08:12 +0000159 // immediately followed by an identifier followed by a <, the
160 // identifier must be looked up to determine whether the < is the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000161 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump11289f42009-09-09 15:08:12 +0000162 // The identifier is first looked up in the class of the object
163 // expression. If the identifier is not found, it is then looked up in
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000164 // the context of the entire postfix-expression and shall name a class
165 // or function template.
166 //
167 // FIXME: When we're instantiating a template, do we actually have to
168 // look in the scope of the template? Seems fishy...
John McCall27b18f82009-11-17 02:14:36 +0000169 LookupName(Found, S);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000170 ObjectTypeSearchedInScope = true;
171 }
172 } else if (isDependent) {
Mike Stump11289f42009-09-09 15:08:12 +0000173 // We cannot look into a dependent object type or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000174 return TNK_Non_template;
175 } else {
176 // Perform unqualified name lookup in the current scope.
John McCall27b18f82009-11-17 02:14:36 +0000177 LookupName(Found, S);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000178 }
Mike Stump11289f42009-09-09 15:08:12 +0000179
Douglas Gregore861bac2009-08-25 22:51:20 +0000180 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump11289f42009-09-09 15:08:12 +0000181 assert(!Found.isAmbiguous() &&
Douglas Gregore861bac2009-08-25 22:51:20 +0000182 "Cannot handle template name-lookup ambiguities");
Douglas Gregordc572a32009-03-30 22:58:21 +0000183
John McCall9f3059a2009-10-09 21:13:30 +0000184 NamedDecl *Template
185 = isAcceptableTemplateName(Context, Found.getAsSingleDecl(Context));
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000186 if (!Template)
187 return TNK_Non_template;
188
189 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
190 // C++ [basic.lookup.classref]p1:
Mike Stump11289f42009-09-09 15:08:12 +0000191 // [...] If the lookup in the class of the object expression finds a
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000192 // template, the name is also looked up in the context of the entire
193 // postfix-expression and [...]
194 //
John McCall27b18f82009-11-17 02:14:36 +0000195 LookupResult FoundOuter(*this, TName, SourceLocation(), LookupOrdinaryName);
196 LookupName(FoundOuter, S);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000197 // FIXME: Handle ambiguities in this lookup better
John McCall9f3059a2009-10-09 21:13:30 +0000198 NamedDecl *OuterTemplate
199 = isAcceptableTemplateName(Context, FoundOuter.getAsSingleDecl(Context));
Mike Stump11289f42009-09-09 15:08:12 +0000200
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000201 if (!OuterTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +0000202 // - if the name is not found, the name found in the class of the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000203 // object expression is used, otherwise
204 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump11289f42009-09-09 15:08:12 +0000205 // - if the name is found in the context of the entire
206 // postfix-expression and does not name a class template, the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000207 // found in the class of the object expression is used, otherwise
208 } else {
209 // - if the name found is a class template, it must refer to the same
Mike Stump11289f42009-09-09 15:08:12 +0000210 // entity as the one found in the class of the object expression,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000211 // otherwise the program is ill-formed.
212 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
Douglas Gregor3cf81312009-11-03 23:16:33 +0000213 Diag(Name.getSourceRange().getBegin(),
214 diag::err_nested_name_member_ref_lookup_ambiguous)
215 << TName
216 << Name.getSourceRange();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000217 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
218 << QualType::getFromOpaquePtr(ObjectTypePtr);
219 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump11289f42009-09-09 15:08:12 +0000220
221 // Recover by taking the template that we found in the object
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000222 // expression's type.
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000223 }
Mike Stump11289f42009-09-09 15:08:12 +0000224 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000225 }
Mike Stump11289f42009-09-09 15:08:12 +0000226
Douglas Gregor3cf81312009-11-03 23:16:33 +0000227 if (SS.isSet() && !SS.isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000228 NestedNameSpecifier *Qualifier
Douglas Gregor3cf81312009-11-03 23:16:33 +0000229 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000230 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000231 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000232 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000233 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
234 Ovl));
235 else
Mike Stump11289f42009-09-09 15:08:12 +0000236 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000237 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000238 cast<TemplateDecl>(Template)));
239 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000240 = dyn_cast<OverloadedFunctionDecl>(Template)) {
241 TemplateResult = TemplateTy::make(TemplateName(Ovl));
242 } else {
243 TemplateResult = TemplateTy::make(
244 TemplateName(cast<TemplateDecl>(Template)));
245 }
Mike Stump11289f42009-09-09 15:08:12 +0000246
247 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000248 isa<TemplateTemplateParmDecl>(Template))
249 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000250
251 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000252 isa<OverloadedFunctionDecl>(Template)) &&
253 "Unhandled template kind in Sema::isTemplateName");
254 return TNK_Function_template;
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000255}
256
Douglas Gregor5101c242008-12-05 18:15:24 +0000257/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
258/// that the template parameter 'PrevDecl' is being shadowed by a new
259/// declaration at location Loc. Returns true to indicate that this is
260/// an error, and false otherwise.
261bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000262 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000263
264 // Microsoft Visual C++ permits template parameters to be shadowed.
265 if (getLangOptions().Microsoft)
266 return false;
267
268 // C++ [temp.local]p4:
269 // A template-parameter shall not be redeclared within its
270 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000271 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000272 << cast<NamedDecl>(PrevDecl)->getDeclName();
273 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
274 return true;
275}
276
Douglas Gregor463421d2009-03-03 04:44:36 +0000277/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000278/// the parameter D to reference the templated declaration and return a pointer
279/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000280TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000281 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000282 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000283 return Temp;
284 }
285 return 0;
286}
287
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000288static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
289 const ParsedTemplateArgument &Arg) {
290
291 switch (Arg.getKind()) {
292 case ParsedTemplateArgument::Type: {
293 DeclaratorInfo *DI;
294 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
295 if (!DI)
296 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation());
297 return TemplateArgumentLoc(TemplateArgument(T), DI);
298 }
299
300 case ParsedTemplateArgument::NonType: {
301 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
302 return TemplateArgumentLoc(TemplateArgument(E), E);
303 }
304
305 case ParsedTemplateArgument::Template: {
306 TemplateName Template
307 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
308 return TemplateArgumentLoc(TemplateArgument(Template),
309 Arg.getScopeSpec().getRange(),
310 Arg.getLocation());
311 }
312 }
313
314 llvm::llvm_unreachable("Unhandled parsed template argument");
315 return TemplateArgumentLoc();
316}
317
318/// \brief Translates template arguments as provided by the parser
319/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000320void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
321 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000322 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000323 TemplateArgs.addArgument(translateTemplateArgument(*this,
324 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000325}
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
Douglas Gregore62e6a02009-11-11 19:13:48 +0000569 // Check only that we have a template template argument. We don't want to
570 // try to check well-formedness now, because our template template parameter
571 // might have dependent types in its template parameters, which we wouldn't
572 // be able to match now.
573 //
574 // If none of the template template parameter's template arguments mention
575 // other template parameters, we could actually perform more checking here.
576 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000577 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000578 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
579 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
580 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000581 return;
582 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000583
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000584 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000585}
586
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000587/// ActOnTemplateParameterList - Builds a TemplateParameterList that
588/// contains the template parameters in Params/NumParams.
589Sema::TemplateParamsTy *
590Sema::ActOnTemplateParameterList(unsigned Depth,
591 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000592 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000593 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000594 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000595 SourceLocation RAngleLoc) {
596 if (ExportLoc.isValid())
597 Diag(ExportLoc, diag::note_template_export_unsupported);
598
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000599 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000600 (NamedDecl**)Params, NumParams,
601 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000602}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000603
Douglas Gregorc08f4892009-03-25 00:13:59 +0000604Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000605Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000606 SourceLocation KWLoc, const CXXScopeSpec &SS,
607 IdentifierInfo *Name, SourceLocation NameLoc,
608 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000609 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000610 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000611 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000612 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000613 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000614 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000615
616 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000617 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000618 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000619
John McCall27b5c252009-09-14 21:59:20 +0000620 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
621 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000622
623 // There is no such thing as an unnamed class template.
624 if (!Name) {
625 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000626 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000627 }
628
629 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000630 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000631 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000632 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000633 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000634 if (RequireCompleteDeclContext(SS))
635 return true;
636
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000637 SemanticContext = computeDeclContext(SS, true);
638 if (!SemanticContext) {
639 // FIXME: Produce a reasonable diagnostic here
640 return true;
641 }
Mike Stump11289f42009-09-09 15:08:12 +0000642
John McCall27b18f82009-11-17 02:14:36 +0000643 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000644 } else {
645 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000646 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000647 }
Mike Stump11289f42009-09-09 15:08:12 +0000648
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000649 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
650 NamedDecl *PrevDecl = 0;
651 if (Previous.begin() != Previous.end())
652 PrevDecl = *Previous.begin();
653
Douglas Gregor9acb6902009-09-26 07:05:09 +0000654 if (PrevDecl && TUK == TUK_Friend) {
655 // C++ [namespace.memdef]p3:
656 // [...] When looking for a prior declaration of a class or a function
657 // declared as a friend, and when the name of the friend class or
658 // function is neither a qualified name nor a template-id, scopes outside
659 // the innermost enclosing namespace scope are not considered.
660 DeclContext *OutermostContext = CurContext;
661 while (!OutermostContext->isFileContext())
662 OutermostContext = OutermostContext->getLookupParent();
663
664 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
665 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
666 SemanticContext = PrevDecl->getDeclContext();
667 } else {
668 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000669 // context we computed is the semantic context for our new
Douglas Gregor9acb6902009-09-26 07:05:09 +0000670 // declaration.
671 PrevDecl = 0;
672 SemanticContext = OutermostContext;
673 }
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000674
675 if (CurContext->isDependentContext()) {
676 // If this is a dependent context, we don't want to link the friend
677 // class template to the template in scope, because that would perform
678 // checking of the template parameter lists that can't be performed
679 // until the outer context is instantiated.
680 PrevDecl = 0;
681 }
Douglas Gregor9acb6902009-09-26 07:05:09 +0000682 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000683 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000684
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000685 // If there is a previous declaration with the same name, check
686 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000687 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000688 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000689
690 // We may have found the injected-class-name of a class template,
691 // class template partial specialization, or class template specialization.
692 // In these cases, grab the template that is being defined or specialized.
693 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
694 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
695 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
696 PrevClassTemplate
697 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
698 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
699 PrevClassTemplate
700 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
701 ->getSpecializedTemplate();
702 }
703 }
704
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000705 if (PrevClassTemplate) {
706 // Ensure that the template parameter lists are compatible.
707 if (!TemplateParameterListsAreEqual(TemplateParams,
708 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000709 /*Complain=*/true,
710 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000711 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000712
713 // C++ [temp.class]p4:
714 // In a redeclaration, partial specialization, explicit
715 // specialization or explicit instantiation of a class template,
716 // the class-key shall agree in kind with the original class
717 // template declaration (7.1.5.3).
718 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000719 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000720 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000721 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000722 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000723 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000724 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000725 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000726 }
727
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000728 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000729 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000730 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
731 Diag(NameLoc, diag::err_redefinition) << Name;
732 Diag(Def->getLocation(), diag::note_previous_definition);
733 // FIXME: Would it make sense to try to "forget" the previous
734 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000735 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000736 }
737 }
738 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
739 // Maybe we will complain about the shadowed template parameter.
740 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
741 // Just pretend that we didn't see the previous declaration.
742 PrevDecl = 0;
743 } else if (PrevDecl) {
744 // C++ [temp]p5:
745 // A class template shall not have the same name as any other
746 // template, class, function, object, enumeration, enumerator,
747 // namespace, or type in the same scope (3.3), except as specified
748 // in (14.5.4).
749 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
750 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000751 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000752 }
753
Douglas Gregordba32632009-02-10 19:49:53 +0000754 // Check the template parameter list of this declaration, possibly
755 // merging in the template parameter list from the previous class
756 // template declaration.
757 if (CheckTemplateParameterList(TemplateParams,
758 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
759 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000760
Douglas Gregore362cea2009-05-10 22:57:19 +0000761 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000762 // declaration!
763
Mike Stump11289f42009-09-09 15:08:12 +0000764 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000765 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000766 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000767 PrevClassTemplate->getTemplatedDecl() : 0,
768 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000769
770 ClassTemplateDecl *NewTemplate
771 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
772 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000773 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000774 NewClass->setDescribedClassTemplate(NewTemplate);
775
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000776 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000777 QualType T =
778 Context.getTypeDeclType(NewClass,
779 PrevClassTemplate?
780 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000781 assert(T->isDependentType() && "Class template type is not dependent?");
782 (void)T;
783
Douglas Gregorcf915552009-10-13 16:30:37 +0000784 // If we are providing an explicit specialization of a member that is a
785 // class template, make a note of that.
786 if (PrevClassTemplate &&
787 PrevClassTemplate->getInstantiatedFromMemberTemplate())
788 PrevClassTemplate->setMemberSpecialization();
789
Anders Carlsson137108d2009-03-26 01:24:28 +0000790 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000791 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000792 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000793
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000794 // Set the lexical context of these templates
795 NewClass->setLexicalDeclContext(CurContext);
796 NewTemplate->setLexicalDeclContext(CurContext);
797
John McCall9bb74a52009-07-31 02:45:11 +0000798 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000799 NewClass->startDefinition();
800
801 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000802 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000803
John McCall27b5c252009-09-14 21:59:20 +0000804 if (TUK != TUK_Friend)
805 PushOnScopeChains(NewTemplate, S);
806 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000807 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000808 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000809 NewClass->setAccess(PrevClassTemplate->getAccess());
810 }
John McCall27b5c252009-09-14 21:59:20 +0000811
Douglas Gregor3dad8422009-09-26 06:47:28 +0000812 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
813 PrevClassTemplate != NULL);
814
John McCall27b5c252009-09-14 21:59:20 +0000815 // Friend templates are visible in fairly strange ways.
816 if (!CurContext->isDependentContext()) {
817 DeclContext *DC = SemanticContext->getLookupContext();
818 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
819 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
820 PushOnScopeChains(NewTemplate, EnclosingScope,
821 /* AddToContext = */ false);
822 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000823
824 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
825 NewClass->getLocation(),
826 NewTemplate,
827 /*FIXME:*/NewClass->getLocation());
828 Friend->setAccess(AS_public);
829 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000830 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000831
Douglas Gregordba32632009-02-10 19:49:53 +0000832 if (Invalid) {
833 NewTemplate->setInvalidDecl();
834 NewClass->setInvalidDecl();
835 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000836 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000837}
838
Douglas Gregordba32632009-02-10 19:49:53 +0000839/// \brief Checks the validity of a template parameter list, possibly
840/// considering the template parameter list from a previous
841/// declaration.
842///
843/// If an "old" template parameter list is provided, it must be
844/// equivalent (per TemplateParameterListsAreEqual) to the "new"
845/// template parameter list.
846///
847/// \param NewParams Template parameter list for a new template
848/// declaration. This template parameter list will be updated with any
849/// default arguments that are carried through from the previous
850/// template parameter list.
851///
852/// \param OldParams If provided, template parameter list from a
853/// previous declaration of the same template. Default template
854/// arguments will be merged from the old template parameter list to
855/// the new template parameter list.
856///
857/// \returns true if an error occurred, false otherwise.
858bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
859 TemplateParameterList *OldParams) {
860 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000861
Douglas Gregordba32632009-02-10 19:49:53 +0000862 // C++ [temp.param]p10:
863 // The set of default template-arguments available for use with a
864 // template declaration or definition is obtained by merging the
865 // default arguments from the definition (if in scope) and all
866 // declarations in scope in the same way default function
867 // arguments are (8.3.6).
868 bool SawDefaultArgument = false;
869 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000870
Anders Carlsson327865d2009-06-12 23:20:15 +0000871 bool SawParameterPack = false;
872 SourceLocation ParameterPackLoc;
873
Mike Stumpc89c8e32009-02-11 23:03:27 +0000874 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000875 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000876 if (OldParams)
877 OldParam = OldParams->begin();
878
879 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
880 NewParamEnd = NewParams->end();
881 NewParam != NewParamEnd; ++NewParam) {
882 // Variables used to diagnose redundant default arguments
883 bool RedundantDefaultArg = false;
884 SourceLocation OldDefaultLoc;
885 SourceLocation NewDefaultLoc;
886
887 // Variables used to diagnose missing default arguments
888 bool MissingDefaultArg = false;
889
Anders Carlsson327865d2009-06-12 23:20:15 +0000890 // C++0x [temp.param]p11:
891 // If a template parameter of a class template is a template parameter pack,
892 // it must be the last template parameter.
893 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +0000894 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +0000895 diag::err_template_param_pack_must_be_last_template_parameter);
896 Invalid = true;
897 }
898
Douglas Gregordba32632009-02-10 19:49:53 +0000899 // Merge default arguments for template type parameters.
900 if (TemplateTypeParmDecl *NewTypeParm
901 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump11289f42009-09-09 15:08:12 +0000902 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000903 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000904
Anders Carlsson327865d2009-06-12 23:20:15 +0000905 if (NewTypeParm->isParameterPack()) {
906 assert(!NewTypeParm->hasDefaultArgument() &&
907 "Parameter packs can't have a default argument!");
908 SawParameterPack = true;
909 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000910 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +0000911 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +0000912 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
913 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
914 SawDefaultArgument = true;
915 RedundantDefaultArg = true;
916 PreviousDefaultArgLoc = NewDefaultLoc;
917 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
918 // Merge the default argument from the old declaration to the
919 // new declaration.
920 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +0000921 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +0000922 true);
923 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
924 } else if (NewTypeParm->hasDefaultArgument()) {
925 SawDefaultArgument = true;
926 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
927 } else if (SawDefaultArgument)
928 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000929 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000930 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000931 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000932 NonTypeTemplateParmDecl *OldNonTypeParm
933 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000934 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000935 NewNonTypeParm->hasDefaultArgument()) {
936 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
937 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
938 SawDefaultArgument = true;
939 RedundantDefaultArg = true;
940 PreviousDefaultArgLoc = NewDefaultLoc;
941 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
942 // Merge the default argument from the old declaration to the
943 // new declaration.
944 SawDefaultArgument = true;
945 // FIXME: We need to create a new kind of "default argument"
946 // expression that points to a previous template template
947 // parameter.
948 NewNonTypeParm->setDefaultArgument(
949 OldNonTypeParm->getDefaultArgument());
950 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
951 } else if (NewNonTypeParm->hasDefaultArgument()) {
952 SawDefaultArgument = true;
953 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
954 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000955 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000956 } else {
Douglas Gregordba32632009-02-10 19:49:53 +0000957 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000958 TemplateTemplateParmDecl *NewTemplateParm
959 = cast<TemplateTemplateParmDecl>(*NewParam);
960 TemplateTemplateParmDecl *OldTemplateParm
961 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000962 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000963 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000964 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
965 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +0000966 SawDefaultArgument = true;
967 RedundantDefaultArg = true;
968 PreviousDefaultArgLoc = NewDefaultLoc;
969 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
970 // Merge the default argument from the old declaration to the
971 // new declaration.
972 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +0000973 // FIXME: We need to create a new kind of "default argument" expression
974 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +0000975 NewTemplateParm->setDefaultArgument(
976 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000977 PreviousDefaultArgLoc
978 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +0000979 } else if (NewTemplateParm->hasDefaultArgument()) {
980 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000981 PreviousDefaultArgLoc
982 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +0000983 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000984 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +0000985 }
986
987 if (RedundantDefaultArg) {
988 // C++ [temp.param]p12:
989 // A template-parameter shall not be given default arguments
990 // by two different declarations in the same scope.
991 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
992 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
993 Invalid = true;
994 } else if (MissingDefaultArg) {
995 // C++ [temp.param]p11:
996 // If a template-parameter has a default template-argument,
997 // all subsequent template-parameters shall have a default
998 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +0000999 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001000 diag::err_template_param_default_arg_missing);
1001 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1002 Invalid = true;
1003 }
1004
1005 // If we have an old template parameter list that we're merging
1006 // in, move on to the next parameter.
1007 if (OldParams)
1008 ++OldParam;
1009 }
1010
1011 return Invalid;
1012}
Douglas Gregord32e0282009-02-09 23:23:08 +00001013
Mike Stump11289f42009-09-09 15:08:12 +00001014/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001015/// specifier, returning the template parameter list that applies to the
1016/// name.
1017///
1018/// \param DeclStartLoc the start of the declaration that has a scope
1019/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001020///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001021/// \param SS the scope specifier that will be matched to the given template
1022/// parameter lists. This scope specifier precedes a qualified name that is
1023/// being declared.
1024///
1025/// \param ParamLists the template parameter lists, from the outermost to the
1026/// innermost template parameter lists.
1027///
1028/// \param NumParamLists the number of template parameter lists in ParamLists.
1029///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001030/// \param IsExplicitSpecialization will be set true if the entity being
1031/// declared is an explicit specialization, false otherwise.
1032///
Mike Stump11289f42009-09-09 15:08:12 +00001033/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001034/// name that is preceded by the scope specifier @p SS. This template
1035/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001036/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001037/// template specialization), or may be NULL (if we were's declaring isn't
1038/// itself a template).
1039TemplateParameterList *
1040Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1041 const CXXScopeSpec &SS,
1042 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001043 unsigned NumParamLists,
1044 bool &IsExplicitSpecialization) {
1045 IsExplicitSpecialization = false;
1046
Douglas Gregord8d297c2009-07-21 23:53:31 +00001047 // Find the template-ids that occur within the nested-name-specifier. These
1048 // template-ids will match up with the template parameter lists.
1049 llvm::SmallVector<const TemplateSpecializationType *, 4>
1050 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001051 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1052 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001053 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1054 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +00001055 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +00001056 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1057 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1058 if (!Template)
1059 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001060
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001061 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001062 ClassTemplateSpecializationDecl *SpecDecl
1063 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1064 // If the nested name specifier refers to an explicit specialization,
1065 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001066 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1067 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001068 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001069 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001070 }
Mike Stump11289f42009-09-09 15:08:12 +00001071
Douglas Gregord8d297c2009-07-21 23:53:31 +00001072 TemplateIdsInSpecifier.push_back(SpecType);
1073 }
1074 }
Mike Stump11289f42009-09-09 15:08:12 +00001075
Douglas Gregord8d297c2009-07-21 23:53:31 +00001076 // Reverse the list of template-ids in the scope specifier, so that we can
1077 // more easily match up the template-ids and the template parameter lists.
1078 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001079
Douglas Gregord8d297c2009-07-21 23:53:31 +00001080 SourceLocation FirstTemplateLoc = DeclStartLoc;
1081 if (NumParamLists)
1082 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001083
Douglas Gregord8d297c2009-07-21 23:53:31 +00001084 // Match the template-ids found in the specifier to the template parameter
1085 // lists.
1086 unsigned Idx = 0;
1087 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1088 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001089 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1090 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001091 if (Idx >= NumParamLists) {
1092 // We have a template-id without a corresponding template parameter
1093 // list.
1094 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001095 // FIXME: the location information here isn't great.
1096 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001097 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001098 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001099 << SS.getRange();
1100 } else {
1101 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1102 << SS.getRange()
1103 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1104 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001105 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001106 }
1107 return 0;
1108 }
Mike Stump11289f42009-09-09 15:08:12 +00001109
Douglas Gregord8d297c2009-07-21 23:53:31 +00001110 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001111 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001112 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001113 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1114
Mike Stump11289f42009-09-09 15:08:12 +00001115 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001116 = dyn_cast<ClassTemplateDecl>(Template)) {
1117 TemplateParameterList *ExpectedTemplateParams = 0;
1118 // Is this template-id naming the primary template?
1119 if (Context.hasSameType(TemplateId,
1120 ClassTemplate->getInjectedClassNameType(Context)))
1121 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1122 // ... or a partial specialization?
1123 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1124 = ClassTemplate->findPartialSpecialization(TemplateId))
1125 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1126
1127 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001128 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001129 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001130 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001131 }
Douglas Gregor15301382009-07-30 17:40:51 +00001132 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001133 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001134 diag::err_template_param_list_matches_nontemplate)
1135 << TemplateId
1136 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001137 else
1138 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001139 }
Mike Stump11289f42009-09-09 15:08:12 +00001140
Douglas Gregord8d297c2009-07-21 23:53:31 +00001141 // If there were at least as many template-ids as there were template
1142 // parameter lists, then there are no template parameter lists remaining for
1143 // the declaration itself.
1144 if (Idx >= NumParamLists)
1145 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001146
Douglas Gregord8d297c2009-07-21 23:53:31 +00001147 // If there were too many template parameter lists, complain about that now.
1148 if (Idx != NumParamLists - 1) {
1149 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001150 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001151 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001152 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1153 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001154 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1155 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001156
1157 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1158 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1159 diag::note_explicit_template_spec_does_not_need_header)
1160 << ExplicitSpecializationsInSpecifier.back();
1161 ExplicitSpecializationsInSpecifier.pop_back();
1162 }
1163
Douglas Gregord8d297c2009-07-21 23:53:31 +00001164 ++Idx;
1165 }
1166 }
Mike Stump11289f42009-09-09 15:08:12 +00001167
Douglas Gregord8d297c2009-07-21 23:53:31 +00001168 // Return the last template parameter list, which corresponds to the
1169 // entity being declared.
1170 return ParamLists[NumParamLists - 1];
1171}
1172
Douglas Gregordc572a32009-03-30 22:58:21 +00001173QualType Sema::CheckTemplateIdType(TemplateName Name,
1174 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001175 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001176 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001177 if (!Template) {
1178 // The template name does not resolve to a template, so we just
1179 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001180 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001181 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001182
Douglas Gregorc40290e2009-03-09 23:48:35 +00001183 // Check that the template argument list is well-formed for this
1184 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001185 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001186 TemplateArgs.size());
1187 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001188 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001189 return QualType();
1190
Mike Stump11289f42009-09-09 15:08:12 +00001191 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001192 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001193 "Converted template argument list is too short!");
1194
1195 QualType CanonType;
1196
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001197 if (Name.isDependent() ||
1198 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001199 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001200 // This class template specialization is a dependent
1201 // type. Therefore, its canonical type is another class template
1202 // specialization type that contains all of the converted
1203 // arguments in canonical form. This ensures that, e.g., A<T> and
1204 // A<T, T> have identical types when A is declared as:
1205 //
1206 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001207 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001208 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001209 Converted.getFlatArguments(),
1210 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001211
Douglas Gregora8e02e72009-07-28 23:00:59 +00001212 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001213 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001214 // In the future, we need to teach getTemplateSpecializationType to only
1215 // build the canonical type and return that to us.
1216 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001217 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001218 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001219 // Find the class template specialization declaration that
1220 // corresponds to these arguments.
1221 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001222 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001223 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001224 Converted.flatSize(),
1225 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001226 void *InsertPos = 0;
1227 ClassTemplateSpecializationDecl *Decl
1228 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1229 if (!Decl) {
1230 // This is the first time we have referenced this class template
1231 // specialization. Create the canonical declaration and add it to
1232 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001233 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001234 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001235 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001236 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001237 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001238 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1239 Decl->setLexicalDeclContext(CurContext);
1240 }
1241
1242 CanonType = Context.getTypeDeclType(Decl);
1243 }
Mike Stump11289f42009-09-09 15:08:12 +00001244
Douglas Gregorc40290e2009-03-09 23:48:35 +00001245 // Build the fully-sugared type for this class template
1246 // specialization, which refers back to the class template
1247 // specialization we created or found.
John McCall6b51f282009-11-23 01:53:49 +00001248 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001249}
1250
Douglas Gregor67a65642009-02-17 23:15:12 +00001251Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001252Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001253 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001254 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001255 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001256 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001257
Douglas Gregorc40290e2009-03-09 23:48:35 +00001258 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001259 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001260 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001261
John McCall6b51f282009-11-23 01:53:49 +00001262 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001263 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001264
1265 if (Result.isNull())
1266 return true;
1267
John McCall0ad16662009-10-29 08:12:44 +00001268 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1269 TemplateSpecializationTypeLoc TL
1270 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1271 TL.setTemplateNameLoc(TemplateLoc);
1272 TL.setLAngleLoc(LAngleLoc);
1273 TL.setRAngleLoc(RAngleLoc);
1274 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1275 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1276
1277 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001278}
John McCall06f6fe8d2009-09-04 01:14:41 +00001279
John McCalld8fe9af2009-09-08 17:47:29 +00001280Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1281 TagUseKind TUK,
1282 DeclSpec::TST TagSpec,
1283 SourceLocation TagLoc) {
1284 if (TypeResult.isInvalid())
1285 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001286
John McCall0ad16662009-10-29 08:12:44 +00001287 // FIXME: preserve source info, ideally without copying the DI.
1288 DeclaratorInfo *DI;
1289 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001290
John McCalld8fe9af2009-09-08 17:47:29 +00001291 // Verify the tag specifier.
1292 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001293
John McCalld8fe9af2009-09-08 17:47:29 +00001294 if (const RecordType *RT = Type->getAs<RecordType>()) {
1295 RecordDecl *D = RT->getDecl();
1296
1297 IdentifierInfo *Id = D->getIdentifier();
1298 assert(Id && "templated class must have an identifier");
1299
1300 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1301 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001302 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001303 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1304 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001305 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001306 }
1307 }
1308
John McCalld8fe9af2009-09-08 17:47:29 +00001309 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1310
1311 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001312}
1313
Douglas Gregord019ff62009-10-22 17:20:55 +00001314Sema::OwningExprResult Sema::BuildTemplateIdExpr(NestedNameSpecifier *Qualifier,
1315 SourceRange QualifierRange,
1316 TemplateName Template,
Douglas Gregora727cb92009-06-30 22:34:41 +00001317 SourceLocation TemplateNameLoc,
John McCall6b51f282009-11-23 01:53:49 +00001318 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001319 // FIXME: Can we do any checking at this point? I guess we could check the
1320 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001321 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001322 // though.
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001323
1324 // Cope with an implicit member access in a C++ non-static member function.
1325 NamedDecl *D = Template.getAsTemplateDecl();
1326 if (!D)
1327 D = Template.getAsOverloadedFunctionDecl();
1328
Douglas Gregord019ff62009-10-22 17:20:55 +00001329 CXXScopeSpec SS;
1330 SS.setRange(QualifierRange);
1331 SS.setScopeRep(Qualifier);
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001332 QualType ThisType, MemberType;
Douglas Gregord019ff62009-10-22 17:20:55 +00001333 if (D && isImplicitMemberReference(&SS, D, TemplateNameLoc,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001334 ThisType, MemberType)) {
1335 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
1336 return Owned(MemberExpr::Create(Context, This, true,
Douglas Gregord019ff62009-10-22 17:20:55 +00001337 Qualifier, QualifierRange,
John McCall6b51f282009-11-23 01:53:49 +00001338 D, TemplateNameLoc, &TemplateArgs,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001339 Context.OverloadTy));
1340 }
1341
Douglas Gregord019ff62009-10-22 17:20:55 +00001342 return Owned(TemplateIdRefExpr::Create(Context, Context.OverloadTy,
1343 Qualifier, QualifierRange,
John McCall6b51f282009-11-23 01:53:49 +00001344 Template, TemplateNameLoc,
1345 TemplateArgs));
Douglas Gregora727cb92009-06-30 22:34:41 +00001346}
1347
Douglas Gregord019ff62009-10-22 17:20:55 +00001348Sema::OwningExprResult Sema::ActOnTemplateIdExpr(const CXXScopeSpec &SS,
1349 TemplateTy TemplateD,
Douglas Gregora727cb92009-06-30 22:34:41 +00001350 SourceLocation TemplateNameLoc,
1351 SourceLocation LAngleLoc,
1352 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora727cb92009-06-30 22:34:41 +00001353 SourceLocation RAngleLoc) {
1354 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001355
Douglas Gregora727cb92009-06-30 22:34:41 +00001356 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001357 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001358 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001359 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001360
Douglas Gregord019ff62009-10-22 17:20:55 +00001361 return BuildTemplateIdExpr((NestedNameSpecifier *)SS.getScopeRep(),
1362 SS.getRange(),
John McCall6b51f282009-11-23 01:53:49 +00001363 Template, TemplateNameLoc, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001364}
1365
Douglas Gregorb67535d2009-03-31 00:43:58 +00001366/// \brief Form a dependent template name.
1367///
1368/// This action forms a dependent template name given the template
1369/// name and its (presumably dependent) scope specifier. For
1370/// example, given "MetaFun::template apply", the scope specifier \p
1371/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1372/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001373Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001374Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001375 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001376 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001377 TypeTy *ObjectType,
1378 bool EnteringContext) {
Mike Stump11289f42009-09-09 15:08:12 +00001379 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001380 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001381 (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001382 // C++0x [temp.names]p5:
1383 // If a name prefixed by the keyword template is not the name of
1384 // a template, the program is ill-formed. [Note: the keyword
1385 // template may not be applied to non-template members of class
1386 // templates. -end note ] [ Note: as is the case with the
1387 // typename prefix, the template prefix is allowed in cases
1388 // where it is not strictly necessary; i.e., when the
1389 // nested-name-specifier or the expression on the left of the ->
1390 // or . is not dependent on a template-parameter, or the use
1391 // does not appear in the scope of a template. -end note]
1392 //
1393 // Note: C++03 was more strict here, because it banned the use of
1394 // the "template" keyword prior to a template-name that was not a
1395 // dependent name. C++ DR468 relaxed this requirement (the
1396 // "template" keyword is now permitted). We follow the C++0x
1397 // rules, even in C++03 mode, retroactively applying the DR.
1398 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001399 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001400 EnteringContext, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001401 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001402 Diag(Name.getSourceRange().getBegin(),
1403 diag::err_template_kw_refers_to_non_template)
1404 << GetNameFromUnqualifiedId(Name)
1405 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001406 return TemplateTy();
1407 }
1408
1409 return Template;
1410 }
1411
Mike Stump11289f42009-09-09 15:08:12 +00001412 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001413 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001414
1415 switch (Name.getKind()) {
1416 case UnqualifiedId::IK_Identifier:
1417 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1418 Name.Identifier));
1419
Douglas Gregor71395fa2009-11-04 00:56:37 +00001420 case UnqualifiedId::IK_OperatorFunctionId:
1421 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1422 Name.OperatorFunctionId.Operator));
1423
Douglas Gregor3cf81312009-11-03 23:16:33 +00001424 default:
1425 break;
1426 }
1427
1428 Diag(Name.getSourceRange().getBegin(),
1429 diag::err_template_kw_refers_to_non_template)
1430 << GetNameFromUnqualifiedId(Name)
1431 << Name.getSourceRange();
1432 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001433}
1434
Mike Stump11289f42009-09-09 15:08:12 +00001435bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001436 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001437 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001438 const TemplateArgument &Arg = AL.getArgument();
1439
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001440 // Check template type parameter.
1441 if (Arg.getKind() != TemplateArgument::Type) {
1442 // C++ [temp.arg.type]p1:
1443 // A template-argument for a template-parameter which is a
1444 // type shall be a type-id.
1445
1446 // We have a template type parameter but the template argument
1447 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001448 SourceRange SR = AL.getSourceRange();
1449 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001450 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001451
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001452 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001453 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001454
John McCall0ad16662009-10-29 08:12:44 +00001455 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001456 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001457
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001458 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001459 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001460 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001461 return false;
1462}
1463
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001464/// \brief Substitute template arguments into the default template argument for
1465/// the given template type parameter.
1466///
1467/// \param SemaRef the semantic analysis object for which we are performing
1468/// the substitution.
1469///
1470/// \param Template the template that we are synthesizing template arguments
1471/// for.
1472///
1473/// \param TemplateLoc the location of the template name that started the
1474/// template-id we are checking.
1475///
1476/// \param RAngleLoc the location of the right angle bracket ('>') that
1477/// terminates the template-id.
1478///
1479/// \param Param the template template parameter whose default we are
1480/// substituting into.
1481///
1482/// \param Converted the list of template arguments provided for template
1483/// parameters that precede \p Param in the template parameter list.
1484///
1485/// \returns the substituted template argument, or NULL if an error occurred.
1486static DeclaratorInfo *
1487SubstDefaultTemplateArgument(Sema &SemaRef,
1488 TemplateDecl *Template,
1489 SourceLocation TemplateLoc,
1490 SourceLocation RAngleLoc,
1491 TemplateTypeParmDecl *Param,
1492 TemplateArgumentListBuilder &Converted) {
1493 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1494
1495 // If the argument type is dependent, instantiate it now based
1496 // on the previously-computed template arguments.
1497 if (ArgType->getType()->isDependentType()) {
1498 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1499 /*TakeArgs=*/false);
1500
1501 MultiLevelTemplateArgumentList AllTemplateArgs
1502 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1503
1504 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1505 Template, Converted.getFlatArguments(),
1506 Converted.flatSize(),
1507 SourceRange(TemplateLoc, RAngleLoc));
1508
1509 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1510 Param->getDefaultArgumentLoc(),
1511 Param->getDeclName());
1512 }
1513
1514 return ArgType;
1515}
1516
1517/// \brief Substitute template arguments into the default template argument for
1518/// the given non-type template parameter.
1519///
1520/// \param SemaRef the semantic analysis object for which we are performing
1521/// the substitution.
1522///
1523/// \param Template the template that we are synthesizing template arguments
1524/// for.
1525///
1526/// \param TemplateLoc the location of the template name that started the
1527/// template-id we are checking.
1528///
1529/// \param RAngleLoc the location of the right angle bracket ('>') that
1530/// terminates the template-id.
1531///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001532/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001533/// substituting into.
1534///
1535/// \param Converted the list of template arguments provided for template
1536/// parameters that precede \p Param in the template parameter list.
1537///
1538/// \returns the substituted template argument, or NULL if an error occurred.
1539static Sema::OwningExprResult
1540SubstDefaultTemplateArgument(Sema &SemaRef,
1541 TemplateDecl *Template,
1542 SourceLocation TemplateLoc,
1543 SourceLocation RAngleLoc,
1544 NonTypeTemplateParmDecl *Param,
1545 TemplateArgumentListBuilder &Converted) {
1546 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1547 /*TakeArgs=*/false);
1548
1549 MultiLevelTemplateArgumentList AllTemplateArgs
1550 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1551
1552 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1553 Template, Converted.getFlatArguments(),
1554 Converted.flatSize(),
1555 SourceRange(TemplateLoc, RAngleLoc));
1556
1557 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1558}
1559
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001560/// \brief Substitute template arguments into the default template argument for
1561/// the given template template parameter.
1562///
1563/// \param SemaRef the semantic analysis object for which we are performing
1564/// the substitution.
1565///
1566/// \param Template the template that we are synthesizing template arguments
1567/// for.
1568///
1569/// \param TemplateLoc the location of the template name that started the
1570/// template-id we are checking.
1571///
1572/// \param RAngleLoc the location of the right angle bracket ('>') that
1573/// terminates the template-id.
1574///
1575/// \param Param the template template parameter whose default we are
1576/// substituting into.
1577///
1578/// \param Converted the list of template arguments provided for template
1579/// parameters that precede \p Param in the template parameter list.
1580///
1581/// \returns the substituted template argument, or NULL if an error occurred.
1582static TemplateName
1583SubstDefaultTemplateArgument(Sema &SemaRef,
1584 TemplateDecl *Template,
1585 SourceLocation TemplateLoc,
1586 SourceLocation RAngleLoc,
1587 TemplateTemplateParmDecl *Param,
1588 TemplateArgumentListBuilder &Converted) {
1589 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1590 /*TakeArgs=*/false);
1591
1592 MultiLevelTemplateArgumentList AllTemplateArgs
1593 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1594
1595 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1596 Template, Converted.getFlatArguments(),
1597 Converted.flatSize(),
1598 SourceRange(TemplateLoc, RAngleLoc));
1599
1600 return SemaRef.SubstTemplateName(
1601 Param->getDefaultArgument().getArgument().getAsTemplate(),
1602 Param->getDefaultArgument().getTemplateNameLoc(),
1603 AllTemplateArgs);
1604}
1605
Douglas Gregorda0fb532009-11-11 19:31:23 +00001606/// \brief Check that the given template argument corresponds to the given
1607/// template parameter.
1608bool Sema::CheckTemplateArgument(NamedDecl *Param,
1609 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001610 TemplateDecl *Template,
1611 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001612 SourceLocation RAngleLoc,
1613 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001614 // Check template type parameters.
1615 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001616 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001617
Douglas Gregoreebed722009-11-11 19:41:09 +00001618 // Check non-type template parameters.
1619 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001620 // Do substitution on the type of the non-type template parameter
1621 // with the template arguments we've seen thus far.
1622 QualType NTTPType = NTTP->getType();
1623 if (NTTPType->isDependentType()) {
1624 // Do substitution on the type of the non-type template parameter.
1625 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1626 NTTP, Converted.getFlatArguments(),
1627 Converted.flatSize(),
1628 SourceRange(TemplateLoc, RAngleLoc));
1629
1630 TemplateArgumentList TemplateArgs(Context, Converted,
1631 /*TakeArgs=*/false);
1632 NTTPType = SubstType(NTTPType,
1633 MultiLevelTemplateArgumentList(TemplateArgs),
1634 NTTP->getLocation(),
1635 NTTP->getDeclName());
1636 // If that worked, check the non-type template parameter type
1637 // for validity.
1638 if (!NTTPType.isNull())
1639 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1640 NTTP->getLocation());
1641 if (NTTPType.isNull())
1642 return true;
1643 }
1644
1645 switch (Arg.getArgument().getKind()) {
1646 case TemplateArgument::Null:
1647 assert(false && "Should never see a NULL template argument here");
1648 return true;
1649
1650 case TemplateArgument::Expression: {
1651 Expr *E = Arg.getArgument().getAsExpr();
1652 TemplateArgument Result;
1653 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1654 return true;
1655
1656 Converted.Append(Result);
1657 break;
1658 }
1659
1660 case TemplateArgument::Declaration:
1661 case TemplateArgument::Integral:
1662 // We've already checked this template argument, so just copy
1663 // it to the list of converted arguments.
1664 Converted.Append(Arg.getArgument());
1665 break;
1666
1667 case TemplateArgument::Template:
1668 // We were given a template template argument. It may not be ill-formed;
1669 // see below.
1670 if (DependentTemplateName *DTN
1671 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1672 // We have a template argument such as \c T::template X, which we
1673 // parsed as a template template argument. However, since we now
1674 // know that we need a non-type template argument, convert this
1675 // template name into an expression.
John McCall8cd78132009-11-19 22:55:06 +00001676 Expr *E = new (Context) DependentScopeDeclRefExpr(DTN->getIdentifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00001677 Context.DependentTy,
1678 Arg.getTemplateNameLoc(),
1679 Arg.getTemplateQualifierRange(),
1680 DTN->getQualifier(),
1681 /*isAddressOfOperand=*/false);
1682
1683 TemplateArgument Result;
1684 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1685 return true;
1686
1687 Converted.Append(Result);
1688 break;
1689 }
1690
1691 // We have a template argument that actually does refer to a class
1692 // template, template alias, or template template parameter, and
1693 // therefore cannot be a non-type template argument.
1694 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1695 << Arg.getSourceRange();
1696
1697 Diag(Param->getLocation(), diag::note_template_param_here);
1698 return true;
1699
1700 case TemplateArgument::Type: {
1701 // We have a non-type template parameter but the template
1702 // argument is a type.
1703
1704 // C++ [temp.arg]p2:
1705 // In a template-argument, an ambiguity between a type-id and
1706 // an expression is resolved to a type-id, regardless of the
1707 // form of the corresponding template-parameter.
1708 //
1709 // We warn specifically about this case, since it can be rather
1710 // confusing for users.
1711 QualType T = Arg.getArgument().getAsType();
1712 SourceRange SR = Arg.getSourceRange();
1713 if (T->isFunctionType())
1714 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1715 else
1716 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1717 Diag(Param->getLocation(), diag::note_template_param_here);
1718 return true;
1719 }
1720
1721 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00001722 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001723 break;
1724 }
1725
1726 return false;
1727 }
1728
1729
1730 // Check template template parameters.
1731 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1732
1733 // Substitute into the template parameter list of the template
1734 // template parameter, since previously-supplied template arguments
1735 // may appear within the template template parameter.
1736 {
1737 // Set up a template instantiation context.
1738 LocalInstantiationScope Scope(*this);
1739 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1740 TempParm, Converted.getFlatArguments(),
1741 Converted.flatSize(),
1742 SourceRange(TemplateLoc, RAngleLoc));
1743
1744 TemplateArgumentList TemplateArgs(Context, Converted,
1745 /*TakeArgs=*/false);
1746 TempParm = cast_or_null<TemplateTemplateParmDecl>(
1747 SubstDecl(TempParm, CurContext,
1748 MultiLevelTemplateArgumentList(TemplateArgs)));
1749 if (!TempParm)
1750 return true;
1751
1752 // FIXME: TempParam is leaked.
1753 }
1754
1755 switch (Arg.getArgument().getKind()) {
1756 case TemplateArgument::Null:
1757 assert(false && "Should never see a NULL template argument here");
1758 return true;
1759
1760 case TemplateArgument::Template:
1761 if (CheckTemplateArgument(TempParm, Arg))
1762 return true;
1763
1764 Converted.Append(Arg.getArgument());
1765 break;
1766
1767 case TemplateArgument::Expression:
1768 case TemplateArgument::Type:
1769 // We have a template template parameter but the template
1770 // argument does not refer to a template.
1771 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1772 return true;
1773
1774 case TemplateArgument::Declaration:
1775 llvm::llvm_unreachable(
1776 "Declaration argument with template template parameter");
1777 break;
1778 case TemplateArgument::Integral:
1779 llvm::llvm_unreachable(
1780 "Integral argument with template template parameter");
1781 break;
1782
1783 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00001784 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001785 break;
1786 }
1787
1788 return false;
1789}
1790
Douglas Gregord32e0282009-02-09 23:23:08 +00001791/// \brief Check that the given template argument list is well-formed
1792/// for specializing the given template.
1793bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1794 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001795 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001796 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001797 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001798 TemplateParameterList *Params = Template->getTemplateParameters();
1799 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00001800 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00001801 bool Invalid = false;
1802
John McCall6b51f282009-11-23 01:53:49 +00001803 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
1804
Mike Stump11289f42009-09-09 15:08:12 +00001805 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001806 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001807
Anders Carlsson15201f12009-06-13 02:08:00 +00001808 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001809 (NumArgs < Params->getMinRequiredArguments() &&
1810 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001811 // FIXME: point at either the first arg beyond what we can handle,
1812 // or the '>', depending on whether we have too many or too few
1813 // arguments.
1814 SourceRange Range;
1815 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001816 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001817 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1818 << (NumArgs > NumParams)
1819 << (isa<ClassTemplateDecl>(Template)? 0 :
1820 isa<FunctionTemplateDecl>(Template)? 1 :
1821 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1822 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001823 Diag(Template->getLocation(), diag::note_template_decl_here)
1824 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001825 Invalid = true;
1826 }
Mike Stump11289f42009-09-09 15:08:12 +00001827
1828 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001829 // [...] The type and form of each template-argument specified in
1830 // a template-id shall match the type and form specified for the
1831 // corresponding parameter declared by the template in its
1832 // template-parameter-list.
1833 unsigned ArgIdx = 0;
1834 for (TemplateParameterList::iterator Param = Params->begin(),
1835 ParamEnd = Params->end();
1836 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001837 if (ArgIdx > NumArgs && PartialTemplateArgs)
1838 break;
Mike Stump11289f42009-09-09 15:08:12 +00001839
Douglas Gregoreebed722009-11-11 19:41:09 +00001840 // If we have a template parameter pack, check every remaining template
1841 // argument against that template parameter pack.
1842 if ((*Param)->isTemplateParameterPack()) {
1843 Converted.BeginPack();
1844 for (; ArgIdx < NumArgs; ++ArgIdx) {
1845 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
1846 TemplateLoc, RAngleLoc, Converted)) {
1847 Invalid = true;
1848 break;
1849 }
1850 }
1851 Converted.EndPack();
1852 continue;
1853 }
1854
Douglas Gregor84d49a22009-11-11 21:54:23 +00001855 if (ArgIdx < NumArgs) {
1856 // Check the template argument we were given.
1857 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
1858 TemplateLoc, RAngleLoc, Converted))
1859 return true;
1860
1861 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001862 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00001863
Douglas Gregor84d49a22009-11-11 21:54:23 +00001864 // We have a default template argument that we will use.
1865 TemplateArgumentLoc Arg;
1866
1867 // Retrieve the default template argument from the template
1868 // parameter. For each kind of template parameter, we substitute the
1869 // template arguments provided thus far and any "outer" template arguments
1870 // (when the template parameter was part of a nested template) into
1871 // the default argument.
1872 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1873 if (!TTP->hasDefaultArgument()) {
1874 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1875 break;
1876 }
1877
1878 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
1879 Template,
1880 TemplateLoc,
1881 RAngleLoc,
1882 TTP,
1883 Converted);
1884 if (!ArgType)
1885 return true;
1886
1887 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
1888 ArgType);
1889 } else if (NonTypeTemplateParmDecl *NTTP
1890 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1891 if (!NTTP->hasDefaultArgument()) {
1892 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1893 break;
1894 }
1895
1896 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
1897 TemplateLoc,
1898 RAngleLoc,
1899 NTTP,
1900 Converted);
1901 if (E.isInvalid())
1902 return true;
1903
1904 Expr *Ex = E.takeAs<Expr>();
1905 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
1906 } else {
1907 TemplateTemplateParmDecl *TempParm
1908 = cast<TemplateTemplateParmDecl>(*Param);
1909
1910 if (!TempParm->hasDefaultArgument()) {
1911 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1912 break;
1913 }
1914
1915 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
1916 TemplateLoc,
1917 RAngleLoc,
1918 TempParm,
1919 Converted);
1920 if (Name.isNull())
1921 return true;
1922
1923 Arg = TemplateArgumentLoc(TemplateArgument(Name),
1924 TempParm->getDefaultArgument().getTemplateQualifierRange(),
1925 TempParm->getDefaultArgument().getTemplateNameLoc());
1926 }
1927
1928 // Introduce an instantiation record that describes where we are using
1929 // the default template argument.
1930 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
1931 Converted.getFlatArguments(),
1932 Converted.flatSize(),
1933 SourceRange(TemplateLoc, RAngleLoc));
1934
1935 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00001936 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001937 RAngleLoc, Converted))
1938 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00001939 }
1940
1941 return Invalid;
1942}
1943
1944/// \brief Check a template argument against its corresponding
1945/// template type parameter.
1946///
1947/// This routine implements the semantics of C++ [temp.arg.type]. It
1948/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001949bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001950 DeclaratorInfo *ArgInfo) {
1951 assert(ArgInfo && "invalid DeclaratorInfo");
1952 QualType Arg = ArgInfo->getType();
1953
Douglas Gregord32e0282009-02-09 23:23:08 +00001954 // C++ [temp.arg.type]p2:
1955 // A local type, a type with no linkage, an unnamed type or a type
1956 // compounded from any of these types shall not be used as a
1957 // template-argument for a template type-parameter.
1958 //
1959 // FIXME: Perform the recursive and no-linkage type checks.
1960 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001961 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001962 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001963 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001964 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00001965 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
1966 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1967 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
1968 << QualType(Tag, 0) << SR;
1969 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001970 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00001971 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1972 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00001973 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1974 return true;
1975 }
1976
1977 return false;
1978}
1979
Douglas Gregorccb07762009-02-11 19:52:55 +00001980/// \brief Checks whether the given template argument is the address
1981/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001982bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1983 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001984 bool Invalid = false;
1985
1986 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00001987 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00001988 Arg = Cast->getSubExpr();
1989
Sebastian Redl576fd422009-05-10 18:38:11 +00001990 // C++0x allows nullptr, and there's no further checking to be done for that.
1991 if (Arg->getType()->isNullPtrType())
1992 return false;
1993
Douglas Gregorccb07762009-02-11 19:52:55 +00001994 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001995 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001996 // A template-argument for a non-type, non-template
1997 // template-parameter shall be one of: [...]
1998 //
1999 // -- the address of an object or function with external
2000 // linkage, including function templates and function
2001 // template-ids but excluding non-static class members,
2002 // expressed as & id-expression where the & is optional if
2003 // the name refers to a function or array, or if the
2004 // corresponding template-parameter is a reference; or
2005 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002006
Douglas Gregorccb07762009-02-11 19:52:55 +00002007 // Ignore (and complain about) any excess parentheses.
2008 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2009 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002010 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002011 diag::err_template_arg_extra_parens)
2012 << Arg->getSourceRange();
2013 Invalid = true;
2014 }
2015
2016 Arg = Parens->getSubExpr();
2017 }
2018
2019 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2020 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2021 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2022 } else
2023 DRE = dyn_cast<DeclRefExpr>(Arg);
2024
2025 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002026 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002027 diag::err_template_arg_not_object_or_func_form)
2028 << Arg->getSourceRange();
2029
2030 // Cannot refer to non-static data members
2031 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2032 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2033 << Field << Arg->getSourceRange();
2034
2035 // Cannot refer to non-static member functions
2036 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2037 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002038 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002039 diag::err_template_arg_method)
2040 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002041
Douglas Gregorccb07762009-02-11 19:52:55 +00002042 // Functions must have external linkage.
2043 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2044 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00002045 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002046 diag::err_template_arg_function_not_extern)
2047 << Func << Arg->getSourceRange();
2048 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2049 << true;
2050 return true;
2051 }
2052
2053 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002054 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002055 return Invalid;
2056 }
2057
2058 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2059 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00002060 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002061 diag::err_template_arg_object_not_extern)
2062 << Var << Arg->getSourceRange();
2063 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2064 << true;
2065 return true;
2066 }
2067
2068 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002069 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002070 return Invalid;
2071 }
Mike Stump11289f42009-09-09 15:08:12 +00002072
Douglas Gregorccb07762009-02-11 19:52:55 +00002073 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002074 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002075 diag::err_template_arg_not_object_or_func)
2076 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002077 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002078 diag::note_template_arg_refers_here);
2079 return true;
2080}
2081
2082/// \brief Checks whether the given template argument is a pointer to
2083/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002084bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2085 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002086 bool Invalid = false;
2087
2088 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002089 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002090 Arg = Cast->getSubExpr();
2091
Sebastian Redl576fd422009-05-10 18:38:11 +00002092 // C++0x allows nullptr, and there's no further checking to be done for that.
2093 if (Arg->getType()->isNullPtrType())
2094 return false;
2095
Douglas Gregorccb07762009-02-11 19:52:55 +00002096 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002097 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002098 // A template-argument for a non-type, non-template
2099 // template-parameter shall be one of: [...]
2100 //
2101 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002102 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002103
2104 // Ignore (and complain about) any excess parentheses.
2105 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2106 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002107 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002108 diag::err_template_arg_extra_parens)
2109 << Arg->getSourceRange();
2110 Invalid = true;
2111 }
2112
2113 Arg = Parens->getSubExpr();
2114 }
2115
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002116 // A pointer-to-member constant written &Class::member.
2117 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002118 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2119 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2120 if (DRE && !DRE->getQualifier())
2121 DRE = 0;
2122 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002123 }
2124 // A constant of pointer-to-member type.
2125 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2126 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2127 if (VD->getType()->isMemberPointerType()) {
2128 if (isa<NonTypeTemplateParmDecl>(VD) ||
2129 (isa<VarDecl>(VD) &&
2130 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2131 if (Arg->isTypeDependent() || Arg->isValueDependent())
2132 Converted = TemplateArgument(Arg->Retain());
2133 else
2134 Converted = TemplateArgument(VD->getCanonicalDecl());
2135 return Invalid;
2136 }
2137 }
2138 }
2139
2140 DRE = 0;
2141 }
2142
Douglas Gregorccb07762009-02-11 19:52:55 +00002143 if (!DRE)
2144 return Diag(Arg->getSourceRange().getBegin(),
2145 diag::err_template_arg_not_pointer_to_member_form)
2146 << Arg->getSourceRange();
2147
2148 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2149 assert((isa<FieldDecl>(DRE->getDecl()) ||
2150 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2151 "Only non-static member pointers can make it here");
2152
2153 // Okay: this is the address of a non-static member, and therefore
2154 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002155 if (Arg->isTypeDependent() || Arg->isValueDependent())
2156 Converted = TemplateArgument(Arg->Retain());
2157 else
2158 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002159 return Invalid;
2160 }
2161
2162 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002163 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002164 diag::err_template_arg_not_pointer_to_member_form)
2165 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002166 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002167 diag::note_template_arg_refers_here);
2168 return true;
2169}
2170
Douglas Gregord32e0282009-02-09 23:23:08 +00002171/// \brief Check a template argument against its corresponding
2172/// non-type template parameter.
2173///
Douglas Gregor463421d2009-03-03 04:44:36 +00002174/// This routine implements the semantics of C++ [temp.arg.nontype].
2175/// It returns true if an error occurred, and false otherwise. \p
2176/// InstantiatedParamType is the type of the non-type template
2177/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002178///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002179/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002180bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002181 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002182 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002183 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2184
Douglas Gregor86560402009-02-10 23:36:10 +00002185 // If either the parameter has a dependent type or the argument is
2186 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002187 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002188 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2189 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002190 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002191 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002192 }
Douglas Gregor86560402009-02-10 23:36:10 +00002193
2194 // C++ [temp.arg.nontype]p5:
2195 // The following conversions are performed on each expression used
2196 // as a non-type template-argument. If a non-type
2197 // template-argument cannot be converted to the type of the
2198 // corresponding template-parameter then the program is
2199 // ill-formed.
2200 //
2201 // -- for a non-type template-parameter of integral or
2202 // enumeration type, integral promotions (4.5) and integral
2203 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002204 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002205 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002206 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002207 // C++ [temp.arg.nontype]p1:
2208 // A template-argument for a non-type, non-template
2209 // template-parameter shall be one of:
2210 //
2211 // -- an integral constant-expression of integral or enumeration
2212 // type; or
2213 // -- the name of a non-type template-parameter; or
2214 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002215 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002216 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002217 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002218 diag::err_template_arg_not_integral_or_enumeral)
2219 << ArgType << Arg->getSourceRange();
2220 Diag(Param->getLocation(), diag::note_template_param_here);
2221 return true;
2222 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002223 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002224 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2225 << ArgType << Arg->getSourceRange();
2226 return true;
2227 }
2228
2229 // FIXME: We need some way to more easily get the unqualified form
2230 // of the types without going all the way to the
2231 // canonical type.
2232 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2233 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2234 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2235 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2236
2237 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002238 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002239 // Okay: no conversion necessary
2240 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2241 !ParamType->isEnumeralType()) {
2242 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002243 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002244 } else {
2245 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002246 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002247 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002248 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002249 Diag(Param->getLocation(), diag::note_template_param_here);
2250 return true;
2251 }
2252
Douglas Gregor52aba872009-03-14 00:20:21 +00002253 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002254 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002255 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002256
2257 if (!Arg->isValueDependent()) {
2258 // Check that an unsigned parameter does not receive a negative
2259 // value.
2260 if (IntegerType->isUnsignedIntegerType()
2261 && (Value.isSigned() && Value.isNegative())) {
2262 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2263 << Value.toString(10) << Param->getType()
2264 << Arg->getSourceRange();
2265 Diag(Param->getLocation(), diag::note_template_param_here);
2266 return true;
2267 }
2268
2269 // Check that we don't overflow the template parameter type.
2270 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2271 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002272 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002273 diag::err_template_arg_too_large)
2274 << Value.toString(10) << Param->getType()
2275 << Arg->getSourceRange();
2276 Diag(Param->getLocation(), diag::note_template_param_here);
2277 return true;
2278 }
2279
2280 if (Value.getBitWidth() != AllowedBits)
2281 Value.extOrTrunc(AllowedBits);
2282 Value.setIsSigned(IntegerType->isSignedIntegerType());
2283 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002284
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002285 // Add the value of this argument to the list of converted
2286 // arguments. We use the bitwidth and signedness of the template
2287 // parameter.
2288 if (Arg->isValueDependent()) {
2289 // The argument is value-dependent. Create a new
2290 // TemplateArgument with the converted expression.
2291 Converted = TemplateArgument(Arg);
2292 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002293 }
2294
John McCall0ad16662009-10-29 08:12:44 +00002295 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002296 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002297 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002298 return false;
2299 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002300
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002301 // Handle pointer-to-function, reference-to-function, and
2302 // pointer-to-member-function all in (roughly) the same way.
2303 if (// -- For a non-type template-parameter of type pointer to
2304 // function, only the function-to-pointer conversion (4.3) is
2305 // applied. If the template-argument represents a set of
2306 // overloaded functions (or a pointer to such), the matching
2307 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002308 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002309 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002310 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002311 // -- For a non-type template-parameter of type reference to
2312 // function, no conversions apply. If the template-argument
2313 // represents a set of overloaded functions, the matching
2314 // function is selected from the set (13.4).
2315 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002316 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002317 // -- For a non-type template-parameter of type pointer to
2318 // member function, no conversions apply. If the
2319 // template-argument represents a set of overloaded member
2320 // functions, the matching member function is selected from
2321 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002322 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002323 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002324 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002325 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002326 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002327 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002328 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002329 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2330 ParamType->isMemberPointerType())) {
2331 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002332 if (ParamType->isMemberPointerType())
2333 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2334 else
2335 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002336 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002337 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002338 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002339 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002340 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002341 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2342 return true;
2343
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002344 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002345 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002346 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002347 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002348 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002349 }
2350 }
2351
Mike Stump11289f42009-09-09 15:08:12 +00002352 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002353 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002354 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002355 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002356 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002357 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002358 Diag(Param->getLocation(), diag::note_template_param_here);
2359 return true;
2360 }
Mike Stump11289f42009-09-09 15:08:12 +00002361
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002362 if (ParamType->isMemberPointerType())
2363 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002364
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002365 NamedDecl *Entity = 0;
2366 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2367 return true;
2368
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002369 if (Entity)
2370 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002371 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002372 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002373 }
2374
Chris Lattner696197c2009-02-20 21:37:53 +00002375 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002376 // -- for a non-type template-parameter of type pointer to
2377 // object, qualification conversions (4.4) and the
2378 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002379 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002380 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002381 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002382
Sebastian Redl576fd422009-05-10 18:38:11 +00002383 if (ArgType->isNullPtrType()) {
2384 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002385 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002386 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002387 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002388 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002389 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002390
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002391 if (IsQualificationConversion(ArgType, ParamType)) {
2392 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002393 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002394 }
Mike Stump11289f42009-09-09 15:08:12 +00002395
Douglas Gregor1515f762009-02-11 18:22:40 +00002396 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002397 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002398 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002399 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002400 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002401 Diag(Param->getLocation(), diag::note_template_param_here);
2402 return true;
2403 }
Mike Stump11289f42009-09-09 15:08:12 +00002404
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002405 NamedDecl *Entity = 0;
2406 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2407 return true;
2408
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002409 if (Entity)
2410 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002411 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002412 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002413 }
Mike Stump11289f42009-09-09 15:08:12 +00002414
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002415 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002416 // -- For a non-type template-parameter of type reference to
2417 // object, no conversions apply. The type referred to by the
2418 // reference may be more cv-qualified than the (otherwise
2419 // identical) type of the template-argument. The
2420 // template-parameter is bound directly to the
2421 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002422 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002423 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002424
Douglas Gregor1515f762009-02-11 18:22:40 +00002425 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002426 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002427 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002428 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002429 << Arg->getSourceRange();
2430 Diag(Param->getLocation(), diag::note_template_param_here);
2431 return true;
2432 }
2433
Mike Stump11289f42009-09-09 15:08:12 +00002434 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002435 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2436 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002437
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002438 if ((ParamQuals | ArgQuals) != ParamQuals) {
2439 Diag(Arg->getSourceRange().getBegin(),
2440 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002441 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002442 << Arg->getSourceRange();
2443 Diag(Param->getLocation(), diag::note_template_param_here);
2444 return true;
2445 }
Mike Stump11289f42009-09-09 15:08:12 +00002446
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002447 NamedDecl *Entity = 0;
2448 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2449 return true;
2450
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002451 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002452 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002453 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002454 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002455
2456 // -- For a non-type template-parameter of type pointer to data
2457 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002458 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002459 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2460
Douglas Gregor1515f762009-02-11 18:22:40 +00002461 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002462 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002463 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002464 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002465 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002466 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002467 } else {
2468 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002469 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002470 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002471 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002472 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002473 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002474 }
2475
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002476 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002477}
2478
2479/// \brief Check a template argument against its corresponding
2480/// template template parameter.
2481///
2482/// This routine implements the semantics of C++ [temp.arg.template].
2483/// It returns true if an error occurred, and false otherwise.
2484bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002485 const TemplateArgumentLoc &Arg) {
2486 TemplateName Name = Arg.getArgument().getAsTemplate();
2487 TemplateDecl *Template = Name.getAsTemplateDecl();
2488 if (!Template) {
2489 // Any dependent template name is fine.
2490 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2491 return false;
2492 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002493
2494 // C++ [temp.arg.template]p1:
2495 // A template-argument for a template template-parameter shall be
2496 // the name of a class template, expressed as id-expression. Only
2497 // primary class templates are considered when matching the
2498 // template template argument with the corresponding parameter;
2499 // partial specializations are not considered even if their
2500 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002501 //
2502 // Note that we also allow template template parameters here, which
2503 // will happen when we are dealing with, e.g., class template
2504 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002505 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002506 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002507 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002508 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002509 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002510 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002511 << Template;
2512 }
2513
2514 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2515 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002516 true,
2517 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002518 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002519}
2520
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002521/// \brief Determine whether the given template parameter lists are
2522/// equivalent.
2523///
Mike Stump11289f42009-09-09 15:08:12 +00002524/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002525/// source code as part of a new template declaration.
2526///
2527/// \param Old The old template parameter list, typically found via
2528/// name lookup of the template declared with this template parameter
2529/// list.
2530///
2531/// \param Complain If true, this routine will produce a diagnostic if
2532/// the template parameter lists are not equivalent.
2533///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002534/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00002535///
2536/// \param TemplateArgLoc If this source location is valid, then we
2537/// are actually checking the template parameter list of a template
2538/// argument (New) against the template parameter list of its
2539/// corresponding template template parameter (Old). We produce
2540/// slightly different diagnostics in this scenario.
2541///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002542/// \returns True if the template parameter lists are equal, false
2543/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002544bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002545Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2546 TemplateParameterList *Old,
2547 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002548 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002549 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002550 if (Old->size() != New->size()) {
2551 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002552 unsigned NextDiag = diag::err_template_param_list_different_arity;
2553 if (TemplateArgLoc.isValid()) {
2554 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2555 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002556 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002557 Diag(New->getTemplateLoc(), NextDiag)
2558 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002559 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002560 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002561 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002562 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002563 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2564 }
2565
2566 return false;
2567 }
2568
2569 for (TemplateParameterList::iterator OldParm = Old->begin(),
2570 OldParmEnd = Old->end(), NewParm = New->begin();
2571 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2572 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002573 if (Complain) {
2574 unsigned NextDiag = diag::err_template_param_different_kind;
2575 if (TemplateArgLoc.isValid()) {
2576 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2577 NextDiag = diag::note_template_param_different_kind;
2578 }
2579 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002580 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00002581 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002582 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00002583 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002584 return false;
2585 }
2586
2587 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2588 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002589 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002590 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002591 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2592 // The types of non-type template parameters must agree.
2593 NonTypeTemplateParmDecl *NewNTTP
2594 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002595
2596 // If we are matching a template template argument to a template
2597 // template parameter and one of the non-type template parameter types
2598 // is dependent, then we must wait until template instantiation time
2599 // to actually compare the arguments.
2600 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2601 (OldNTTP->getType()->isDependentType() ||
2602 NewNTTP->getType()->isDependentType()))
2603 continue;
2604
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002605 if (Context.getCanonicalType(OldNTTP->getType()) !=
2606 Context.getCanonicalType(NewNTTP->getType())) {
2607 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002608 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2609 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002610 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002611 diag::err_template_arg_template_params_mismatch);
2612 NextDiag = diag::note_template_nontype_parm_different_type;
2613 }
2614 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002615 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002616 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00002617 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002618 diag::note_template_nontype_parm_prev_declaration)
2619 << OldNTTP->getType();
2620 }
2621 return false;
2622 }
2623 } else {
2624 // The template parameter lists of template template
2625 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002626 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002627 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002628 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002629 = cast<TemplateTemplateParmDecl>(*OldParm);
2630 TemplateTemplateParmDecl *NewTTP
2631 = cast<TemplateTemplateParmDecl>(*NewParm);
2632 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2633 OldTTP->getTemplateParameters(),
2634 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002635 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00002636 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002637 return false;
2638 }
2639 }
2640
2641 return true;
2642}
2643
2644/// \brief Check whether a template can be declared within this scope.
2645///
2646/// If the template declaration is valid in this scope, returns
2647/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002648bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002649Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002650 // Find the nearest enclosing declaration scope.
2651 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2652 (S->getFlags() & Scope::TemplateParamScope) != 0)
2653 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002654
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002655 // C++ [temp]p2:
2656 // A template-declaration can appear only as a namespace scope or
2657 // class scope declaration.
2658 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002659 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2660 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002661 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002662 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002663
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002664 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002665 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002666
2667 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2668 return false;
2669
Mike Stump11289f42009-09-09 15:08:12 +00002670 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002671 diag::err_template_outside_namespace_or_class_scope)
2672 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002673}
Douglas Gregor67a65642009-02-17 23:15:12 +00002674
Douglas Gregor54888652009-10-07 00:13:32 +00002675/// \brief Determine what kind of template specialization the given declaration
2676/// is.
2677static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2678 if (!D)
2679 return TSK_Undeclared;
2680
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002681 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2682 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002683 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2684 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002685 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2686 return Var->getTemplateSpecializationKind();
2687
Douglas Gregor54888652009-10-07 00:13:32 +00002688 return TSK_Undeclared;
2689}
2690
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002691/// \brief Check whether a specialization is well-formed in the current
2692/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002693///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002694/// This routine determines whether a template specialization can be declared
2695/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002696///
2697/// \param S the semantic analysis object for which this check is being
2698/// performed.
2699///
2700/// \param Specialized the entity being specialized or instantiated, which
2701/// may be a kind of template (class template, function template, etc.) or
2702/// a member of a class template (member function, static data member,
2703/// member class).
2704///
2705/// \param PrevDecl the previous declaration of this entity, if any.
2706///
2707/// \param Loc the location of the explicit specialization or instantiation of
2708/// this entity.
2709///
2710/// \param IsPartialSpecialization whether this is a partial specialization of
2711/// a class template.
2712///
Douglas Gregor54888652009-10-07 00:13:32 +00002713/// \returns true if there was an error that we cannot recover from, false
2714/// otherwise.
2715static bool CheckTemplateSpecializationScope(Sema &S,
2716 NamedDecl *Specialized,
2717 NamedDecl *PrevDecl,
2718 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002719 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002720 // Keep these "kind" numbers in sync with the %select statements in the
2721 // various diagnostics emitted by this routine.
2722 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002723 bool isTemplateSpecialization = false;
2724 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002725 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002726 isTemplateSpecialization = true;
2727 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002728 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002729 isTemplateSpecialization = true;
2730 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002731 EntityKind = 3;
2732 else if (isa<VarDecl>(Specialized))
2733 EntityKind = 4;
2734 else if (isa<RecordDecl>(Specialized))
2735 EntityKind = 5;
2736 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002737 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2738 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00002739 return true;
2740 }
2741
Douglas Gregorf47b9112009-02-25 22:02:03 +00002742 // C++ [temp.expl.spec]p2:
2743 // An explicit specialization shall be declared in the namespace
2744 // of which the template is a member, or, for member templates, in
2745 // the namespace of which the enclosing class or enclosing class
2746 // template is a member. An explicit specialization of a member
2747 // function, member class or static data member of a class
2748 // template shall be declared in the namespace of which the class
2749 // template is a member. Such a declaration may also be a
2750 // definition. If the declaration is not a definition, the
2751 // specialization may be defined later in the name- space in which
2752 // the explicit specialization was declared, or in a namespace
2753 // that encloses the one in which the explicit specialization was
2754 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002755 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2756 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002757 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002758 return true;
2759 }
Douglas Gregore4b05162009-10-07 17:21:34 +00002760
Douglas Gregor40fb7442009-10-07 17:30:37 +00002761 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2762 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002763 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00002764 return true;
2765 }
2766
Douglas Gregore4b05162009-10-07 17:21:34 +00002767 // C++ [temp.class.spec]p6:
2768 // A class template partial specialization may be declared or redeclared
2769 // in any namespace scope in which its definition may be defined (14.5.1
2770 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002771 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002772 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002773 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002774 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002775 if ((!PrevDecl ||
2776 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2777 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2778 // There is no prior declaration of this entity, so this
2779 // specialization must be in the same context as the template
2780 // itself.
2781 if (!DC->Equals(SpecializedContext)) {
2782 if (isa<TranslationUnitDecl>(SpecializedContext))
2783 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2784 << EntityKind << Specialized;
2785 else if (isa<NamespaceDecl>(SpecializedContext))
2786 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2787 << EntityKind << Specialized
2788 << cast<NamedDecl>(SpecializedContext);
2789
2790 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2791 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002792 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002793 }
Douglas Gregor54888652009-10-07 00:13:32 +00002794
2795 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002796 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00002797 // Note that HandleDeclarator() performs this check for explicit
2798 // specializations of function templates, static data members, and member
2799 // functions, so we skip the check here for those kinds of entities.
2800 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00002801 // Should we refactor that check, so that it occurs later?
2802 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002803 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2804 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00002805 if (isa<TranslationUnitDecl>(SpecializedContext))
2806 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2807 << EntityKind << Specialized;
2808 else if (isa<NamespaceDecl>(SpecializedContext))
2809 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2810 << EntityKind << Specialized
2811 << cast<NamedDecl>(SpecializedContext);
2812
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002813 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002814 }
Douglas Gregor54888652009-10-07 00:13:32 +00002815
2816 // FIXME: check for specialization-after-instantiation errors and such.
2817
Douglas Gregorf47b9112009-02-25 22:02:03 +00002818 return false;
2819}
Douglas Gregor54888652009-10-07 00:13:32 +00002820
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002821/// \brief Check the non-type template arguments of a class template
2822/// partial specialization according to C++ [temp.class.spec]p9.
2823///
Douglas Gregor09a30232009-06-12 22:08:06 +00002824/// \param TemplateParams the template parameters of the primary class
2825/// template.
2826///
2827/// \param TemplateArg the template arguments of the class template
2828/// partial specialization.
2829///
2830/// \param MirrorsPrimaryTemplate will be set true if the class
2831/// template partial specialization arguments are identical to the
2832/// implicit template arguments of the primary template. This is not
2833/// necessarily an error (C++0x), and it is left to the caller to diagnose
2834/// this condition when it is an error.
2835///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002836/// \returns true if there was an error, false otherwise.
2837bool Sema::CheckClassTemplatePartialSpecializationArgs(
2838 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002839 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002840 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002841 // FIXME: the interface to this function will have to change to
2842 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002843 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002844
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002845 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002846
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002847 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002848 // Determine whether the template argument list of the partial
2849 // specialization is identical to the implicit argument list of
2850 // the primary template. The caller may need to diagnostic this as
2851 // an error per C++ [temp.class.spec]p9b3.
2852 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002853 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002854 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2855 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002856 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002857 MirrorsPrimaryTemplate = false;
2858 } else if (TemplateTemplateParmDecl *TTP
2859 = dyn_cast<TemplateTemplateParmDecl>(
2860 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002861 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00002862 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002863 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002864 if (!ArgDecl ||
2865 ArgDecl->getIndex() != TTP->getIndex() ||
2866 ArgDecl->getDepth() != TTP->getDepth())
2867 MirrorsPrimaryTemplate = false;
2868 }
2869 }
2870
Mike Stump11289f42009-09-09 15:08:12 +00002871 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002872 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002873 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002874 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002875 }
2876
Anders Carlsson40c1d492009-06-13 18:20:51 +00002877 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002878 if (!ArgExpr) {
2879 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002880 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002881 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002882
2883 // C++ [temp.class.spec]p8:
2884 // A non-type argument is non-specialized if it is the name of a
2885 // non-type parameter. All other non-type arguments are
2886 // specialized.
2887 //
2888 // Below, we check the two conditions that only apply to
2889 // specialized non-type arguments, so skip any non-specialized
2890 // arguments.
2891 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002892 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002893 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002894 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002895 (Param->getIndex() != NTTP->getIndex() ||
2896 Param->getDepth() != NTTP->getDepth()))
2897 MirrorsPrimaryTemplate = false;
2898
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002899 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002900 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002901
2902 // C++ [temp.class.spec]p9:
2903 // Within the argument list of a class template partial
2904 // specialization, the following restrictions apply:
2905 // -- A partially specialized non-type argument expression
2906 // shall not involve a template parameter of the partial
2907 // specialization except when the argument expression is a
2908 // simple identifier.
2909 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002910 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002911 diag::err_dependent_non_type_arg_in_partial_spec)
2912 << ArgExpr->getSourceRange();
2913 return true;
2914 }
2915
2916 // -- The type of a template parameter corresponding to a
2917 // specialized non-type argument shall not be dependent on a
2918 // parameter of the specialization.
2919 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002920 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002921 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2922 << Param->getType()
2923 << ArgExpr->getSourceRange();
2924 Diag(Param->getLocation(), diag::note_template_param_here);
2925 return true;
2926 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002927
2928 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002929 }
2930
2931 return false;
2932}
2933
Douglas Gregorc08f4892009-03-25 00:13:59 +00002934Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002935Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2936 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002937 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002938 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002939 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002940 SourceLocation TemplateNameLoc,
2941 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002942 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002943 SourceLocation RAngleLoc,
2944 AttributeList *Attr,
2945 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00002946 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00002947
Douglas Gregor67a65642009-02-17 23:15:12 +00002948 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002949 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002950 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00002951 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
2952
2953 if (!ClassTemplate) {
2954 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
2955 << (Name.getAsTemplateDecl() &&
2956 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
2957 return true;
2958 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002959
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002960 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00002961 bool isPartialSpecialization = false;
2962
Douglas Gregorf47b9112009-02-25 22:02:03 +00002963 // Check the validity of the template headers that introduce this
2964 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00002965 // FIXME: We probably shouldn't complain about these headers for
2966 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002967 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002968 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2969 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002970 TemplateParameterLists.size(),
2971 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002972 if (TemplateParams && TemplateParams->size() > 0) {
2973 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002974
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002975 // C++ [temp.class.spec]p10:
2976 // The template parameter list of a specialization shall not
2977 // contain default template argument values.
2978 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2979 Decl *Param = TemplateParams->getParam(I);
2980 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2981 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002982 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002983 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00002984 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002985 }
2986 } else if (NonTypeTemplateParmDecl *NTTP
2987 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2988 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002989 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002990 diag::err_default_arg_in_partial_spec)
2991 << DefArg->getSourceRange();
2992 NTTP->setDefaultArgument(0);
2993 DefArg->Destroy(Context);
2994 }
2995 } else {
2996 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002997 if (TTP->hasDefaultArgument()) {
2998 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002999 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003000 << TTP->getDefaultArgument().getSourceRange();
3001 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003002 }
3003 }
3004 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003005 } else if (TemplateParams) {
3006 if (TUK == TUK_Friend)
3007 Diag(KWLoc, diag::err_template_spec_friend)
3008 << CodeModificationHint::CreateRemoval(
3009 SourceRange(TemplateParams->getTemplateLoc(),
3010 TemplateParams->getRAngleLoc()))
3011 << SourceRange(LAngleLoc, RAngleLoc);
3012 else
3013 isExplicitSpecialization = true;
3014 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003015 Diag(KWLoc, diag::err_template_spec_needs_header)
3016 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003017 isExplicitSpecialization = true;
3018 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003019
Douglas Gregor67a65642009-02-17 23:15:12 +00003020 // Check that the specialization uses the same tag kind as the
3021 // original template.
3022 TagDecl::TagKind Kind;
3023 switch (TagSpec) {
3024 default: assert(0 && "Unknown tag type!");
3025 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3026 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3027 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3028 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003029 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003030 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003031 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003032 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003033 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003034 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003035 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003036 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003037 diag::note_previous_use);
3038 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3039 }
3040
Douglas Gregorc40290e2009-03-09 23:48:35 +00003041 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003042 TemplateArgumentListInfo TemplateArgs;
3043 TemplateArgs.setLAngleLoc(LAngleLoc);
3044 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003045 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003046
Douglas Gregor67a65642009-02-17 23:15:12 +00003047 // Check that the template argument list is well-formed for this
3048 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003049 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3050 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003051 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3052 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003053 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003054
Mike Stump11289f42009-09-09 15:08:12 +00003055 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003056 ClassTemplate->getTemplateParameters()->size()) &&
3057 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003058
Douglas Gregor2373c592009-05-31 09:31:02 +00003059 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003060 // corresponds to these arguments.
3061 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003062 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003063 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003064 if (CheckClassTemplatePartialSpecializationArgs(
3065 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003066 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003067 return true;
3068
Douglas Gregor09a30232009-06-12 22:08:06 +00003069 if (MirrorsPrimaryTemplate) {
3070 // C++ [temp.class.spec]p9b3:
3071 //
Mike Stump11289f42009-09-09 15:08:12 +00003072 // -- The argument list of the specialization shall not be identical
3073 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003074 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003075 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003076 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003077 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003078 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003079 ClassTemplate->getIdentifier(),
3080 TemplateNameLoc,
3081 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003082 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003083 AS_none);
3084 }
3085
Douglas Gregor2208a292009-09-26 20:57:03 +00003086 // FIXME: Diagnose friend partial specializations
3087
Douglas Gregor2373c592009-05-31 09:31:02 +00003088 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00003089 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003090 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003091 Converted.flatSize(),
3092 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003093 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003094 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003095 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003096 Converted.flatSize(),
3097 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003098 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003099 ClassTemplateSpecializationDecl *PrevDecl = 0;
3100
3101 if (isPartialSpecialization)
3102 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003103 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003104 InsertPos);
3105 else
3106 PrevDecl
3107 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003108
3109 ClassTemplateSpecializationDecl *Specialization = 0;
3110
Douglas Gregorf47b9112009-02-25 22:02:03 +00003111 // Check whether we can declare a class template specialization in
3112 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003113 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003114 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003115 TemplateNameLoc,
3116 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003117 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003118
Douglas Gregor15301382009-07-30 17:40:51 +00003119 // The canonical type
3120 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003121 if (PrevDecl &&
3122 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3123 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003124 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003125 // arguments was referenced but not declared, or we're only
3126 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003127 // declaration node as our own, updating its source location to
3128 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003129 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003130 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003131 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003132 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003133 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003134 // Build the canonical type that describes the converted template
3135 // arguments of the class template partial specialization.
3136 CanonType = Context.getTemplateSpecializationType(
3137 TemplateName(ClassTemplate),
3138 Converted.getFlatArguments(),
3139 Converted.flatSize());
3140
Douglas Gregor2373c592009-05-31 09:31:02 +00003141 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003142 ClassTemplatePartialSpecializationDecl *PrevPartial
3143 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003144 ClassTemplatePartialSpecializationDecl *Partial
3145 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003146 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003147 TemplateNameLoc,
3148 TemplateParams,
3149 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003150 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003151 TemplateArgs,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003152 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003153
3154 if (PrevPartial) {
3155 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3156 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3157 } else {
3158 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3159 }
3160 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003161
Douglas Gregor21610382009-10-29 00:04:11 +00003162 // If we are providing an explicit specialization of a member class
3163 // template specialization, make a note of that.
3164 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3165 PrevPartial->setMemberSpecialization();
3166
Douglas Gregor91772d12009-06-13 00:26:55 +00003167 // Check that all of the template parameters of the class template
3168 // partial specialization are deducible from the template
3169 // arguments. If not, this class template partial specialization
3170 // will never be used.
3171 llvm::SmallVector<bool, 8> DeducibleParams;
3172 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003173 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003174 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003175 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003176 unsigned NumNonDeducible = 0;
3177 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3178 if (!DeducibleParams[I])
3179 ++NumNonDeducible;
3180
3181 if (NumNonDeducible) {
3182 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3183 << (NumNonDeducible > 1)
3184 << SourceRange(TemplateNameLoc, RAngleLoc);
3185 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3186 if (!DeducibleParams[I]) {
3187 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3188 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003189 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003190 diag::note_partial_spec_unused_parameter)
3191 << Param->getDeclName();
3192 else
Mike Stump11289f42009-09-09 15:08:12 +00003193 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003194 diag::note_partial_spec_unused_parameter)
3195 << std::string("<anonymous>");
3196 }
3197 }
3198 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003199 } else {
3200 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003201 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003202 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003203 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003204 ClassTemplate->getDeclContext(),
3205 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003206 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003207 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003208 PrevDecl);
3209
3210 if (PrevDecl) {
3211 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3212 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3213 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003214 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003215 InsertPos);
3216 }
Douglas Gregor15301382009-07-30 17:40:51 +00003217
3218 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003219 }
3220
Douglas Gregor06db9f52009-10-12 20:18:28 +00003221 // C++ [temp.expl.spec]p6:
3222 // If a template, a member template or the member of a class template is
3223 // explicitly specialized then that specialization shall be declared
3224 // before the first use of that specialization that would cause an implicit
3225 // instantiation to take place, in every translation unit in which such a
3226 // use occurs; no diagnostic is required.
3227 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3228 SourceRange Range(TemplateNameLoc, RAngleLoc);
3229 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3230 << Context.getTypeDeclType(Specialization) << Range;
3231
3232 Diag(PrevDecl->getPointOfInstantiation(),
3233 diag::note_instantiation_required_here)
3234 << (PrevDecl->getTemplateSpecializationKind()
3235 != TSK_ImplicitInstantiation);
3236 return true;
3237 }
3238
Douglas Gregor2208a292009-09-26 20:57:03 +00003239 // If this is not a friend, note that this is an explicit specialization.
3240 if (TUK != TUK_Friend)
3241 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003242
3243 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003244 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003245 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003246 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003247 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003248 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003249 Diag(Def->getLocation(), diag::note_previous_definition);
3250 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003251 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003252 }
3253 }
3254
Douglas Gregord56a91e2009-02-26 22:19:44 +00003255 // Build the fully-sugared type for this class template
3256 // specialization as the user wrote in the specialization
3257 // itself. This means that we'll pretty-print the type retrieved
3258 // from the specialization's declaration the way that the user
3259 // actually wrote the specialization, rather than formatting the
3260 // name based on the "canonical" representation used to store the
3261 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003262 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00003263 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003264 if (TUK != TUK_Friend)
3265 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003266 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003267
Douglas Gregor1e249f82009-02-25 22:18:32 +00003268 // C++ [temp.expl.spec]p9:
3269 // A template explicit specialization is in the scope of the
3270 // namespace in which the template was defined.
3271 //
3272 // We actually implement this paragraph where we set the semantic
3273 // context (in the creation of the ClassTemplateSpecializationDecl),
3274 // but we also maintain the lexical context where the actual
3275 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003276 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003277
Douglas Gregor67a65642009-02-17 23:15:12 +00003278 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003279 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003280 Specialization->startDefinition();
3281
Douglas Gregor2208a292009-09-26 20:57:03 +00003282 if (TUK == TUK_Friend) {
3283 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3284 TemplateNameLoc,
3285 WrittenTy.getTypePtr(),
3286 /*FIXME:*/KWLoc);
3287 Friend->setAccess(AS_public);
3288 CurContext->addDecl(Friend);
3289 } else {
3290 // Add the specialization into its lexical context, so that it can
3291 // be seen when iterating through the list of declarations in that
3292 // context. However, specializations are not found by name lookup.
3293 CurContext->addDecl(Specialization);
3294 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003295 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003296}
Douglas Gregor333489b2009-03-27 23:10:48 +00003297
Mike Stump11289f42009-09-09 15:08:12 +00003298Sema::DeclPtrTy
3299Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003300 MultiTemplateParamsArg TemplateParameterLists,
3301 Declarator &D) {
3302 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3303}
3304
Mike Stump11289f42009-09-09 15:08:12 +00003305Sema::DeclPtrTy
3306Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003307 MultiTemplateParamsArg TemplateParameterLists,
3308 Declarator &D) {
3309 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3310 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3311 "Not a function declarator!");
3312 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003313
Douglas Gregor17a7c122009-06-24 00:54:41 +00003314 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003315 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003316 }
Mike Stump11289f42009-09-09 15:08:12 +00003317
Douglas Gregor17a7c122009-06-24 00:54:41 +00003318 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003319
3320 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003321 move(TemplateParameterLists),
3322 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003323 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003324 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003325 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003326 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003327 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3328 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003329 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003330}
3331
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003332/// \brief Diagnose cases where we have an explicit template specialization
3333/// before/after an explicit template instantiation, producing diagnostics
3334/// for those cases where they are required and determining whether the
3335/// new specialization/instantiation will have any effect.
3336///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003337/// \param NewLoc the location of the new explicit specialization or
3338/// instantiation.
3339///
3340/// \param NewTSK the kind of the new explicit specialization or instantiation.
3341///
3342/// \param PrevDecl the previous declaration of the entity.
3343///
3344/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3345///
3346/// \param PrevPointOfInstantiation if valid, indicates where the previus
3347/// declaration was instantiated (either implicitly or explicitly).
3348///
3349/// \param SuppressNew will be set to true to indicate that the new
3350/// specialization or instantiation has no effect and should be ignored.
3351///
3352/// \returns true if there was an error that should prevent the introduction of
3353/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003354bool
3355Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3356 TemplateSpecializationKind NewTSK,
3357 NamedDecl *PrevDecl,
3358 TemplateSpecializationKind PrevTSK,
3359 SourceLocation PrevPointOfInstantiation,
3360 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003361 SuppressNew = false;
3362
3363 switch (NewTSK) {
3364 case TSK_Undeclared:
3365 case TSK_ImplicitInstantiation:
3366 assert(false && "Don't check implicit instantiations here");
3367 return false;
3368
3369 case TSK_ExplicitSpecialization:
3370 switch (PrevTSK) {
3371 case TSK_Undeclared:
3372 case TSK_ExplicitSpecialization:
3373 // Okay, we're just specializing something that is either already
3374 // explicitly specialized or has merely been mentioned without any
3375 // instantiation.
3376 return false;
3377
3378 case TSK_ImplicitInstantiation:
3379 if (PrevPointOfInstantiation.isInvalid()) {
3380 // The declaration itself has not actually been instantiated, so it is
3381 // still okay to specialize it.
3382 return false;
3383 }
3384 // Fall through
3385
3386 case TSK_ExplicitInstantiationDeclaration:
3387 case TSK_ExplicitInstantiationDefinition:
3388 assert((PrevTSK == TSK_ImplicitInstantiation ||
3389 PrevPointOfInstantiation.isValid()) &&
3390 "Explicit instantiation without point of instantiation?");
3391
3392 // C++ [temp.expl.spec]p6:
3393 // If a template, a member template or the member of a class template
3394 // is explicitly specialized then that specialization shall be declared
3395 // before the first use of that specialization that would cause an
3396 // implicit instantiation to take place, in every translation unit in
3397 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003398 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003399 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003400 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003401 << (PrevTSK != TSK_ImplicitInstantiation);
3402
3403 return true;
3404 }
3405 break;
3406
3407 case TSK_ExplicitInstantiationDeclaration:
3408 switch (PrevTSK) {
3409 case TSK_ExplicitInstantiationDeclaration:
3410 // This explicit instantiation declaration is redundant (that's okay).
3411 SuppressNew = true;
3412 return false;
3413
3414 case TSK_Undeclared:
3415 case TSK_ImplicitInstantiation:
3416 // We're explicitly instantiating something that may have already been
3417 // implicitly instantiated; that's fine.
3418 return false;
3419
3420 case TSK_ExplicitSpecialization:
3421 // C++0x [temp.explicit]p4:
3422 // For a given set of template parameters, if an explicit instantiation
3423 // of a template appears after a declaration of an explicit
3424 // specialization for that template, the explicit instantiation has no
3425 // effect.
3426 return false;
3427
3428 case TSK_ExplicitInstantiationDefinition:
3429 // C++0x [temp.explicit]p10:
3430 // If an entity is the subject of both an explicit instantiation
3431 // declaration and an explicit instantiation definition in the same
3432 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003433 Diag(NewLoc,
3434 diag::err_explicit_instantiation_declaration_after_definition);
3435 Diag(PrevPointOfInstantiation,
3436 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003437 assert(PrevPointOfInstantiation.isValid() &&
3438 "Explicit instantiation without point of instantiation?");
3439 SuppressNew = true;
3440 return false;
3441 }
3442 break;
3443
3444 case TSK_ExplicitInstantiationDefinition:
3445 switch (PrevTSK) {
3446 case TSK_Undeclared:
3447 case TSK_ImplicitInstantiation:
3448 // We're explicitly instantiating something that may have already been
3449 // implicitly instantiated; that's fine.
3450 return false;
3451
3452 case TSK_ExplicitSpecialization:
3453 // C++ DR 259, C++0x [temp.explicit]p4:
3454 // For a given set of template parameters, if an explicit
3455 // instantiation of a template appears after a declaration of
3456 // an explicit specialization for that template, the explicit
3457 // instantiation has no effect.
3458 //
3459 // In C++98/03 mode, we only give an extension warning here, because it
3460 // is not not harmful to try to explicitly instantiate something that
3461 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003462 if (!getLangOptions().CPlusPlus0x) {
3463 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003464 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003465 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003466 diag::note_previous_template_specialization);
3467 }
3468 SuppressNew = true;
3469 return false;
3470
3471 case TSK_ExplicitInstantiationDeclaration:
3472 // We're explicity instantiating a definition for something for which we
3473 // were previously asked to suppress instantiations. That's fine.
3474 return false;
3475
3476 case TSK_ExplicitInstantiationDefinition:
3477 // C++0x [temp.spec]p5:
3478 // For a given template and a given set of template-arguments,
3479 // - an explicit instantiation definition shall appear at most once
3480 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003481 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003482 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003483 Diag(PrevPointOfInstantiation,
3484 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003485 SuppressNew = true;
3486 return false;
3487 }
3488 break;
3489 }
3490
3491 assert(false && "Missing specialization/instantiation case?");
3492
3493 return false;
3494}
3495
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003496/// \brief Perform semantic analysis for the given function template
3497/// specialization.
3498///
3499/// This routine performs all of the semantic analysis required for an
3500/// explicit function template specialization. On successful completion,
3501/// the function declaration \p FD will become a function template
3502/// specialization.
3503///
3504/// \param FD the function declaration, which will be updated to become a
3505/// function template specialization.
3506///
3507/// \param HasExplicitTemplateArgs whether any template arguments were
3508/// explicitly provided.
3509///
3510/// \param LAngleLoc the location of the left angle bracket ('<'), if
3511/// template arguments were explicitly provided.
3512///
3513/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3514/// if any.
3515///
3516/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3517/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3518/// true as in, e.g., \c void sort<>(char*, char*);
3519///
3520/// \param RAngleLoc the location of the right angle bracket ('>'), if
3521/// template arguments were explicitly provided.
3522///
3523/// \param PrevDecl the set of declarations that
3524bool
3525Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00003526 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00003527 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003528 // The set of function template specializations that could match this
3529 // explicit function template specialization.
3530 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3531 CandidateSet Candidates;
3532
3533 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00003534 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3535 I != E; ++I) {
3536 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3537 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003538 // Only consider templates found within the same semantic lookup scope as
3539 // FD.
3540 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3541 continue;
3542
3543 // C++ [temp.expl.spec]p11:
3544 // A trailing template-argument can be left unspecified in the
3545 // template-id naming an explicit function template specialization
3546 // provided it can be deduced from the function argument type.
3547 // Perform template argument deduction to determine whether we may be
3548 // specializing this template.
3549 // FIXME: It is somewhat wasteful to build
3550 TemplateDeductionInfo Info(Context);
3551 FunctionDecl *Specialization = 0;
3552 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00003553 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003554 FD->getType(),
3555 Specialization,
3556 Info)) {
3557 // FIXME: Template argument deduction failed; record why it failed, so
3558 // that we can provide nifty diagnostics.
3559 (void)TDK;
3560 continue;
3561 }
3562
3563 // Record this candidate.
3564 Candidates.push_back(Specialization);
3565 }
3566 }
3567
Douglas Gregor5de279c2009-09-26 03:41:46 +00003568 // Find the most specialized function template.
3569 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3570 Candidates.size(),
3571 TPOC_Other,
3572 FD->getLocation(),
3573 PartialDiagnostic(diag::err_function_template_spec_no_match)
3574 << FD->getDeclName(),
3575 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00003576 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor5de279c2009-09-26 03:41:46 +00003577 PartialDiagnostic(diag::note_function_template_spec_matched));
3578 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003579 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003580
3581 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003582 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003583
Douglas Gregor54888652009-10-07 00:13:32 +00003584 // Check the scope of this explicit specialization.
3585 if (CheckTemplateSpecializationScope(*this,
3586 Specialization->getPrimaryTemplate(),
3587 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003588 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003589 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003590
3591 // C++ [temp.expl.spec]p6:
3592 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003593 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003594 // before the first use of that specialization that would cause an implicit
3595 // instantiation to take place, in every translation unit in which such a
3596 // use occurs; no diagnostic is required.
3597 FunctionTemplateSpecializationInfo *SpecInfo
3598 = Specialization->getTemplateSpecializationInfo();
3599 assert(SpecInfo && "Function template specialization info missing?");
3600 if (SpecInfo->getPointOfInstantiation().isValid()) {
3601 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3602 << FD;
3603 Diag(SpecInfo->getPointOfInstantiation(),
3604 diag::note_instantiation_required_here)
3605 << (Specialization->getTemplateSpecializationKind()
3606 != TSK_ImplicitInstantiation);
3607 return true;
3608 }
Douglas Gregor54888652009-10-07 00:13:32 +00003609
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003610 // Mark the prior declaration as an explicit specialization, so that later
3611 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003612 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003613
3614 // Turn the given function declaration into a function template
3615 // specialization, with the template arguments from the previous
3616 // specialization.
3617 FD->setFunctionTemplateSpecialization(Context,
3618 Specialization->getPrimaryTemplate(),
3619 new (Context) TemplateArgumentList(
3620 *Specialization->getTemplateSpecializationArgs()),
3621 /*InsertPos=*/0,
3622 TSK_ExplicitSpecialization);
3623
3624 // The "previous declaration" for this function template specialization is
3625 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00003626 Previous.clear();
3627 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003628 return false;
3629}
3630
Douglas Gregor86d142a2009-10-08 07:24:58 +00003631/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003632/// specialization.
3633///
3634/// This routine performs all of the semantic analysis required for an
3635/// explicit member function specialization. On successful completion,
3636/// the function declaration \p FD will become a member function
3637/// specialization.
3638///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003639/// \param Member the member declaration, which will be updated to become a
3640/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003641///
John McCall1f82f242009-11-18 22:49:29 +00003642/// \param Previous the set of declarations, one of which may be specialized
3643/// by this function specialization; the set will be modified to contain the
3644/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003645bool
John McCall1f82f242009-11-18 22:49:29 +00003646Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003647 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3648
3649 // Try to find the member we are instantiating.
3650 NamedDecl *Instantiation = 0;
3651 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003652 MemberSpecializationInfo *MSInfo = 0;
3653
John McCall1f82f242009-11-18 22:49:29 +00003654 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003655 // Nowhere to look anyway.
3656 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003657 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3658 I != E; ++I) {
3659 NamedDecl *D = (*I)->getUnderlyingDecl();
3660 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003661 if (Context.hasSameType(Function->getType(), Method->getType())) {
3662 Instantiation = Method;
3663 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003664 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003665 break;
3666 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003667 }
3668 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003669 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003670 VarDecl *PrevVar;
3671 if (Previous.isSingleResult() &&
3672 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00003673 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00003674 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003675 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003676 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003677 }
3678 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003679 CXXRecordDecl *PrevRecord;
3680 if (Previous.isSingleResult() &&
3681 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3682 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003683 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003684 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003685 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003686 }
3687
3688 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003689 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003690 // specializations are always out-of-line, the caller will complain about
3691 // this mismatch later.
3692 return false;
3693 }
3694
Douglas Gregor86d142a2009-10-08 07:24:58 +00003695 // Make sure that this is a specialization of a member.
3696 if (!InstantiatedFrom) {
3697 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3698 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003699 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3700 return true;
3701 }
3702
Douglas Gregor06db9f52009-10-12 20:18:28 +00003703 // C++ [temp.expl.spec]p6:
3704 // If a template, a member template or the member of a class template is
3705 // explicitly specialized then that spe- cialization shall be declared
3706 // before the first use of that specialization that would cause an implicit
3707 // instantiation to take place, in every translation unit in which such a
3708 // use occurs; no diagnostic is required.
3709 assert(MSInfo && "Member specialization info missing?");
3710 if (MSInfo->getPointOfInstantiation().isValid()) {
3711 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3712 << Member;
3713 Diag(MSInfo->getPointOfInstantiation(),
3714 diag::note_instantiation_required_here)
3715 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3716 return true;
3717 }
3718
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003719 // Check the scope of this explicit specialization.
3720 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003721 InstantiatedFrom,
3722 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003723 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003724 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003725
Douglas Gregor86d142a2009-10-08 07:24:58 +00003726 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003727 // the original declaration to note that it is an explicit specialization
3728 // (if it was previously an implicit instantiation). This latter step
3729 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003730 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003731 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3732 if (InstantiationFunction->getTemplateSpecializationKind() ==
3733 TSK_ImplicitInstantiation) {
3734 InstantiationFunction->setTemplateSpecializationKind(
3735 TSK_ExplicitSpecialization);
3736 InstantiationFunction->setLocation(Member->getLocation());
3737 }
3738
Douglas Gregor86d142a2009-10-08 07:24:58 +00003739 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3740 cast<CXXMethodDecl>(InstantiatedFrom),
3741 TSK_ExplicitSpecialization);
3742 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003743 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3744 if (InstantiationVar->getTemplateSpecializationKind() ==
3745 TSK_ImplicitInstantiation) {
3746 InstantiationVar->setTemplateSpecializationKind(
3747 TSK_ExplicitSpecialization);
3748 InstantiationVar->setLocation(Member->getLocation());
3749 }
3750
Douglas Gregor86d142a2009-10-08 07:24:58 +00003751 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3752 cast<VarDecl>(InstantiatedFrom),
3753 TSK_ExplicitSpecialization);
3754 } else {
3755 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003756 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3757 if (InstantiationClass->getTemplateSpecializationKind() ==
3758 TSK_ImplicitInstantiation) {
3759 InstantiationClass->setTemplateSpecializationKind(
3760 TSK_ExplicitSpecialization);
3761 InstantiationClass->setLocation(Member->getLocation());
3762 }
3763
Douglas Gregor86d142a2009-10-08 07:24:58 +00003764 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003765 cast<CXXRecordDecl>(InstantiatedFrom),
3766 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003767 }
3768
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003769 // Save the caller the trouble of having to figure out which declaration
3770 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00003771 Previous.clear();
3772 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003773 return false;
3774}
3775
Douglas Gregore47f5a72009-10-14 23:41:34 +00003776/// \brief Check the scope of an explicit instantiation.
3777static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3778 SourceLocation InstLoc,
3779 bool WasQualifiedName) {
3780 DeclContext *ExpectedContext
3781 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3782 DeclContext *CurContext = S.CurContext->getLookupContext();
3783
3784 // C++0x [temp.explicit]p2:
3785 // An explicit instantiation shall appear in an enclosing namespace of its
3786 // template.
3787 //
3788 // This is DR275, which we do not retroactively apply to C++98/03.
3789 if (S.getLangOptions().CPlusPlus0x &&
3790 !CurContext->Encloses(ExpectedContext)) {
3791 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3792 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3793 << D << NS;
3794 else
3795 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3796 << D;
3797 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3798 return;
3799 }
3800
3801 // C++0x [temp.explicit]p2:
3802 // If the name declared in the explicit instantiation is an unqualified
3803 // name, the explicit instantiation shall appear in the namespace where
3804 // its template is declared or, if that namespace is inline (7.3.1), any
3805 // namespace from its enclosing namespace set.
3806 if (WasQualifiedName)
3807 return;
3808
3809 if (CurContext->Equals(ExpectedContext))
3810 return;
3811
3812 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3813 << D << ExpectedContext;
3814 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3815}
3816
3817/// \brief Determine whether the given scope specifier has a template-id in it.
3818static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3819 if (!SS.isSet())
3820 return false;
3821
3822 // C++0x [temp.explicit]p2:
3823 // If the explicit instantiation is for a member function, a member class
3824 // or a static data member of a class template specialization, the name of
3825 // the class template specialization in the qualified-id for the member
3826 // name shall be a simple-template-id.
3827 //
3828 // C++98 has the same restriction, just worded differently.
3829 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3830 NNS; NNS = NNS->getPrefix())
3831 if (Type *T = NNS->getAsType())
3832 if (isa<TemplateSpecializationType>(T))
3833 return true;
3834
3835 return false;
3836}
3837
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003838// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003839// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003840Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003841Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003842 SourceLocation ExternLoc,
3843 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003844 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003845 SourceLocation KWLoc,
3846 const CXXScopeSpec &SS,
3847 TemplateTy TemplateD,
3848 SourceLocation TemplateNameLoc,
3849 SourceLocation LAngleLoc,
3850 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00003851 SourceLocation RAngleLoc,
3852 AttributeList *Attr) {
3853 // Find the class template we're specializing
3854 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003855 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003856 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3857
3858 // Check that the specialization uses the same tag kind as the
3859 // original template.
3860 TagDecl::TagKind Kind;
3861 switch (TagSpec) {
3862 default: assert(0 && "Unknown tag type!");
3863 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3864 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3865 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3866 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003867 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003868 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003869 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003870 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003871 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003872 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003873 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003874 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003875 diag::note_previous_use);
3876 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3877 }
3878
Douglas Gregore47f5a72009-10-14 23:41:34 +00003879 // C++0x [temp.explicit]p2:
3880 // There are two forms of explicit instantiation: an explicit instantiation
3881 // definition and an explicit instantiation declaration. An explicit
3882 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00003883 TemplateSpecializationKind TSK
3884 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3885 : TSK_ExplicitInstantiationDeclaration;
3886
Douglas Gregora1f49972009-05-13 00:25:59 +00003887 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003888 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003889 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00003890
3891 // Check that the template argument list is well-formed for this
3892 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003893 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3894 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003895 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3896 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003897 return true;
3898
Mike Stump11289f42009-09-09 15:08:12 +00003899 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003900 ClassTemplate->getTemplateParameters()->size()) &&
3901 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003902
Douglas Gregora1f49972009-05-13 00:25:59 +00003903 // Find the class template specialization declaration that
3904 // corresponds to these arguments.
3905 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003906 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003907 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003908 Converted.flatSize(),
3909 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003910 void *InsertPos = 0;
3911 ClassTemplateSpecializationDecl *PrevDecl
3912 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3913
Douglas Gregor54888652009-10-07 00:13:32 +00003914 // C++0x [temp.explicit]p2:
3915 // [...] An explicit instantiation shall appear in an enclosing
3916 // namespace of its template. [...]
3917 //
3918 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00003919 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
3920 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00003921
Douglas Gregora1f49972009-05-13 00:25:59 +00003922 ClassTemplateSpecializationDecl *Specialization = 0;
3923
3924 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00003925 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003926 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00003927 PrevDecl,
3928 PrevDecl->getSpecializationKind(),
3929 PrevDecl->getPointOfInstantiation(),
3930 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00003931 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003932
Douglas Gregor12e49d32009-10-15 22:53:21 +00003933 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003934 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00003935
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003936 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3937 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3938 // Since the only prior class template specialization with these
3939 // arguments was referenced but not declared, reuse that
3940 // declaration node as our own, updating its source location to
3941 // reflect our new declaration.
3942 Specialization = PrevDecl;
3943 Specialization->setLocation(TemplateNameLoc);
3944 PrevDecl = 0;
3945 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00003946 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003947
3948 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003949 // Create a new class template specialization declaration node for
3950 // this explicit specialization.
3951 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003952 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003953 ClassTemplate->getDeclContext(),
3954 TemplateNameLoc,
3955 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003956 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003957
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003958 if (PrevDecl) {
3959 // Remove the previous declaration from the folding set, since we want
3960 // to introduce a new declaration.
3961 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3962 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3963 }
3964
3965 // Insert the new specialization.
3966 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003967 }
3968
3969 // Build the fully-sugared type for this explicit instantiation as
3970 // the user wrote in the explicit instantiation itself. This means
3971 // that we'll pretty-print the type retrieved from the
3972 // specialization's declaration the way that the user actually wrote
3973 // the explicit instantiation, rather than formatting the name based
3974 // on the "canonical" representation used to store the template
3975 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003976 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00003977 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00003978 Context.getTypeDeclType(Specialization));
3979 Specialization->setTypeAsWritten(WrittenTy);
3980 TemplateArgsIn.release();
3981
3982 // Add the explicit instantiation into its lexical context. However,
3983 // since explicit instantiations are never found by name lookup, we
3984 // just put it into the declaration context directly.
3985 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003986 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003987
3988 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003989 // A definition of a class template or class member template
3990 // shall be in scope at the point of the explicit instantiation of
3991 // the class template or class member template.
3992 //
3993 // This check comes when we actually try to perform the
3994 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00003995 ClassTemplateSpecializationDecl *Def
3996 = cast_or_null<ClassTemplateSpecializationDecl>(
3997 Specialization->getDefinition(Context));
3998 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00003999 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004000
4001 // Instantiate the members of this class template specialization.
4002 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4003 Specialization->getDefinition(Context));
4004 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00004005 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004006
4007 return DeclPtrTy::make(Specialization);
4008}
4009
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004010// Explicit instantiation of a member class of a class template.
4011Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004012Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004013 SourceLocation ExternLoc,
4014 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004015 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004016 SourceLocation KWLoc,
4017 const CXXScopeSpec &SS,
4018 IdentifierInfo *Name,
4019 SourceLocation NameLoc,
4020 AttributeList *Attr) {
4021
Douglas Gregord6ab8742009-05-28 23:31:59 +00004022 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004023 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004024 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004025 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004026 MultiTemplateParamsArg(*this, 0, 0),
4027 Owned, IsDependent);
4028 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4029
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004030 if (!TagD)
4031 return true;
4032
4033 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4034 if (Tag->isEnum()) {
4035 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4036 << Context.getTypeDeclType(Tag);
4037 return true;
4038 }
4039
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004040 if (Tag->isInvalidDecl())
4041 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004042
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004043 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4044 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4045 if (!Pattern) {
4046 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4047 << Context.getTypeDeclType(Record);
4048 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4049 return true;
4050 }
4051
Douglas Gregore47f5a72009-10-14 23:41:34 +00004052 // C++0x [temp.explicit]p2:
4053 // If the explicit instantiation is for a class or member class, the
4054 // elaborated-type-specifier in the declaration shall include a
4055 // simple-template-id.
4056 //
4057 // C++98 has the same restriction, just worded differently.
4058 if (!ScopeSpecifierHasTemplateId(SS))
4059 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4060 << Record << SS.getRange();
4061
4062 // C++0x [temp.explicit]p2:
4063 // There are two forms of explicit instantiation: an explicit instantiation
4064 // definition and an explicit instantiation declaration. An explicit
4065 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004066 TemplateSpecializationKind TSK
4067 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4068 : TSK_ExplicitInstantiationDeclaration;
4069
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004070 // C++0x [temp.explicit]p2:
4071 // [...] An explicit instantiation shall appear in an enclosing
4072 // namespace of its template. [...]
4073 //
4074 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004075 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004076
4077 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004078 CXXRecordDecl *PrevDecl
4079 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4080 if (!PrevDecl && Record->getDefinition(Context))
4081 PrevDecl = Record;
4082 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004083 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4084 bool SuppressNew = false;
4085 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004086 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004087 PrevDecl,
4088 MSInfo->getTemplateSpecializationKind(),
4089 MSInfo->getPointOfInstantiation(),
4090 SuppressNew))
4091 return true;
4092 if (SuppressNew)
4093 return TagD;
4094 }
4095
Douglas Gregor12e49d32009-10-15 22:53:21 +00004096 CXXRecordDecl *RecordDef
4097 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4098 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004099 // C++ [temp.explicit]p3:
4100 // A definition of a member class of a class template shall be in scope
4101 // at the point of an explicit instantiation of the member class.
4102 CXXRecordDecl *Def
4103 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4104 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004105 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4106 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004107 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4108 << Pattern;
4109 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004110 } else {
4111 if (InstantiateClass(NameLoc, Record, Def,
4112 getTemplateInstantiationArgs(Record),
4113 TSK))
4114 return true;
4115
4116 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4117 if (!RecordDef)
4118 return true;
4119 }
4120 }
4121
4122 // Instantiate all of the members of the class.
4123 InstantiateClassMembers(NameLoc, RecordDef,
4124 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004125
Mike Stump87c57ac2009-05-16 07:39:55 +00004126 // FIXME: We don't have any representation for explicit instantiations of
4127 // member classes. Such a representation is not needed for compilation, but it
4128 // should be available for clients that want to see all of the declarations in
4129 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004130 return TagD;
4131}
4132
Douglas Gregor450f00842009-09-25 18:43:00 +00004133Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4134 SourceLocation ExternLoc,
4135 SourceLocation TemplateLoc,
4136 Declarator &D) {
4137 // Explicit instantiations always require a name.
4138 DeclarationName Name = GetNameForDeclarator(D);
4139 if (!Name) {
4140 if (!D.isInvalidType())
4141 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4142 diag::err_explicit_instantiation_requires_name)
4143 << D.getDeclSpec().getSourceRange()
4144 << D.getSourceRange();
4145
4146 return true;
4147 }
4148
4149 // The scope passed in may not be a decl scope. Zip up the scope tree until
4150 // we find one that is.
4151 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4152 (S->getFlags() & Scope::TemplateParamScope) != 0)
4153 S = S->getParent();
4154
4155 // Determine the type of the declaration.
4156 QualType R = GetTypeForDeclarator(D, S, 0);
4157 if (R.isNull())
4158 return true;
4159
4160 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4161 // Cannot explicitly instantiate a typedef.
4162 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4163 << Name;
4164 return true;
4165 }
4166
Douglas Gregor3c74d412009-10-14 20:14:33 +00004167 // C++0x [temp.explicit]p1:
4168 // [...] An explicit instantiation of a function template shall not use the
4169 // inline or constexpr specifiers.
4170 // Presumably, this also applies to member functions of class templates as
4171 // well.
4172 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4173 Diag(D.getDeclSpec().getInlineSpecLoc(),
4174 diag::err_explicit_instantiation_inline)
4175 << CodeModificationHint::CreateRemoval(
4176 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
4177
4178 // FIXME: check for constexpr specifier.
4179
Douglas Gregore47f5a72009-10-14 23:41:34 +00004180 // C++0x [temp.explicit]p2:
4181 // There are two forms of explicit instantiation: an explicit instantiation
4182 // definition and an explicit instantiation declaration. An explicit
4183 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004184 TemplateSpecializationKind TSK
4185 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4186 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004187
John McCall27b18f82009-11-17 02:14:36 +00004188 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4189 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004190
4191 if (!R->isFunctionType()) {
4192 // C++ [temp.explicit]p1:
4193 // A [...] static data member of a class template can be explicitly
4194 // instantiated from the member definition associated with its class
4195 // template.
John McCall27b18f82009-11-17 02:14:36 +00004196 if (Previous.isAmbiguous())
4197 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004198
John McCall9f3059a2009-10-09 21:13:30 +00004199 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4200 Previous.getAsSingleDecl(Context));
Douglas Gregor450f00842009-09-25 18:43:00 +00004201 if (!Prev || !Prev->isStaticDataMember()) {
4202 // We expect to see a data data member here.
4203 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4204 << Name;
4205 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4206 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004207 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004208 return true;
4209 }
4210
4211 if (!Prev->getInstantiatedFromStaticDataMember()) {
4212 // FIXME: Check for explicit specialization?
4213 Diag(D.getIdentifierLoc(),
4214 diag::err_explicit_instantiation_data_member_not_instantiated)
4215 << Prev;
4216 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4217 // FIXME: Can we provide a note showing where this was declared?
4218 return true;
4219 }
4220
Douglas Gregore47f5a72009-10-14 23:41:34 +00004221 // C++0x [temp.explicit]p2:
4222 // If the explicit instantiation is for a member function, a member class
4223 // or a static data member of a class template specialization, the name of
4224 // the class template specialization in the qualified-id for the member
4225 // name shall be a simple-template-id.
4226 //
4227 // C++98 has the same restriction, just worded differently.
4228 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4229 Diag(D.getIdentifierLoc(),
4230 diag::err_explicit_instantiation_without_qualified_id)
4231 << Prev << D.getCXXScopeSpec().getRange();
4232
4233 // Check the scope of this explicit instantiation.
4234 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4235
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004236 // Verify that it is okay to explicitly instantiate here.
4237 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4238 assert(MSInfo && "Missing static data member specialization info?");
4239 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004240 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004241 MSInfo->getTemplateSpecializationKind(),
4242 MSInfo->getPointOfInstantiation(),
4243 SuppressNew))
4244 return true;
4245 if (SuppressNew)
4246 return DeclPtrTy();
4247
Douglas Gregor450f00842009-09-25 18:43:00 +00004248 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004249 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004250 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004251 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4252 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004253
4254 // FIXME: Create an ExplicitInstantiation node?
4255 return DeclPtrTy();
4256 }
4257
Douglas Gregor0e876e02009-09-25 23:53:26 +00004258 // If the declarator is a template-id, translate the parser's template
4259 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004260 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004261 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004262 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4263 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004264 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4265 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004266 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4267 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004268 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004269 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004270 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004271 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004272 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004273
Douglas Gregor450f00842009-09-25 18:43:00 +00004274 // C++ [temp.explicit]p1:
4275 // A [...] function [...] can be explicitly instantiated from its template.
4276 // A member function [...] of a class template can be explicitly
4277 // instantiated from the member definition associated with its class
4278 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004279 llvm::SmallVector<FunctionDecl *, 8> Matches;
4280 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4281 P != PEnd; ++P) {
4282 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004283 if (!HasExplicitTemplateArgs) {
4284 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4285 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4286 Matches.clear();
4287 Matches.push_back(Method);
4288 break;
4289 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004290 }
4291 }
4292
4293 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4294 if (!FunTmpl)
4295 continue;
4296
4297 TemplateDeductionInfo Info(Context);
4298 FunctionDecl *Specialization = 0;
4299 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004300 = DeduceTemplateArguments(FunTmpl,
4301 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004302 R, Specialization, Info)) {
4303 // FIXME: Keep track of almost-matches?
4304 (void)TDK;
4305 continue;
4306 }
4307
4308 Matches.push_back(Specialization);
4309 }
4310
4311 // Find the most specialized function template specialization.
4312 FunctionDecl *Specialization
4313 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4314 D.getIdentifierLoc(),
4315 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4316 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4317 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4318
4319 if (!Specialization)
4320 return true;
4321
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004322 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004323 Diag(D.getIdentifierLoc(),
4324 diag::err_explicit_instantiation_member_function_not_instantiated)
4325 << Specialization
4326 << (Specialization->getTemplateSpecializationKind() ==
4327 TSK_ExplicitSpecialization);
4328 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4329 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004330 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004331
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004332 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004333 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4334 PrevDecl = Specialization;
4335
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004336 if (PrevDecl) {
4337 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004338 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004339 PrevDecl,
4340 PrevDecl->getTemplateSpecializationKind(),
4341 PrevDecl->getPointOfInstantiation(),
4342 SuppressNew))
4343 return true;
4344
4345 // FIXME: We may still want to build some representation of this
4346 // explicit specialization.
4347 if (SuppressNew)
4348 return DeclPtrTy();
4349 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00004350
4351 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004352
4353 if (TSK == TSK_ExplicitInstantiationDefinition)
4354 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4355 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004356
Douglas Gregore47f5a72009-10-14 23:41:34 +00004357 // C++0x [temp.explicit]p2:
4358 // If the explicit instantiation is for a member function, a member class
4359 // or a static data member of a class template specialization, the name of
4360 // the class template specialization in the qualified-id for the member
4361 // name shall be a simple-template-id.
4362 //
4363 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004364 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004365 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004366 D.getCXXScopeSpec().isSet() &&
4367 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4368 Diag(D.getIdentifierLoc(),
4369 diag::err_explicit_instantiation_without_qualified_id)
4370 << Specialization << D.getCXXScopeSpec().getRange();
4371
4372 CheckExplicitInstantiationScope(*this,
4373 FunTmpl? (NamedDecl *)FunTmpl
4374 : Specialization->getInstantiatedFromMemberFunction(),
4375 D.getIdentifierLoc(),
4376 D.getCXXScopeSpec().isSet());
4377
Douglas Gregor450f00842009-09-25 18:43:00 +00004378 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4379 return DeclPtrTy();
4380}
4381
Douglas Gregor333489b2009-03-27 23:10:48 +00004382Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004383Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4384 const CXXScopeSpec &SS, IdentifierInfo *Name,
4385 SourceLocation TagLoc, SourceLocation NameLoc) {
4386 // This has to hold, because SS is expected to be defined.
4387 assert(Name && "Expected a name in a dependent tag");
4388
4389 NestedNameSpecifier *NNS
4390 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4391 if (!NNS)
4392 return true;
4393
4394 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4395 if (T.isNull())
4396 return true;
4397
4398 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4399 QualType ElabType = Context.getElaboratedType(T, TagKind);
4400
4401 return ElabType.getAsOpaquePtr();
4402}
4403
4404Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004405Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4406 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004407 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004408 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4409 if (!NNS)
4410 return true;
4411
4412 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004413 if (T.isNull())
4414 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004415 return T.getAsOpaquePtr();
4416}
4417
Douglas Gregordce2b622009-04-01 00:28:59 +00004418Sema::TypeResult
4419Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4420 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004421 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004422 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004423 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004424 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004425 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004426 assert(TemplateId && "Expected a template specialization type");
4427
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004428 if (computeDeclContext(SS, false)) {
4429 // If we can compute a declaration context, then the "typename"
4430 // keyword was superfluous. Just build a QualifiedNameType to keep
4431 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004432
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004433 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4434 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4435 }
Mike Stump11289f42009-09-09 15:08:12 +00004436
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004437 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004438}
4439
Douglas Gregor333489b2009-03-27 23:10:48 +00004440/// \brief Build the type that describes a C++ typename specifier,
4441/// e.g., "typename T::type".
4442QualType
4443Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4444 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004445 CXXRecordDecl *CurrentInstantiation = 0;
4446 if (NNS->isDependent()) {
4447 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004448
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004449 // If the nested-name-specifier does not refer to the current
4450 // instantiation, then build a typename type.
4451 if (!CurrentInstantiation)
4452 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004453
Douglas Gregorc707da62009-09-02 13:12:51 +00004454 // The nested-name-specifier refers to the current instantiation, so the
4455 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004456 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004457 // extraneous "typename" keywords, and we retroactively apply this DR to
4458 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004459 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004460
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004461 DeclContext *Ctx = 0;
4462
4463 if (CurrentInstantiation)
4464 Ctx = CurrentInstantiation;
4465 else {
4466 CXXScopeSpec SS;
4467 SS.setScopeRep(NNS);
4468 SS.setRange(Range);
4469 if (RequireCompleteDeclContext(SS))
4470 return QualType();
4471
4472 Ctx = computeDeclContext(SS);
4473 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004474 assert(Ctx && "No declaration context?");
4475
4476 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00004477 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4478 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00004479 unsigned DiagID = 0;
4480 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00004481 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004482 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004483 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004484 break;
4485
4486 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004487 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004488 // We found a type. Build a QualifiedNameType, since the
4489 // typename-specifier was just sugar. FIXME: Tell
4490 // QualifiedNameType that it has a "typename" prefix.
4491 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4492 }
4493
4494 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004495 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004496 break;
4497
John McCalle61f2ba2009-11-18 02:36:19 +00004498 case LookupResult::FoundUnresolvedValue:
4499 llvm::llvm_unreachable("unresolved using decl in non-dependent context");
4500 return QualType();
4501
Douglas Gregor333489b2009-03-27 23:10:48 +00004502 case LookupResult::FoundOverloaded:
4503 DiagID = diag::err_typename_nested_not_type;
4504 Referenced = *Result.begin();
4505 break;
4506
John McCall6538c932009-10-10 05:48:19 +00004507 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004508 return QualType();
4509 }
4510
4511 // If we get here, it's because name lookup did not find a
4512 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004513 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004514 if (Referenced)
4515 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4516 << Name;
4517 return QualType();
4518}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004519
4520namespace {
4521 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00004522 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4523 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004524 SourceLocation Loc;
4525 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004526
Douglas Gregor15acfb92009-08-06 16:20:37 +00004527 public:
Mike Stump11289f42009-09-09 15:08:12 +00004528 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004529 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004530 DeclarationName Entity)
4531 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004532 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004533
4534 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004535 /// transformed.
4536 ///
4537 /// For the purposes of type reconstruction, a type has already been
4538 /// transformed if it is NULL or if it is not dependent.
4539 bool AlreadyTransformed(QualType T) {
4540 return T.isNull() || !T->isDependentType();
4541 }
Mike Stump11289f42009-09-09 15:08:12 +00004542
4543 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004544 /// rebuilt.
4545 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004546
Douglas Gregor15acfb92009-08-06 16:20:37 +00004547 /// \brief Returns the name of the entity whose type is being rebuilt.
4548 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004549
Douglas Gregoref6ab412009-10-27 06:26:26 +00004550 /// \brief Sets the "base" location and entity when that
4551 /// information is known based on another transformation.
4552 void setBase(SourceLocation Loc, DeclarationName Entity) {
4553 this->Loc = Loc;
4554 this->Entity = Entity;
4555 }
4556
Douglas Gregor15acfb92009-08-06 16:20:37 +00004557 /// \brief Transforms an expression by returning the expression itself
4558 /// (an identity function).
4559 ///
4560 /// FIXME: This is completely unsafe; we will need to actually clone the
4561 /// expressions.
4562 Sema::OwningExprResult TransformExpr(Expr *E) {
4563 return getSema().Owned(E);
4564 }
Mike Stump11289f42009-09-09 15:08:12 +00004565
Douglas Gregor15acfb92009-08-06 16:20:37 +00004566 /// \brief Transforms a typename type by determining whether the type now
4567 /// refers to a member of the current instantiation, and then
4568 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004569 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004570 };
4571}
4572
Mike Stump11289f42009-09-09 15:08:12 +00004573QualType
John McCall550e0c22009-10-21 00:40:46 +00004574CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4575 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004576 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004577
Douglas Gregor15acfb92009-08-06 16:20:37 +00004578 NestedNameSpecifier *NNS
4579 = TransformNestedNameSpecifier(T->getQualifier(),
4580 /*FIXME:*/SourceRange(getBaseLocation()));
4581 if (!NNS)
4582 return QualType();
4583
4584 // If the nested-name-specifier did not change, and we cannot compute the
4585 // context corresponding to the nested-name-specifier, then this
4586 // typename type will not change; exit early.
4587 CXXScopeSpec SS;
4588 SS.setRange(SourceRange(getBaseLocation()));
4589 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004590
4591 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004592 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004593 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004594
4595 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004596 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004597 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004598 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004599 = TransformType(QualType(TemplateId, 0));
4600 if (NewTemplateId.isNull())
4601 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004602
Douglas Gregor15acfb92009-08-06 16:20:37 +00004603 if (NNS == T->getQualifier() &&
4604 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004605 Result = QualType(T, 0);
4606 else
4607 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4608 } else
4609 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4610 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004611
John McCall0ad16662009-10-29 08:12:44 +00004612 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4613 NewTL.setNameLoc(TL.getNameLoc());
4614 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004615}
4616
4617/// \brief Rebuilds a type within the context of the current instantiation.
4618///
Mike Stump11289f42009-09-09 15:08:12 +00004619/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004620/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004621/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004622/// partial specialization thereof). This routine will rebuild that type now
4623/// that we have entered the declarator's scope, which may produce different
4624/// canonical types, e.g.,
4625///
4626/// \code
4627/// template<typename T>
4628/// struct X {
4629/// typedef T* pointer;
4630/// pointer data();
4631/// };
4632///
4633/// template<typename T>
4634/// typename X<T>::pointer X<T>::data() { ... }
4635/// \endcode
4636///
4637/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4638/// since we do not know that we can look into X<T> when we parsed the type.
4639/// This function will rebuild the type, performing the lookup of "pointer"
4640/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4641/// as the canonical type of T*, allowing the return types of the out-of-line
4642/// definition and the declaration to match.
4643QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4644 DeclarationName Name) {
4645 if (T.isNull() || !T->isDependentType())
4646 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004647
Douglas Gregor15acfb92009-08-06 16:20:37 +00004648 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4649 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004650}
Douglas Gregorbe999392009-09-15 16:23:51 +00004651
4652/// \brief Produces a formatted string that describes the binding of
4653/// template parameters to template arguments.
4654std::string
4655Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4656 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004657 // FIXME: For variadic templates, we'll need to get the structured list.
4658 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4659 Args.flat_size());
4660}
4661
4662std::string
4663Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4664 const TemplateArgument *Args,
4665 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004666 std::string Result;
4667
Douglas Gregore62e6a02009-11-11 19:13:48 +00004668 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00004669 return Result;
4670
4671 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004672 if (I >= NumArgs)
4673 break;
4674
Douglas Gregorbe999392009-09-15 16:23:51 +00004675 if (I == 0)
4676 Result += "[with ";
4677 else
4678 Result += ", ";
4679
4680 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4681 Result += Id->getName();
4682 } else {
4683 Result += '$';
4684 Result += llvm::utostr(I);
4685 }
4686
4687 Result += " = ";
4688
4689 switch (Args[I].getKind()) {
4690 case TemplateArgument::Null:
4691 Result += "<no value>";
4692 break;
4693
4694 case TemplateArgument::Type: {
4695 std::string TypeStr;
4696 Args[I].getAsType().getAsStringInternal(TypeStr,
4697 Context.PrintingPolicy);
4698 Result += TypeStr;
4699 break;
4700 }
4701
4702 case TemplateArgument::Declaration: {
4703 bool Unnamed = true;
4704 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4705 if (ND->getDeclName()) {
4706 Unnamed = false;
4707 Result += ND->getNameAsString();
4708 }
4709 }
4710
4711 if (Unnamed) {
4712 Result += "<anonymous>";
4713 }
4714 break;
4715 }
4716
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004717 case TemplateArgument::Template: {
4718 std::string Str;
4719 llvm::raw_string_ostream OS(Str);
4720 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4721 Result += OS.str();
4722 break;
4723 }
4724
Douglas Gregorbe999392009-09-15 16:23:51 +00004725 case TemplateArgument::Integral: {
4726 Result += Args[I].getAsIntegral()->toString(10);
4727 break;
4728 }
4729
4730 case TemplateArgument::Expression: {
4731 assert(false && "No expressions in deduced template arguments!");
4732 Result += "<expression>";
4733 break;
4734 }
4735
4736 case TemplateArgument::Pack:
4737 // FIXME: Format template argument packs
4738 Result += "<template argument pack>";
4739 break;
4740 }
4741 }
4742
4743 Result += ']';
4744 return Result;
4745}