blob: af7634ae86aa2a63ac7cf483af63de7c29f2d533 [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000019#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000020#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000021#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000022#include "llvm/Support/Compiler.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000023#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000024using namespace clang;
25
Douglas Gregorb7bfe792009-09-02 22:59:36 +000026/// \brief Determine whether the declaration found is acceptable as the name
27/// of a template and, if so, return that template declaration. Otherwise,
28/// returns NULL.
29static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
30 if (!D)
31 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000032
Douglas Gregorb7bfe792009-09-02 22:59:36 +000033 if (isa<TemplateDecl>(D))
34 return D;
Mike Stump11289f42009-09-09 15:08:12 +000035
Douglas Gregorb7bfe792009-09-02 22:59:36 +000036 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
37 // C++ [temp.local]p1:
38 // Like normal (non-template) classes, class templates have an
39 // injected-class-name (Clause 9). The injected-class-name
40 // can be used with or without a template-argument-list. When
41 // it is used without a template-argument-list, it is
42 // equivalent to the injected-class-name followed by the
43 // template-parameters of the class template enclosed in
44 // <>. When it is used with a template-argument-list, it
45 // refers to the specified class template specialization,
46 // which could be the current specialization or another
47 // specialization.
48 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000049 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000050 if (Record->getDescribedClassTemplate())
51 return Record->getDescribedClassTemplate();
52
53 if (ClassTemplateSpecializationDecl *Spec
54 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
55 return Spec->getSpecializedTemplate();
56 }
Mike Stump11289f42009-09-09 15:08:12 +000057
Douglas Gregorb7bfe792009-09-02 22:59:36 +000058 return 0;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Douglas Gregorb7bfe792009-09-02 22:59:36 +000061 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
62 if (!Ovl)
63 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000064
Douglas Gregorb7bfe792009-09-02 22:59:36 +000065 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
66 FEnd = Ovl->function_end();
67 F != FEnd; ++F) {
68 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
69 // We've found a function template. Determine whether there are
70 // any other function templates we need to bundle together in an
71 // OverloadedFunctionDecl
72 for (++F; F != FEnd; ++F) {
73 if (isa<FunctionTemplateDecl>(*F))
74 break;
75 }
Mike Stump11289f42009-09-09 15:08:12 +000076
Douglas Gregorb7bfe792009-09-02 22:59:36 +000077 if (F != FEnd) {
78 // Build an overloaded function decl containing only the
79 // function templates in Ovl.
Mike Stump11289f42009-09-09 15:08:12 +000080 OverloadedFunctionDecl *OvlTemplate
Douglas Gregorb7bfe792009-09-02 22:59:36 +000081 = OverloadedFunctionDecl::Create(Context,
82 Ovl->getDeclContext(),
83 Ovl->getDeclName());
84 OvlTemplate->addOverload(FuncTmpl);
85 OvlTemplate->addOverload(*F);
86 for (++F; F != FEnd; ++F) {
87 if (isa<FunctionTemplateDecl>(*F))
88 OvlTemplate->addOverload(*F);
89 }
Mike Stump11289f42009-09-09 15:08:12 +000090
Douglas Gregorb7bfe792009-09-02 22:59:36 +000091 return OvlTemplate;
92 }
93
94 return FuncTmpl;
95 }
96 }
Mike Stump11289f42009-09-09 15:08:12 +000097
Douglas Gregorb7bfe792009-09-02 22:59:36 +000098 return 0;
99}
100
101TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000102 const CXXScopeSpec &SS,
103 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000104 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000105 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000106 TemplateTy &TemplateResult) {
Douglas Gregor3cf81312009-11-03 23:16:33 +0000107 DeclarationName TName;
108
109 switch (Name.getKind()) {
110 case UnqualifiedId::IK_Identifier:
111 TName = DeclarationName(Name.Identifier);
112 break;
113
114 case UnqualifiedId::IK_OperatorFunctionId:
115 TName = Context.DeclarationNames.getCXXOperatorName(
116 Name.OperatorFunctionId.Operator);
117 break;
118
119 default:
120 return TNK_Non_template;
121 }
122
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000123 // Determine where to perform name lookup
124 DeclContext *LookupCtx = 0;
125 bool isDependent = false;
126 if (ObjectTypePtr) {
127 // This nested-name-specifier occurs in a member access expression, e.g.,
128 // x->B::f, and we are looking into the type of the object.
Douglas Gregor3cf81312009-11-03 23:16:33 +0000129 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000130 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
131 LookupCtx = computeDeclContext(ObjectType);
132 isDependent = ObjectType->isDependentType();
Douglas Gregor3cf81312009-11-03 23:16:33 +0000133 } else if (SS.isSet()) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000134 // This nested-name-specifier occurs after another nested-name-specifier,
135 // so long into the context associated with the prior nested-name-specifier.
136
Douglas Gregor3cf81312009-11-03 23:16:33 +0000137 LookupCtx = computeDeclContext(SS, EnteringContext);
138 isDependent = isDependentScopeSpecifier(SS);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000139 }
Mike Stump11289f42009-09-09 15:08:12 +0000140
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000141 LookupResult Found;
142 bool ObjectTypeSearchedInScope = false;
143 if (LookupCtx) {
144 // Perform "qualified" name lookup into the declaration context we
145 // computed, which is either the type of the base of a member access
Mike Stump11289f42009-09-09 15:08:12 +0000146 // expression or the declaration context associated with a prior
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000147 // nested-name-specifier.
148
149 // The declaration context must be complete.
Douglas Gregor3cf81312009-11-03 23:16:33 +0000150 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(SS))
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000151 return TNK_Non_template;
Mike Stump11289f42009-09-09 15:08:12 +0000152
Douglas Gregor3cf81312009-11-03 23:16:33 +0000153 LookupQualifiedName(Found, LookupCtx, TName, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +0000154
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000155 if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
156 // C++ [basic.lookup.classref]p1:
157 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump11289f42009-09-09 15:08:12 +0000158 // immediately followed by an identifier followed by a <, the
159 // identifier must be looked up to determine whether the < is the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000160 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump11289f42009-09-09 15:08:12 +0000161 // The identifier is first looked up in the class of the object
162 // expression. If the identifier is not found, it is then looked up in
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000163 // the context of the entire postfix-expression and shall name a class
164 // or function template.
165 //
166 // FIXME: When we're instantiating a template, do we actually have to
167 // look in the scope of the template? Seems fishy...
Douglas Gregor3cf81312009-11-03 23:16:33 +0000168 LookupName(Found, S, TName, LookupOrdinaryName);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000169 ObjectTypeSearchedInScope = true;
170 }
171 } else if (isDependent) {
Mike Stump11289f42009-09-09 15:08:12 +0000172 // We cannot look into a dependent object type or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000173 return TNK_Non_template;
174 } else {
175 // Perform unqualified name lookup in the current scope.
Douglas Gregor3cf81312009-11-03 23:16:33 +0000176 LookupName(Found, S, TName, LookupOrdinaryName);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000177 }
Mike Stump11289f42009-09-09 15:08:12 +0000178
Douglas Gregore861bac2009-08-25 22:51:20 +0000179 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump11289f42009-09-09 15:08:12 +0000180 assert(!Found.isAmbiguous() &&
Douglas Gregore861bac2009-08-25 22:51:20 +0000181 "Cannot handle template name-lookup ambiguities");
Douglas Gregordc572a32009-03-30 22:58:21 +0000182
John McCall9f3059a2009-10-09 21:13:30 +0000183 NamedDecl *Template
184 = isAcceptableTemplateName(Context, Found.getAsSingleDecl(Context));
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000185 if (!Template)
186 return TNK_Non_template;
187
188 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
189 // C++ [basic.lookup.classref]p1:
Mike Stump11289f42009-09-09 15:08:12 +0000190 // [...] If the lookup in the class of the object expression finds a
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000191 // template, the name is also looked up in the context of the entire
192 // postfix-expression and [...]
193 //
John McCall9f3059a2009-10-09 21:13:30 +0000194 LookupResult FoundOuter;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000195 LookupName(FoundOuter, S, TName, LookupOrdinaryName);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000196 // FIXME: Handle ambiguities in this lookup better
John McCall9f3059a2009-10-09 21:13:30 +0000197 NamedDecl *OuterTemplate
198 = isAcceptableTemplateName(Context, FoundOuter.getAsSingleDecl(Context));
Mike Stump11289f42009-09-09 15:08:12 +0000199
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000200 if (!OuterTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +0000201 // - if the name is not found, the name found in the class of the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000202 // object expression is used, otherwise
203 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump11289f42009-09-09 15:08:12 +0000204 // - if the name is found in the context of the entire
205 // postfix-expression and does not name a class template, the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000206 // found in the class of the object expression is used, otherwise
207 } else {
208 // - if the name found is a class template, it must refer to the same
Mike Stump11289f42009-09-09 15:08:12 +0000209 // entity as the one found in the class of the object expression,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000210 // otherwise the program is ill-formed.
211 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
Douglas Gregor3cf81312009-11-03 23:16:33 +0000212 Diag(Name.getSourceRange().getBegin(),
213 diag::err_nested_name_member_ref_lookup_ambiguous)
214 << TName
215 << Name.getSourceRange();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000216 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
217 << QualType::getFromOpaquePtr(ObjectTypePtr);
218 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump11289f42009-09-09 15:08:12 +0000219
220 // Recover by taking the template that we found in the object
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000221 // expression's type.
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000222 }
Mike Stump11289f42009-09-09 15:08:12 +0000223 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000224 }
Mike Stump11289f42009-09-09 15:08:12 +0000225
Douglas Gregor3cf81312009-11-03 23:16:33 +0000226 if (SS.isSet() && !SS.isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000227 NestedNameSpecifier *Qualifier
Douglas Gregor3cf81312009-11-03 23:16:33 +0000228 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000229 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000230 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000231 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000232 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
233 Ovl));
234 else
Mike Stump11289f42009-09-09 15:08:12 +0000235 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000236 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000237 cast<TemplateDecl>(Template)));
238 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000239 = dyn_cast<OverloadedFunctionDecl>(Template)) {
240 TemplateResult = TemplateTy::make(TemplateName(Ovl));
241 } else {
242 TemplateResult = TemplateTy::make(
243 TemplateName(cast<TemplateDecl>(Template)));
244 }
Mike Stump11289f42009-09-09 15:08:12 +0000245
246 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000247 isa<TemplateTemplateParmDecl>(Template))
248 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000249
250 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000251 isa<OverloadedFunctionDecl>(Template)) &&
252 "Unhandled template kind in Sema::isTemplateName");
253 return TNK_Function_template;
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000254}
255
Douglas Gregor5101c242008-12-05 18:15:24 +0000256/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
257/// that the template parameter 'PrevDecl' is being shadowed by a new
258/// declaration at location Loc. Returns true to indicate that this is
259/// an error, and false otherwise.
260bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000261 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000262
263 // Microsoft Visual C++ permits template parameters to be shadowed.
264 if (getLangOptions().Microsoft)
265 return false;
266
267 // C++ [temp.local]p4:
268 // A template-parameter shall not be redeclared within its
269 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000270 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000271 << cast<NamedDecl>(PrevDecl)->getDeclName();
272 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
273 return true;
274}
275
Douglas Gregor463421d2009-03-03 04:44:36 +0000276/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000277/// the parameter D to reference the templated declaration and return a pointer
278/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000279TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000280 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000281 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000282 return Temp;
283 }
284 return 0;
285}
286
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000287static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
288 const ParsedTemplateArgument &Arg) {
289
290 switch (Arg.getKind()) {
291 case ParsedTemplateArgument::Type: {
292 DeclaratorInfo *DI;
293 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
294 if (!DI)
295 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation());
296 return TemplateArgumentLoc(TemplateArgument(T), DI);
297 }
298
299 case ParsedTemplateArgument::NonType: {
300 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
301 return TemplateArgumentLoc(TemplateArgument(E), E);
302 }
303
304 case ParsedTemplateArgument::Template: {
305 TemplateName Template
306 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
307 return TemplateArgumentLoc(TemplateArgument(Template),
308 Arg.getScopeSpec().getRange(),
309 Arg.getLocation());
310 }
311 }
312
313 llvm::llvm_unreachable("Unhandled parsed template argument");
314 return TemplateArgumentLoc();
315}
316
317/// \brief Translates template arguments as provided by the parser
318/// into template arguments used by semantic analysis.
319void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
320 llvm::SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs) {
321 TemplateArgs.reserve(TemplateArgsIn.size());
322
323 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
324 TemplateArgs.push_back(translateTemplateArgument(*this, TemplateArgsIn[I]));
325}
326
Douglas Gregor5101c242008-12-05 18:15:24 +0000327/// ActOnTypeParameter - Called when a C++ template type parameter
328/// (e.g., "typename T") has been parsed. Typename specifies whether
329/// the keyword "typename" was used to declare the type parameter
330/// (otherwise, "class" was used), and KeyLoc is the location of the
331/// "class" or "typename" keyword. ParamName is the name of the
332/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000333/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000334/// If the type parameter has a default argument, it will be added
335/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000336Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000337 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000338 SourceLocation KeyLoc,
339 IdentifierInfo *ParamName,
340 SourceLocation ParamNameLoc,
341 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000342 assert(S->isTemplateParamScope() &&
343 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000344 bool Invalid = false;
345
346 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000347 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000348 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000349 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000350 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000351 }
352
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000353 SourceLocation Loc = ParamNameLoc;
354 if (!ParamName)
355 Loc = KeyLoc;
356
Douglas Gregor5101c242008-12-05 18:15:24 +0000357 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000358 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
359 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000360 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000361 if (Invalid)
362 Param->setInvalidDecl();
363
364 if (ParamName) {
365 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000366 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000367 IdResolver.AddDecl(Param);
368 }
369
Chris Lattner83f095c2009-03-28 19:18:32 +0000370 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000371}
372
Douglas Gregordba32632009-02-10 19:49:53 +0000373/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000374/// Default) to the given template type parameter (TypeParam).
375void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000376 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000377 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000378 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000379 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000380 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000381
382 DeclaratorInfo *DefaultDInfo;
383 GetTypeFromParser(DefaultT, &DefaultDInfo);
384
385 assert(DefaultDInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000386
Anders Carlssond3824352009-06-12 22:30:13 +0000387 // C++0x [temp.param]p9:
388 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000389 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000390 if (Parm->isParameterPack()) {
391 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000392 return;
393 }
Mike Stump11289f42009-09-09 15:08:12 +0000394
Douglas Gregordba32632009-02-10 19:49:53 +0000395 // C++ [temp.param]p14:
396 // A template-parameter shall not be used in its own default argument.
397 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000398
Douglas Gregordba32632009-02-10 19:49:53 +0000399 // Check the template argument itself.
John McCall0ad16662009-10-29 08:12:44 +0000400 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000401 Parm->setInvalidDecl();
402 return;
403 }
404
John McCall0ad16662009-10-29 08:12:44 +0000405 Parm->setDefaultArgument(DefaultDInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000406}
407
Douglas Gregor463421d2009-03-03 04:44:36 +0000408/// \brief Check that the type of a non-type template parameter is
409/// well-formed.
410///
411/// \returns the (possibly-promoted) parameter type if valid;
412/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000413QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000414Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
415 // C++ [temp.param]p4:
416 //
417 // A non-type template-parameter shall have one of the following
418 // (optionally cv-qualified) types:
419 //
420 // -- integral or enumeration type,
421 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000422 // -- pointer to object or pointer to function,
423 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000424 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
425 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000426 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000427 T->isReferenceType() ||
428 // -- pointer to member.
429 T->isMemberPointerType() ||
430 // If T is a dependent type, we can't do the check now, so we
431 // assume that it is well-formed.
432 T->isDependentType())
433 return T;
434 // C++ [temp.param]p8:
435 //
436 // A non-type template-parameter of type "array of T" or
437 // "function returning T" is adjusted to be of type "pointer to
438 // T" or "pointer to function returning T", respectively.
439 else if (T->isArrayType())
440 // FIXME: Keep the type prior to promotion?
441 return Context.getArrayDecayedType(T);
442 else if (T->isFunctionType())
443 // FIXME: Keep the type prior to promotion?
444 return Context.getPointerType(T);
445
446 Diag(Loc, diag::err_template_nontype_parm_bad_type)
447 << T;
448
449 return QualType();
450}
451
Douglas Gregor5101c242008-12-05 18:15:24 +0000452/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
453/// template parameter (e.g., "int Size" in "template<int Size>
454/// class Array") has been parsed. S is the current scope and D is
455/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000456Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000457 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000458 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000459 DeclaratorInfo *DInfo = 0;
460 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000461
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000462 assert(S->isTemplateParamScope() &&
463 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000464 bool Invalid = false;
465
466 IdentifierInfo *ParamName = D.getIdentifier();
467 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000468 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000469 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000470 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000471 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000472 }
473
Douglas Gregor463421d2009-03-03 04:44:36 +0000474 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000475 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000476 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000477 Invalid = true;
478 }
Douglas Gregor81338792009-02-10 17:43:50 +0000479
Douglas Gregor5101c242008-12-05 18:15:24 +0000480 NonTypeTemplateParmDecl *Param
481 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000482 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000483 if (Invalid)
484 Param->setInvalidDecl();
485
486 if (D.getIdentifier()) {
487 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000488 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000489 IdResolver.AddDecl(Param);
490 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000491 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000492}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000493
Douglas Gregordba32632009-02-10 19:49:53 +0000494/// \brief Adds a default argument to the given non-type template
495/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000496void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000497 SourceLocation EqualLoc,
498 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000499 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000500 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000501 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000502
Douglas Gregordba32632009-02-10 19:49:53 +0000503 // C++ [temp.param]p14:
504 // A template-parameter shall not be used in its own default argument.
505 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000506
Douglas Gregordba32632009-02-10 19:49:53 +0000507 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000508 TemplateArgument Converted;
509 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
510 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000511 TemplateParm->setInvalidDecl();
512 return;
513 }
514
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000515 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000516}
517
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000518
519/// ActOnTemplateTemplateParameter - Called when a C++ template template
520/// parameter (e.g. T in template <template <typename> class T> class array)
521/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000522Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
523 SourceLocation TmpLoc,
524 TemplateParamsTy *Params,
525 IdentifierInfo *Name,
526 SourceLocation NameLoc,
527 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000528 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000529 assert(S->isTemplateParamScope() &&
530 "Template template parameter not in template parameter scope!");
531
532 // Construct the parameter object.
533 TemplateTemplateParmDecl *Param =
534 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
535 Position, Name,
536 (TemplateParameterList*)Params);
537
538 // Make sure the parameter is valid.
539 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
540 // do anything yet. However, if the template parameter list or (eventual)
541 // default value is ever invalidated, that will propagate here.
542 bool Invalid = false;
543 if (Invalid) {
544 Param->setInvalidDecl();
545 }
546
547 // If the tt-param has a name, then link the identifier into the scope
548 // and lookup mechanisms.
549 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000550 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000551 IdResolver.AddDecl(Param);
552 }
553
Chris Lattner83f095c2009-03-28 19:18:32 +0000554 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000555}
556
Douglas Gregordba32632009-02-10 19:49:53 +0000557/// \brief Adds a default argument to the given template template
558/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000559void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000560 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000561 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000562 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000563 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000564
Douglas Gregordba32632009-02-10 19:49:53 +0000565 // C++ [temp.param]p14:
566 // A template-parameter shall not be used in its own default argument.
567 // FIXME: Implement this check! Needs a recursive walk over the types.
568
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;
631 LookupResult Previous;
632 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000633 if (RequireCompleteDeclContext(SS))
634 return true;
635
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000636 SemanticContext = computeDeclContext(SS, true);
637 if (!SemanticContext) {
638 // FIXME: Produce a reasonable diagnostic here
639 return true;
640 }
Mike Stump11289f42009-09-09 15:08:12 +0000641
John McCall9f3059a2009-10-09 21:13:30 +0000642 LookupQualifiedName(Previous, SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000643 true);
644 } else {
645 SemanticContext = CurContext;
John McCall9f3059a2009-10-09 21:13:30 +0000646 LookupName(Previous, S, Name, LookupOrdinaryName, true);
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;
1051 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1052 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +00001053 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +00001054 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1055 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1056 if (!Template)
1057 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001058
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001059 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001060 ClassTemplateSpecializationDecl *SpecDecl
1061 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1062 // If the nested name specifier refers to an explicit specialization,
1063 // we don't need a template<> header.
Douglas Gregor82e22862009-09-16 00:01:48 +00001064 // FIXME: revisit this approach once we cope with specializations
Douglas Gregor15301382009-07-30 17:40:51 +00001065 // properly.
Douglas Gregord8d297c2009-07-21 23:53:31 +00001066 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
1067 continue;
1068 }
Mike Stump11289f42009-09-09 15:08:12 +00001069
Douglas Gregord8d297c2009-07-21 23:53:31 +00001070 TemplateIdsInSpecifier.push_back(SpecType);
1071 }
1072 }
Mike Stump11289f42009-09-09 15:08:12 +00001073
Douglas Gregord8d297c2009-07-21 23:53:31 +00001074 // Reverse the list of template-ids in the scope specifier, so that we can
1075 // more easily match up the template-ids and the template parameter lists.
1076 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001077
Douglas Gregord8d297c2009-07-21 23:53:31 +00001078 SourceLocation FirstTemplateLoc = DeclStartLoc;
1079 if (NumParamLists)
1080 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001081
Douglas Gregord8d297c2009-07-21 23:53:31 +00001082 // Match the template-ids found in the specifier to the template parameter
1083 // lists.
1084 unsigned Idx = 0;
1085 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1086 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001087 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1088 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001089 if (Idx >= NumParamLists) {
1090 // We have a template-id without a corresponding template parameter
1091 // list.
1092 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001093 // FIXME: the location information here isn't great.
1094 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001095 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001096 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001097 << SS.getRange();
1098 } else {
1099 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1100 << SS.getRange()
1101 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1102 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001103 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001104 }
1105 return 0;
1106 }
Mike Stump11289f42009-09-09 15:08:12 +00001107
Douglas Gregord8d297c2009-07-21 23:53:31 +00001108 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001109 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001110 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001111 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1112
Mike Stump11289f42009-09-09 15:08:12 +00001113 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001114 = dyn_cast<ClassTemplateDecl>(Template)) {
1115 TemplateParameterList *ExpectedTemplateParams = 0;
1116 // Is this template-id naming the primary template?
1117 if (Context.hasSameType(TemplateId,
1118 ClassTemplate->getInjectedClassNameType(Context)))
1119 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1120 // ... or a partial specialization?
1121 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1122 = ClassTemplate->findPartialSpecialization(TemplateId))
1123 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1124
1125 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001126 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001127 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001128 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001129 }
Douglas Gregor15301382009-07-30 17:40:51 +00001130 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001131 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001132 diag::err_template_param_list_matches_nontemplate)
1133 << TemplateId
1134 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001135 else
1136 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001137 }
Mike Stump11289f42009-09-09 15:08:12 +00001138
Douglas Gregord8d297c2009-07-21 23:53:31 +00001139 // If there were at least as many template-ids as there were template
1140 // parameter lists, then there are no template parameter lists remaining for
1141 // the declaration itself.
1142 if (Idx >= NumParamLists)
1143 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001144
Douglas Gregord8d297c2009-07-21 23:53:31 +00001145 // If there were too many template parameter lists, complain about that now.
1146 if (Idx != NumParamLists - 1) {
1147 while (Idx < NumParamLists - 1) {
Mike Stump11289f42009-09-09 15:08:12 +00001148 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001149 diag::err_template_spec_extra_headers)
1150 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1151 ParamLists[Idx]->getRAngleLoc());
1152 ++Idx;
1153 }
1154 }
Mike Stump11289f42009-09-09 15:08:12 +00001155
Douglas Gregord8d297c2009-07-21 23:53:31 +00001156 // Return the last template parameter list, which corresponds to the
1157 // entity being declared.
1158 return ParamLists[NumParamLists - 1];
1159}
1160
Douglas Gregordc572a32009-03-30 22:58:21 +00001161QualType Sema::CheckTemplateIdType(TemplateName Name,
1162 SourceLocation TemplateLoc,
1163 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001164 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregordc572a32009-03-30 22:58:21 +00001165 unsigned NumTemplateArgs,
1166 SourceLocation RAngleLoc) {
1167 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001168 if (!Template) {
1169 // The template name does not resolve to a template, so we just
1170 // build a dependent template-id type.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001171 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001172 NumTemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001173 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001174
Douglas Gregorc40290e2009-03-09 23:48:35 +00001175 // Check that the template argument list is well-formed for this
1176 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001177 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1178 NumTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001179 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001180 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001181 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001182 return QualType();
1183
Mike Stump11289f42009-09-09 15:08:12 +00001184 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001185 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001186 "Converted template argument list is too short!");
1187
1188 QualType CanonType;
1189
Douglas Gregordc572a32009-03-30 22:58:21 +00001190 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorc40290e2009-03-09 23:48:35 +00001191 TemplateArgs,
Douglas Gregordd6c0352009-11-12 00:46:20 +00001192 NumTemplateArgs) ||
1193 isa<TemplateTemplateParmDecl>(Template) ||
1194 Template->getDeclContext()->isDependentContext()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001195 // This class template specialization is a dependent
1196 // type. Therefore, its canonical type is another class template
1197 // specialization type that contains all of the converted
1198 // arguments in canonical form. This ensures that, e.g., A<T> and
1199 // A<T, T> have identical types when A is declared as:
1200 //
1201 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001202 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001203 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001204 Converted.getFlatArguments(),
1205 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001206
Douglas Gregora8e02e72009-07-28 23:00:59 +00001207 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001208 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001209 // In the future, we need to teach getTemplateSpecializationType to only
1210 // build the canonical type and return that to us.
1211 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001212 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001213 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001214 // Find the class template specialization declaration that
1215 // corresponds to these arguments.
1216 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001217 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001218 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001219 Converted.flatSize(),
1220 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001221 void *InsertPos = 0;
1222 ClassTemplateSpecializationDecl *Decl
1223 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1224 if (!Decl) {
1225 // This is the first time we have referenced this class template
1226 // specialization. Create the canonical declaration and add it to
1227 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001228 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001229 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001230 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001231 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001232 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001233 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1234 Decl->setLexicalDeclContext(CurContext);
1235 }
1236
1237 CanonType = Context.getTypeDeclType(Decl);
1238 }
Mike Stump11289f42009-09-09 15:08:12 +00001239
Douglas Gregorc40290e2009-03-09 23:48:35 +00001240 // Build the fully-sugared type for this class template
1241 // specialization, which refers back to the class template
1242 // specialization we created or found.
Douglas Gregordc572a32009-03-30 22:58:21 +00001243 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1244 NumTemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001245}
1246
Douglas Gregor67a65642009-02-17 23:15:12 +00001247Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001248Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001249 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001250 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001251 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001252 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001253
Douglas Gregorc40290e2009-03-09 23:48:35 +00001254 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00001255 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001256 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001257
Douglas Gregordc572a32009-03-30 22:58:21 +00001258 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +00001259 TemplateArgs.data(),
1260 TemplateArgs.size(),
Douglas Gregordc572a32009-03-30 22:58:21 +00001261 RAngleLoc);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001262 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001263
1264 if (Result.isNull())
1265 return true;
1266
John McCall0ad16662009-10-29 08:12:44 +00001267 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1268 TemplateSpecializationTypeLoc TL
1269 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1270 TL.setTemplateNameLoc(TemplateLoc);
1271 TL.setLAngleLoc(LAngleLoc);
1272 TL.setRAngleLoc(RAngleLoc);
1273 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1274 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1275
1276 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001277}
John McCall06f6fe8d2009-09-04 01:14:41 +00001278
John McCalld8fe9af2009-09-08 17:47:29 +00001279Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1280 TagUseKind TUK,
1281 DeclSpec::TST TagSpec,
1282 SourceLocation TagLoc) {
1283 if (TypeResult.isInvalid())
1284 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001285
John McCall0ad16662009-10-29 08:12:44 +00001286 // FIXME: preserve source info, ideally without copying the DI.
1287 DeclaratorInfo *DI;
1288 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001289
John McCalld8fe9af2009-09-08 17:47:29 +00001290 // Verify the tag specifier.
1291 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001292
John McCalld8fe9af2009-09-08 17:47:29 +00001293 if (const RecordType *RT = Type->getAs<RecordType>()) {
1294 RecordDecl *D = RT->getDecl();
1295
1296 IdentifierInfo *Id = D->getIdentifier();
1297 assert(Id && "templated class must have an identifier");
1298
1299 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1300 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001301 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001302 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1303 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001304 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001305 }
1306 }
1307
John McCalld8fe9af2009-09-08 17:47:29 +00001308 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1309
1310 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001311}
1312
Douglas Gregord019ff62009-10-22 17:20:55 +00001313Sema::OwningExprResult Sema::BuildTemplateIdExpr(NestedNameSpecifier *Qualifier,
1314 SourceRange QualifierRange,
1315 TemplateName Template,
Douglas Gregora727cb92009-06-30 22:34:41 +00001316 SourceLocation TemplateNameLoc,
1317 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001318 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001319 unsigned NumTemplateArgs,
1320 SourceLocation RAngleLoc) {
1321 // FIXME: Can we do any checking at this point? I guess we could check the
1322 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001323 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001324 // though.
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001325
1326 // Cope with an implicit member access in a C++ non-static member function.
1327 NamedDecl *D = Template.getAsTemplateDecl();
1328 if (!D)
1329 D = Template.getAsOverloadedFunctionDecl();
1330
Douglas Gregord019ff62009-10-22 17:20:55 +00001331 CXXScopeSpec SS;
1332 SS.setRange(QualifierRange);
1333 SS.setScopeRep(Qualifier);
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001334 QualType ThisType, MemberType;
Douglas Gregord019ff62009-10-22 17:20:55 +00001335 if (D && isImplicitMemberReference(&SS, D, TemplateNameLoc,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001336 ThisType, MemberType)) {
1337 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
1338 return Owned(MemberExpr::Create(Context, This, true,
Douglas Gregord019ff62009-10-22 17:20:55 +00001339 Qualifier, QualifierRange,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001340 D, TemplateNameLoc, true,
1341 LAngleLoc, TemplateArgs,
1342 NumTemplateArgs, RAngleLoc,
1343 Context.OverloadTy));
1344 }
1345
Douglas Gregord019ff62009-10-22 17:20:55 +00001346 return Owned(TemplateIdRefExpr::Create(Context, Context.OverloadTy,
1347 Qualifier, QualifierRange,
Douglas Gregora727cb92009-06-30 22:34:41 +00001348 Template, TemplateNameLoc, LAngleLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001349 TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001350 NumTemplateArgs, RAngleLoc));
1351}
1352
Douglas Gregord019ff62009-10-22 17:20:55 +00001353Sema::OwningExprResult Sema::ActOnTemplateIdExpr(const CXXScopeSpec &SS,
1354 TemplateTy TemplateD,
Douglas Gregora727cb92009-06-30 22:34:41 +00001355 SourceLocation TemplateNameLoc,
1356 SourceLocation LAngleLoc,
1357 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora727cb92009-06-30 22:34:41 +00001358 SourceLocation RAngleLoc) {
1359 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001360
Douglas Gregora727cb92009-06-30 22:34:41 +00001361 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00001362 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001363 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001364 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001365
Douglas Gregord019ff62009-10-22 17:20:55 +00001366 return BuildTemplateIdExpr((NestedNameSpecifier *)SS.getScopeRep(),
1367 SS.getRange(),
1368 Template, TemplateNameLoc, LAngleLoc,
Douglas Gregora727cb92009-06-30 22:34:41 +00001369 TemplateArgs.data(), TemplateArgs.size(),
1370 RAngleLoc);
1371}
1372
Douglas Gregorb67535d2009-03-31 00:43:58 +00001373/// \brief Form a dependent template name.
1374///
1375/// This action forms a dependent template name given the template
1376/// name and its (presumably dependent) scope specifier. For
1377/// example, given "MetaFun::template apply", the scope specifier \p
1378/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1379/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001380Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001381Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001382 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001383 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001384 TypeTy *ObjectType) {
Mike Stump11289f42009-09-09 15:08:12 +00001385 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001386 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1387 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001388 // C++0x [temp.names]p5:
1389 // If a name prefixed by the keyword template is not the name of
1390 // a template, the program is ill-formed. [Note: the keyword
1391 // template may not be applied to non-template members of class
1392 // templates. -end note ] [ Note: as is the case with the
1393 // typename prefix, the template prefix is allowed in cases
1394 // where it is not strictly necessary; i.e., when the
1395 // nested-name-specifier or the expression on the left of the ->
1396 // or . is not dependent on a template-parameter, or the use
1397 // does not appear in the scope of a template. -end note]
1398 //
1399 // Note: C++03 was more strict here, because it banned the use of
1400 // the "template" keyword prior to a template-name that was not a
1401 // dependent name. C++ DR468 relaxed this requirement (the
1402 // "template" keyword is now permitted). We follow the C++0x
1403 // rules, even in C++03 mode, retroactively applying the DR.
1404 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001405 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001406 false, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001407 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001408 Diag(Name.getSourceRange().getBegin(),
1409 diag::err_template_kw_refers_to_non_template)
1410 << GetNameFromUnqualifiedId(Name)
1411 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001412 return TemplateTy();
1413 }
1414
1415 return Template;
1416 }
1417
Mike Stump11289f42009-09-09 15:08:12 +00001418 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001419 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001420
1421 switch (Name.getKind()) {
1422 case UnqualifiedId::IK_Identifier:
1423 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1424 Name.Identifier));
1425
Douglas Gregor71395fa2009-11-04 00:56:37 +00001426 case UnqualifiedId::IK_OperatorFunctionId:
1427 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1428 Name.OperatorFunctionId.Operator));
1429
Douglas Gregor3cf81312009-11-03 23:16:33 +00001430 default:
1431 break;
1432 }
1433
1434 Diag(Name.getSourceRange().getBegin(),
1435 diag::err_template_kw_refers_to_non_template)
1436 << GetNameFromUnqualifiedId(Name)
1437 << Name.getSourceRange();
1438 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001439}
1440
Mike Stump11289f42009-09-09 15:08:12 +00001441bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001442 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001443 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001444 const TemplateArgument &Arg = AL.getArgument();
1445
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001446 // Check template type parameter.
1447 if (Arg.getKind() != TemplateArgument::Type) {
1448 // C++ [temp.arg.type]p1:
1449 // A template-argument for a template-parameter which is a
1450 // type shall be a type-id.
1451
1452 // We have a template type parameter but the template argument
1453 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001454 SourceRange SR = AL.getSourceRange();
1455 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001456 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001457
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001458 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001459 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001460
John McCall0ad16662009-10-29 08:12:44 +00001461 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001462 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001463
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001464 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001465 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001466 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001467 return false;
1468}
1469
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001470/// \brief Substitute template arguments into the default template argument for
1471/// the given template type parameter.
1472///
1473/// \param SemaRef the semantic analysis object for which we are performing
1474/// the substitution.
1475///
1476/// \param Template the template that we are synthesizing template arguments
1477/// for.
1478///
1479/// \param TemplateLoc the location of the template name that started the
1480/// template-id we are checking.
1481///
1482/// \param RAngleLoc the location of the right angle bracket ('>') that
1483/// terminates the template-id.
1484///
1485/// \param Param the template template parameter whose default we are
1486/// substituting into.
1487///
1488/// \param Converted the list of template arguments provided for template
1489/// parameters that precede \p Param in the template parameter list.
1490///
1491/// \returns the substituted template argument, or NULL if an error occurred.
1492static DeclaratorInfo *
1493SubstDefaultTemplateArgument(Sema &SemaRef,
1494 TemplateDecl *Template,
1495 SourceLocation TemplateLoc,
1496 SourceLocation RAngleLoc,
1497 TemplateTypeParmDecl *Param,
1498 TemplateArgumentListBuilder &Converted) {
1499 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1500
1501 // If the argument type is dependent, instantiate it now based
1502 // on the previously-computed template arguments.
1503 if (ArgType->getType()->isDependentType()) {
1504 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1505 /*TakeArgs=*/false);
1506
1507 MultiLevelTemplateArgumentList AllTemplateArgs
1508 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1509
1510 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1511 Template, Converted.getFlatArguments(),
1512 Converted.flatSize(),
1513 SourceRange(TemplateLoc, RAngleLoc));
1514
1515 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1516 Param->getDefaultArgumentLoc(),
1517 Param->getDeclName());
1518 }
1519
1520 return ArgType;
1521}
1522
1523/// \brief Substitute template arguments into the default template argument for
1524/// the given non-type template parameter.
1525///
1526/// \param SemaRef the semantic analysis object for which we are performing
1527/// the substitution.
1528///
1529/// \param Template the template that we are synthesizing template arguments
1530/// for.
1531///
1532/// \param TemplateLoc the location of the template name that started the
1533/// template-id we are checking.
1534///
1535/// \param RAngleLoc the location of the right angle bracket ('>') that
1536/// terminates the template-id.
1537///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001538/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001539/// substituting into.
1540///
1541/// \param Converted the list of template arguments provided for template
1542/// parameters that precede \p Param in the template parameter list.
1543///
1544/// \returns the substituted template argument, or NULL if an error occurred.
1545static Sema::OwningExprResult
1546SubstDefaultTemplateArgument(Sema &SemaRef,
1547 TemplateDecl *Template,
1548 SourceLocation TemplateLoc,
1549 SourceLocation RAngleLoc,
1550 NonTypeTemplateParmDecl *Param,
1551 TemplateArgumentListBuilder &Converted) {
1552 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1553 /*TakeArgs=*/false);
1554
1555 MultiLevelTemplateArgumentList AllTemplateArgs
1556 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1557
1558 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1559 Template, Converted.getFlatArguments(),
1560 Converted.flatSize(),
1561 SourceRange(TemplateLoc, RAngleLoc));
1562
1563 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1564}
1565
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001566/// \brief Substitute template arguments into the default template argument for
1567/// the given template template parameter.
1568///
1569/// \param SemaRef the semantic analysis object for which we are performing
1570/// the substitution.
1571///
1572/// \param Template the template that we are synthesizing template arguments
1573/// for.
1574///
1575/// \param TemplateLoc the location of the template name that started the
1576/// template-id we are checking.
1577///
1578/// \param RAngleLoc the location of the right angle bracket ('>') that
1579/// terminates the template-id.
1580///
1581/// \param Param the template template parameter whose default we are
1582/// substituting into.
1583///
1584/// \param Converted the list of template arguments provided for template
1585/// parameters that precede \p Param in the template parameter list.
1586///
1587/// \returns the substituted template argument, or NULL if an error occurred.
1588static TemplateName
1589SubstDefaultTemplateArgument(Sema &SemaRef,
1590 TemplateDecl *Template,
1591 SourceLocation TemplateLoc,
1592 SourceLocation RAngleLoc,
1593 TemplateTemplateParmDecl *Param,
1594 TemplateArgumentListBuilder &Converted) {
1595 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1596 /*TakeArgs=*/false);
1597
1598 MultiLevelTemplateArgumentList AllTemplateArgs
1599 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1600
1601 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1602 Template, Converted.getFlatArguments(),
1603 Converted.flatSize(),
1604 SourceRange(TemplateLoc, RAngleLoc));
1605
1606 return SemaRef.SubstTemplateName(
1607 Param->getDefaultArgument().getArgument().getAsTemplate(),
1608 Param->getDefaultArgument().getTemplateNameLoc(),
1609 AllTemplateArgs);
1610}
1611
Douglas Gregorda0fb532009-11-11 19:31:23 +00001612/// \brief Check that the given template argument corresponds to the given
1613/// template parameter.
1614bool Sema::CheckTemplateArgument(NamedDecl *Param,
1615 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001616 TemplateDecl *Template,
1617 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001618 SourceLocation RAngleLoc,
1619 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001620 // Check template type parameters.
1621 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001622 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001623
Douglas Gregoreebed722009-11-11 19:41:09 +00001624 // Check non-type template parameters.
1625 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001626 // Do substitution on the type of the non-type template parameter
1627 // with the template arguments we've seen thus far.
1628 QualType NTTPType = NTTP->getType();
1629 if (NTTPType->isDependentType()) {
1630 // Do substitution on the type of the non-type template parameter.
1631 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1632 NTTP, Converted.getFlatArguments(),
1633 Converted.flatSize(),
1634 SourceRange(TemplateLoc, RAngleLoc));
1635
1636 TemplateArgumentList TemplateArgs(Context, Converted,
1637 /*TakeArgs=*/false);
1638 NTTPType = SubstType(NTTPType,
1639 MultiLevelTemplateArgumentList(TemplateArgs),
1640 NTTP->getLocation(),
1641 NTTP->getDeclName());
1642 // If that worked, check the non-type template parameter type
1643 // for validity.
1644 if (!NTTPType.isNull())
1645 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1646 NTTP->getLocation());
1647 if (NTTPType.isNull())
1648 return true;
1649 }
1650
1651 switch (Arg.getArgument().getKind()) {
1652 case TemplateArgument::Null:
1653 assert(false && "Should never see a NULL template argument here");
1654 return true;
1655
1656 case TemplateArgument::Expression: {
1657 Expr *E = Arg.getArgument().getAsExpr();
1658 TemplateArgument Result;
1659 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1660 return true;
1661
1662 Converted.Append(Result);
1663 break;
1664 }
1665
1666 case TemplateArgument::Declaration:
1667 case TemplateArgument::Integral:
1668 // We've already checked this template argument, so just copy
1669 // it to the list of converted arguments.
1670 Converted.Append(Arg.getArgument());
1671 break;
1672
1673 case TemplateArgument::Template:
1674 // We were given a template template argument. It may not be ill-formed;
1675 // see below.
1676 if (DependentTemplateName *DTN
1677 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1678 // We have a template argument such as \c T::template X, which we
1679 // parsed as a template template argument. However, since we now
1680 // know that we need a non-type template argument, convert this
1681 // template name into an expression.
1682 Expr *E = new (Context) UnresolvedDeclRefExpr(DTN->getIdentifier(),
1683 Context.DependentTy,
1684 Arg.getTemplateNameLoc(),
1685 Arg.getTemplateQualifierRange(),
1686 DTN->getQualifier(),
1687 /*isAddressOfOperand=*/false);
1688
1689 TemplateArgument Result;
1690 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1691 return true;
1692
1693 Converted.Append(Result);
1694 break;
1695 }
1696
1697 // We have a template argument that actually does refer to a class
1698 // template, template alias, or template template parameter, and
1699 // therefore cannot be a non-type template argument.
1700 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1701 << Arg.getSourceRange();
1702
1703 Diag(Param->getLocation(), diag::note_template_param_here);
1704 return true;
1705
1706 case TemplateArgument::Type: {
1707 // We have a non-type template parameter but the template
1708 // argument is a type.
1709
1710 // C++ [temp.arg]p2:
1711 // In a template-argument, an ambiguity between a type-id and
1712 // an expression is resolved to a type-id, regardless of the
1713 // form of the corresponding template-parameter.
1714 //
1715 // We warn specifically about this case, since it can be rather
1716 // confusing for users.
1717 QualType T = Arg.getArgument().getAsType();
1718 SourceRange SR = Arg.getSourceRange();
1719 if (T->isFunctionType())
1720 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1721 else
1722 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1723 Diag(Param->getLocation(), diag::note_template_param_here);
1724 return true;
1725 }
1726
1727 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00001728 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001729 break;
1730 }
1731
1732 return false;
1733 }
1734
1735
1736 // Check template template parameters.
1737 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1738
1739 // Substitute into the template parameter list of the template
1740 // template parameter, since previously-supplied template arguments
1741 // may appear within the template template parameter.
1742 {
1743 // Set up a template instantiation context.
1744 LocalInstantiationScope Scope(*this);
1745 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1746 TempParm, Converted.getFlatArguments(),
1747 Converted.flatSize(),
1748 SourceRange(TemplateLoc, RAngleLoc));
1749
1750 TemplateArgumentList TemplateArgs(Context, Converted,
1751 /*TakeArgs=*/false);
1752 TempParm = cast_or_null<TemplateTemplateParmDecl>(
1753 SubstDecl(TempParm, CurContext,
1754 MultiLevelTemplateArgumentList(TemplateArgs)));
1755 if (!TempParm)
1756 return true;
1757
1758 // FIXME: TempParam is leaked.
1759 }
1760
1761 switch (Arg.getArgument().getKind()) {
1762 case TemplateArgument::Null:
1763 assert(false && "Should never see a NULL template argument here");
1764 return true;
1765
1766 case TemplateArgument::Template:
1767 if (CheckTemplateArgument(TempParm, Arg))
1768 return true;
1769
1770 Converted.Append(Arg.getArgument());
1771 break;
1772
1773 case TemplateArgument::Expression:
1774 case TemplateArgument::Type:
1775 // We have a template template parameter but the template
1776 // argument does not refer to a template.
1777 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1778 return true;
1779
1780 case TemplateArgument::Declaration:
1781 llvm::llvm_unreachable(
1782 "Declaration argument with template template parameter");
1783 break;
1784 case TemplateArgument::Integral:
1785 llvm::llvm_unreachable(
1786 "Integral argument with template template parameter");
1787 break;
1788
1789 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00001790 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001791 break;
1792 }
1793
1794 return false;
1795}
1796
Douglas Gregord32e0282009-02-09 23:23:08 +00001797/// \brief Check that the given template argument list is well-formed
1798/// for specializing the given template.
1799bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1800 SourceLocation TemplateLoc,
1801 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001802 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001803 unsigned NumTemplateArgs,
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001804 SourceLocation RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001805 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001806 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001807 TemplateParameterList *Params = Template->getTemplateParameters();
1808 unsigned NumParams = Params->size();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001809 unsigned NumArgs = NumTemplateArgs;
Douglas Gregord32e0282009-02-09 23:23:08 +00001810 bool Invalid = false;
1811
Mike Stump11289f42009-09-09 15:08:12 +00001812 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001813 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001814
Anders Carlsson15201f12009-06-13 02:08:00 +00001815 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001816 (NumArgs < Params->getMinRequiredArguments() &&
1817 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001818 // FIXME: point at either the first arg beyond what we can handle,
1819 // or the '>', depending on whether we have too many or too few
1820 // arguments.
1821 SourceRange Range;
1822 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001823 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001824 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1825 << (NumArgs > NumParams)
1826 << (isa<ClassTemplateDecl>(Template)? 0 :
1827 isa<FunctionTemplateDecl>(Template)? 1 :
1828 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1829 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001830 Diag(Template->getLocation(), diag::note_template_decl_here)
1831 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001832 Invalid = true;
1833 }
Mike Stump11289f42009-09-09 15:08:12 +00001834
1835 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001836 // [...] The type and form of each template-argument specified in
1837 // a template-id shall match the type and form specified for the
1838 // corresponding parameter declared by the template in its
1839 // template-parameter-list.
1840 unsigned ArgIdx = 0;
1841 for (TemplateParameterList::iterator Param = Params->begin(),
1842 ParamEnd = Params->end();
1843 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001844 if (ArgIdx > NumArgs && PartialTemplateArgs)
1845 break;
Mike Stump11289f42009-09-09 15:08:12 +00001846
Douglas Gregoreebed722009-11-11 19:41:09 +00001847 // If we have a template parameter pack, check every remaining template
1848 // argument against that template parameter pack.
1849 if ((*Param)->isTemplateParameterPack()) {
1850 Converted.BeginPack();
1851 for (; ArgIdx < NumArgs; ++ArgIdx) {
1852 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
1853 TemplateLoc, RAngleLoc, Converted)) {
1854 Invalid = true;
1855 break;
1856 }
1857 }
1858 Converted.EndPack();
1859 continue;
1860 }
1861
Douglas Gregor84d49a22009-11-11 21:54:23 +00001862 if (ArgIdx < NumArgs) {
1863 // Check the template argument we were given.
1864 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
1865 TemplateLoc, RAngleLoc, Converted))
1866 return true;
1867
1868 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001869 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00001870
Douglas Gregor84d49a22009-11-11 21:54:23 +00001871 // We have a default template argument that we will use.
1872 TemplateArgumentLoc Arg;
1873
1874 // Retrieve the default template argument from the template
1875 // parameter. For each kind of template parameter, we substitute the
1876 // template arguments provided thus far and any "outer" template arguments
1877 // (when the template parameter was part of a nested template) into
1878 // the default argument.
1879 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1880 if (!TTP->hasDefaultArgument()) {
1881 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1882 break;
1883 }
1884
1885 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
1886 Template,
1887 TemplateLoc,
1888 RAngleLoc,
1889 TTP,
1890 Converted);
1891 if (!ArgType)
1892 return true;
1893
1894 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
1895 ArgType);
1896 } else if (NonTypeTemplateParmDecl *NTTP
1897 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1898 if (!NTTP->hasDefaultArgument()) {
1899 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1900 break;
1901 }
1902
1903 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
1904 TemplateLoc,
1905 RAngleLoc,
1906 NTTP,
1907 Converted);
1908 if (E.isInvalid())
1909 return true;
1910
1911 Expr *Ex = E.takeAs<Expr>();
1912 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
1913 } else {
1914 TemplateTemplateParmDecl *TempParm
1915 = cast<TemplateTemplateParmDecl>(*Param);
1916
1917 if (!TempParm->hasDefaultArgument()) {
1918 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
1919 break;
1920 }
1921
1922 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
1923 TemplateLoc,
1924 RAngleLoc,
1925 TempParm,
1926 Converted);
1927 if (Name.isNull())
1928 return true;
1929
1930 Arg = TemplateArgumentLoc(TemplateArgument(Name),
1931 TempParm->getDefaultArgument().getTemplateQualifierRange(),
1932 TempParm->getDefaultArgument().getTemplateNameLoc());
1933 }
1934
1935 // Introduce an instantiation record that describes where we are using
1936 // the default template argument.
1937 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
1938 Converted.getFlatArguments(),
1939 Converted.flatSize(),
1940 SourceRange(TemplateLoc, RAngleLoc));
1941
1942 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00001943 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001944 RAngleLoc, Converted))
1945 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00001946 }
1947
1948 return Invalid;
1949}
1950
1951/// \brief Check a template argument against its corresponding
1952/// template type parameter.
1953///
1954/// This routine implements the semantics of C++ [temp.arg.type]. It
1955/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001956bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001957 DeclaratorInfo *ArgInfo) {
1958 assert(ArgInfo && "invalid DeclaratorInfo");
1959 QualType Arg = ArgInfo->getType();
1960
Douglas Gregord32e0282009-02-09 23:23:08 +00001961 // C++ [temp.arg.type]p2:
1962 // A local type, a type with no linkage, an unnamed type or a type
1963 // compounded from any of these types shall not be used as a
1964 // template-argument for a template type-parameter.
1965 //
1966 // FIXME: Perform the recursive and no-linkage type checks.
1967 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001968 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001969 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001970 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001971 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00001972 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
1973 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1974 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
1975 << QualType(Tag, 0) << SR;
1976 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001977 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00001978 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1979 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00001980 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1981 return true;
1982 }
1983
1984 return false;
1985}
1986
Douglas Gregorccb07762009-02-11 19:52:55 +00001987/// \brief Checks whether the given template argument is the address
1988/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001989bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1990 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001991 bool Invalid = false;
1992
1993 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00001994 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00001995 Arg = Cast->getSubExpr();
1996
Sebastian Redl576fd422009-05-10 18:38:11 +00001997 // C++0x allows nullptr, and there's no further checking to be done for that.
1998 if (Arg->getType()->isNullPtrType())
1999 return false;
2000
Douglas Gregorccb07762009-02-11 19:52:55 +00002001 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002002 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002003 // A template-argument for a non-type, non-template
2004 // template-parameter shall be one of: [...]
2005 //
2006 // -- the address of an object or function with external
2007 // linkage, including function templates and function
2008 // template-ids but excluding non-static class members,
2009 // expressed as & id-expression where the & is optional if
2010 // the name refers to a function or array, or if the
2011 // corresponding template-parameter is a reference; or
2012 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002013
Douglas Gregorccb07762009-02-11 19:52:55 +00002014 // Ignore (and complain about) any excess parentheses.
2015 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2016 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002017 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002018 diag::err_template_arg_extra_parens)
2019 << Arg->getSourceRange();
2020 Invalid = true;
2021 }
2022
2023 Arg = Parens->getSubExpr();
2024 }
2025
2026 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2027 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2028 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2029 } else
2030 DRE = dyn_cast<DeclRefExpr>(Arg);
2031
2032 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002033 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002034 diag::err_template_arg_not_object_or_func_form)
2035 << Arg->getSourceRange();
2036
2037 // Cannot refer to non-static data members
2038 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2039 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2040 << Field << Arg->getSourceRange();
2041
2042 // Cannot refer to non-static member functions
2043 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2044 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002045 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002046 diag::err_template_arg_method)
2047 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002048
Douglas Gregorccb07762009-02-11 19:52:55 +00002049 // Functions must have external linkage.
2050 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2051 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00002052 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002053 diag::err_template_arg_function_not_extern)
2054 << Func << Arg->getSourceRange();
2055 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2056 << true;
2057 return true;
2058 }
2059
2060 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002061 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002062 return Invalid;
2063 }
2064
2065 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2066 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00002067 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002068 diag::err_template_arg_object_not_extern)
2069 << Var << Arg->getSourceRange();
2070 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2071 << true;
2072 return true;
2073 }
2074
2075 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002076 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002077 return Invalid;
2078 }
Mike Stump11289f42009-09-09 15:08:12 +00002079
Douglas Gregorccb07762009-02-11 19:52:55 +00002080 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002081 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002082 diag::err_template_arg_not_object_or_func)
2083 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002084 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002085 diag::note_template_arg_refers_here);
2086 return true;
2087}
2088
2089/// \brief Checks whether the given template argument is a pointer to
2090/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump11289f42009-09-09 15:08:12 +00002091bool
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002092Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002093 bool Invalid = false;
2094
2095 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002096 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002097 Arg = Cast->getSubExpr();
2098
Sebastian Redl576fd422009-05-10 18:38:11 +00002099 // C++0x allows nullptr, and there's no further checking to be done for that.
2100 if (Arg->getType()->isNullPtrType())
2101 return false;
2102
Douglas Gregorccb07762009-02-11 19:52:55 +00002103 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002104 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002105 // A template-argument for a non-type, non-template
2106 // template-parameter shall be one of: [...]
2107 //
2108 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002109 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002110
2111 // Ignore (and complain about) any excess parentheses.
2112 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2113 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002114 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002115 diag::err_template_arg_extra_parens)
2116 << Arg->getSourceRange();
2117 Invalid = true;
2118 }
2119
2120 Arg = Parens->getSubExpr();
2121 }
2122
2123 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002124 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2125 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2126 if (DRE && !DRE->getQualifier())
2127 DRE = 0;
2128 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002129
2130 if (!DRE)
2131 return Diag(Arg->getSourceRange().getBegin(),
2132 diag::err_template_arg_not_pointer_to_member_form)
2133 << Arg->getSourceRange();
2134
2135 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2136 assert((isa<FieldDecl>(DRE->getDecl()) ||
2137 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2138 "Only non-static member pointers can make it here");
2139
2140 // Okay: this is the address of a non-static member, and therefore
2141 // a member pointer constant.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002142 Member = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00002143 return Invalid;
2144 }
2145
2146 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002147 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002148 diag::err_template_arg_not_pointer_to_member_form)
2149 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002150 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002151 diag::note_template_arg_refers_here);
2152 return true;
2153}
2154
Douglas Gregord32e0282009-02-09 23:23:08 +00002155/// \brief Check a template argument against its corresponding
2156/// non-type template parameter.
2157///
Douglas Gregor463421d2009-03-03 04:44:36 +00002158/// This routine implements the semantics of C++ [temp.arg.nontype].
2159/// It returns true if an error occurred, and false otherwise. \p
2160/// InstantiatedParamType is the type of the non-type template
2161/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002162///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002163/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002164bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002165 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002166 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002167 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2168
Douglas Gregor86560402009-02-10 23:36:10 +00002169 // If either the parameter has a dependent type or the argument is
2170 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002171 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002172 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2173 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002174 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002175 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002176 }
Douglas Gregor86560402009-02-10 23:36:10 +00002177
2178 // C++ [temp.arg.nontype]p5:
2179 // The following conversions are performed on each expression used
2180 // as a non-type template-argument. If a non-type
2181 // template-argument cannot be converted to the type of the
2182 // corresponding template-parameter then the program is
2183 // ill-formed.
2184 //
2185 // -- for a non-type template-parameter of integral or
2186 // enumeration type, integral promotions (4.5) and integral
2187 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002188 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002189 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002190 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002191 // C++ [temp.arg.nontype]p1:
2192 // A template-argument for a non-type, non-template
2193 // template-parameter shall be one of:
2194 //
2195 // -- an integral constant-expression of integral or enumeration
2196 // type; or
2197 // -- the name of a non-type template-parameter; or
2198 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002199 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002200 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002201 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002202 diag::err_template_arg_not_integral_or_enumeral)
2203 << ArgType << Arg->getSourceRange();
2204 Diag(Param->getLocation(), diag::note_template_param_here);
2205 return true;
2206 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002207 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002208 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2209 << ArgType << Arg->getSourceRange();
2210 return true;
2211 }
2212
2213 // FIXME: We need some way to more easily get the unqualified form
2214 // of the types without going all the way to the
2215 // canonical type.
2216 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2217 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2218 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2219 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2220
2221 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002222 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002223 // Okay: no conversion necessary
2224 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2225 !ParamType->isEnumeralType()) {
2226 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002227 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002228 } else {
2229 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002230 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002231 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002232 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002233 Diag(Param->getLocation(), diag::note_template_param_here);
2234 return true;
2235 }
2236
Douglas Gregor52aba872009-03-14 00:20:21 +00002237 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002238 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002239 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002240
2241 if (!Arg->isValueDependent()) {
2242 // Check that an unsigned parameter does not receive a negative
2243 // value.
2244 if (IntegerType->isUnsignedIntegerType()
2245 && (Value.isSigned() && Value.isNegative())) {
2246 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2247 << Value.toString(10) << Param->getType()
2248 << Arg->getSourceRange();
2249 Diag(Param->getLocation(), diag::note_template_param_here);
2250 return true;
2251 }
2252
2253 // Check that we don't overflow the template parameter type.
2254 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2255 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002256 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002257 diag::err_template_arg_too_large)
2258 << Value.toString(10) << Param->getType()
2259 << Arg->getSourceRange();
2260 Diag(Param->getLocation(), diag::note_template_param_here);
2261 return true;
2262 }
2263
2264 if (Value.getBitWidth() != AllowedBits)
2265 Value.extOrTrunc(AllowedBits);
2266 Value.setIsSigned(IntegerType->isSignedIntegerType());
2267 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002268
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002269 // Add the value of this argument to the list of converted
2270 // arguments. We use the bitwidth and signedness of the template
2271 // parameter.
2272 if (Arg->isValueDependent()) {
2273 // The argument is value-dependent. Create a new
2274 // TemplateArgument with the converted expression.
2275 Converted = TemplateArgument(Arg);
2276 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002277 }
2278
John McCall0ad16662009-10-29 08:12:44 +00002279 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002280 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002281 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002282 return false;
2283 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002284
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002285 // Handle pointer-to-function, reference-to-function, and
2286 // pointer-to-member-function all in (roughly) the same way.
2287 if (// -- For a non-type template-parameter of type pointer to
2288 // function, only the function-to-pointer conversion (4.3) is
2289 // applied. If the template-argument represents a set of
2290 // overloaded functions (or a pointer to such), the matching
2291 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002292 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002293 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002294 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002295 // -- For a non-type template-parameter of type reference to
2296 // function, no conversions apply. If the template-argument
2297 // represents a set of overloaded functions, the matching
2298 // function is selected from the set (13.4).
2299 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002300 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002301 // -- For a non-type template-parameter of type pointer to
2302 // member function, no conversions apply. If the
2303 // template-argument represents a set of overloaded member
2304 // functions, the matching member function is selected from
2305 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002306 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002307 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002308 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002309 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002310 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002311 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002312 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002313 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2314 ParamType->isMemberPointerType())) {
2315 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002316 if (ParamType->isMemberPointerType())
2317 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2318 else
2319 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002320 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002321 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002322 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002323 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002324 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002325 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2326 return true;
2327
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002328 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002329 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002330 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002331 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002332 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002333 }
2334 }
2335
Mike Stump11289f42009-09-09 15:08:12 +00002336 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002337 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002338 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002339 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002340 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002341 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002342 Diag(Param->getLocation(), diag::note_template_param_here);
2343 return true;
2344 }
Mike Stump11289f42009-09-09 15:08:12 +00002345
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002346 if (ParamType->isMemberPointerType()) {
2347 NamedDecl *Member = 0;
2348 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2349 return true;
2350
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002351 if (Member)
2352 Member = cast<NamedDecl>(Member->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002353 Converted = TemplateArgument(Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002354 return false;
2355 }
Mike Stump11289f42009-09-09 15:08:12 +00002356
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002357 NamedDecl *Entity = 0;
2358 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2359 return true;
2360
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002361 if (Entity)
2362 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002363 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002364 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002365 }
2366
Chris Lattner696197c2009-02-20 21:37:53 +00002367 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002368 // -- for a non-type template-parameter of type pointer to
2369 // object, qualification conversions (4.4) and the
2370 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002371 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002372 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002373 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002374
Sebastian Redl576fd422009-05-10 18:38:11 +00002375 if (ArgType->isNullPtrType()) {
2376 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002377 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002378 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002379 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002380 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002381 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002382
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002383 if (IsQualificationConversion(ArgType, ParamType)) {
2384 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002385 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002386 }
Mike Stump11289f42009-09-09 15:08:12 +00002387
Douglas Gregor1515f762009-02-11 18:22:40 +00002388 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002389 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002390 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002391 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002392 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002393 Diag(Param->getLocation(), diag::note_template_param_here);
2394 return true;
2395 }
Mike Stump11289f42009-09-09 15:08:12 +00002396
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002397 NamedDecl *Entity = 0;
2398 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2399 return true;
2400
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002401 if (Entity)
2402 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002403 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002404 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002405 }
Mike Stump11289f42009-09-09 15:08:12 +00002406
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002407 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002408 // -- For a non-type template-parameter of type reference to
2409 // object, no conversions apply. The type referred to by the
2410 // reference may be more cv-qualified than the (otherwise
2411 // identical) type of the template-argument. The
2412 // template-parameter is bound directly to the
2413 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002414 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002415 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002416
Douglas Gregor1515f762009-02-11 18:22:40 +00002417 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002418 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002419 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002420 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002421 << Arg->getSourceRange();
2422 Diag(Param->getLocation(), diag::note_template_param_here);
2423 return true;
2424 }
2425
Mike Stump11289f42009-09-09 15:08:12 +00002426 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002427 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2428 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002429
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002430 if ((ParamQuals | ArgQuals) != ParamQuals) {
2431 Diag(Arg->getSourceRange().getBegin(),
2432 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002433 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002434 << Arg->getSourceRange();
2435 Diag(Param->getLocation(), diag::note_template_param_here);
2436 return true;
2437 }
Mike Stump11289f42009-09-09 15:08:12 +00002438
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002439 NamedDecl *Entity = 0;
2440 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2441 return true;
2442
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002443 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002444 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002445 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002446 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002447
2448 // -- For a non-type template-parameter of type pointer to data
2449 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002450 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002451 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2452
Douglas Gregor1515f762009-02-11 18:22:40 +00002453 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002454 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002455 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002456 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002457 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002458 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002459 } else {
2460 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002461 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002462 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002463 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002464 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002465 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002466 }
2467
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002468 NamedDecl *Member = 0;
2469 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2470 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002471
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002472 if (Member)
2473 Member = cast<NamedDecl>(Member->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002474 Converted = TemplateArgument(Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002475 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00002476}
2477
2478/// \brief Check a template argument against its corresponding
2479/// template template parameter.
2480///
2481/// This routine implements the semantics of C++ [temp.arg.template].
2482/// It returns true if an error occurred, and false otherwise.
2483bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002484 const TemplateArgumentLoc &Arg) {
2485 TemplateName Name = Arg.getArgument().getAsTemplate();
2486 TemplateDecl *Template = Name.getAsTemplateDecl();
2487 if (!Template) {
2488 // Any dependent template name is fine.
2489 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2490 return false;
2491 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002492
2493 // C++ [temp.arg.template]p1:
2494 // A template-argument for a template template-parameter shall be
2495 // the name of a class template, expressed as id-expression. Only
2496 // primary class templates are considered when matching the
2497 // template template argument with the corresponding parameter;
2498 // partial specializations are not considered even if their
2499 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002500 //
2501 // Note that we also allow template template parameters here, which
2502 // will happen when we are dealing with, e.g., class template
2503 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002504 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002505 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002506 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002507 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002508 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002509 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002510 << Template;
2511 }
2512
2513 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2514 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002515 true,
2516 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002517 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002518}
2519
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002520/// \brief Determine whether the given template parameter lists are
2521/// equivalent.
2522///
Mike Stump11289f42009-09-09 15:08:12 +00002523/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002524/// source code as part of a new template declaration.
2525///
2526/// \param Old The old template parameter list, typically found via
2527/// name lookup of the template declared with this template parameter
2528/// list.
2529///
2530/// \param Complain If true, this routine will produce a diagnostic if
2531/// the template parameter lists are not equivalent.
2532///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002533/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00002534///
2535/// \param TemplateArgLoc If this source location is valid, then we
2536/// are actually checking the template parameter list of a template
2537/// argument (New) against the template parameter list of its
2538/// corresponding template template parameter (Old). We produce
2539/// slightly different diagnostics in this scenario.
2540///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002541/// \returns True if the template parameter lists are equal, false
2542/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002543bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002544Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2545 TemplateParameterList *Old,
2546 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002547 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002548 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002549 if (Old->size() != New->size()) {
2550 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002551 unsigned NextDiag = diag::err_template_param_list_different_arity;
2552 if (TemplateArgLoc.isValid()) {
2553 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2554 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002555 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002556 Diag(New->getTemplateLoc(), NextDiag)
2557 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002558 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002559 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002560 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002561 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002562 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2563 }
2564
2565 return false;
2566 }
2567
2568 for (TemplateParameterList::iterator OldParm = Old->begin(),
2569 OldParmEnd = Old->end(), NewParm = New->begin();
2570 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2571 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002572 if (Complain) {
2573 unsigned NextDiag = diag::err_template_param_different_kind;
2574 if (TemplateArgLoc.isValid()) {
2575 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2576 NextDiag = diag::note_template_param_different_kind;
2577 }
2578 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002579 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00002580 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002581 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00002582 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002583 return false;
2584 }
2585
2586 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2587 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002588 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002589 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002590 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2591 // The types of non-type template parameters must agree.
2592 NonTypeTemplateParmDecl *NewNTTP
2593 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002594
2595 // If we are matching a template template argument to a template
2596 // template parameter and one of the non-type template parameter types
2597 // is dependent, then we must wait until template instantiation time
2598 // to actually compare the arguments.
2599 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2600 (OldNTTP->getType()->isDependentType() ||
2601 NewNTTP->getType()->isDependentType()))
2602 continue;
2603
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002604 if (Context.getCanonicalType(OldNTTP->getType()) !=
2605 Context.getCanonicalType(NewNTTP->getType())) {
2606 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002607 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2608 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002609 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002610 diag::err_template_arg_template_params_mismatch);
2611 NextDiag = diag::note_template_nontype_parm_different_type;
2612 }
2613 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002614 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002615 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00002616 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002617 diag::note_template_nontype_parm_prev_declaration)
2618 << OldNTTP->getType();
2619 }
2620 return false;
2621 }
2622 } else {
2623 // The template parameter lists of template template
2624 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002625 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002626 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002627 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002628 = cast<TemplateTemplateParmDecl>(*OldParm);
2629 TemplateTemplateParmDecl *NewTTP
2630 = cast<TemplateTemplateParmDecl>(*NewParm);
2631 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2632 OldTTP->getTemplateParameters(),
2633 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002634 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00002635 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002636 return false;
2637 }
2638 }
2639
2640 return true;
2641}
2642
2643/// \brief Check whether a template can be declared within this scope.
2644///
2645/// If the template declaration is valid in this scope, returns
2646/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002647bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002648Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002649 // Find the nearest enclosing declaration scope.
2650 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2651 (S->getFlags() & Scope::TemplateParamScope) != 0)
2652 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002653
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002654 // C++ [temp]p2:
2655 // A template-declaration can appear only as a namespace scope or
2656 // class scope declaration.
2657 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002658 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2659 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002660 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002661 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002662
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002663 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002664 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002665
2666 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2667 return false;
2668
Mike Stump11289f42009-09-09 15:08:12 +00002669 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002670 diag::err_template_outside_namespace_or_class_scope)
2671 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002672}
Douglas Gregor67a65642009-02-17 23:15:12 +00002673
Douglas Gregor54888652009-10-07 00:13:32 +00002674/// \brief Determine what kind of template specialization the given declaration
2675/// is.
2676static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2677 if (!D)
2678 return TSK_Undeclared;
2679
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002680 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2681 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002682 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2683 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002684 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2685 return Var->getTemplateSpecializationKind();
2686
Douglas Gregor54888652009-10-07 00:13:32 +00002687 return TSK_Undeclared;
2688}
2689
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002690/// \brief Check whether a specialization is well-formed in the current
2691/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002692///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002693/// This routine determines whether a template specialization can be declared
2694/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002695///
2696/// \param S the semantic analysis object for which this check is being
2697/// performed.
2698///
2699/// \param Specialized the entity being specialized or instantiated, which
2700/// may be a kind of template (class template, function template, etc.) or
2701/// a member of a class template (member function, static data member,
2702/// member class).
2703///
2704/// \param PrevDecl the previous declaration of this entity, if any.
2705///
2706/// \param Loc the location of the explicit specialization or instantiation of
2707/// this entity.
2708///
2709/// \param IsPartialSpecialization whether this is a partial specialization of
2710/// a class template.
2711///
Douglas Gregor54888652009-10-07 00:13:32 +00002712/// \returns true if there was an error that we cannot recover from, false
2713/// otherwise.
2714static bool CheckTemplateSpecializationScope(Sema &S,
2715 NamedDecl *Specialized,
2716 NamedDecl *PrevDecl,
2717 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002718 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002719 // Keep these "kind" numbers in sync with the %select statements in the
2720 // various diagnostics emitted by this routine.
2721 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002722 bool isTemplateSpecialization = false;
2723 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002724 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002725 isTemplateSpecialization = true;
2726 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002727 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002728 isTemplateSpecialization = true;
2729 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002730 EntityKind = 3;
2731 else if (isa<VarDecl>(Specialized))
2732 EntityKind = 4;
2733 else if (isa<RecordDecl>(Specialized))
2734 EntityKind = 5;
2735 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002736 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2737 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00002738 return true;
2739 }
2740
Douglas Gregorf47b9112009-02-25 22:02:03 +00002741 // C++ [temp.expl.spec]p2:
2742 // An explicit specialization shall be declared in the namespace
2743 // of which the template is a member, or, for member templates, in
2744 // the namespace of which the enclosing class or enclosing class
2745 // template is a member. An explicit specialization of a member
2746 // function, member class or static data member of a class
2747 // template shall be declared in the namespace of which the class
2748 // template is a member. Such a declaration may also be a
2749 // definition. If the declaration is not a definition, the
2750 // specialization may be defined later in the name- space in which
2751 // the explicit specialization was declared, or in a namespace
2752 // that encloses the one in which the explicit specialization was
2753 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002754 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2755 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002756 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002757 return true;
2758 }
Douglas Gregore4b05162009-10-07 17:21:34 +00002759
Douglas Gregor40fb7442009-10-07 17:30:37 +00002760 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2761 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002762 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00002763 return true;
2764 }
2765
Douglas Gregore4b05162009-10-07 17:21:34 +00002766 // C++ [temp.class.spec]p6:
2767 // A class template partial specialization may be declared or redeclared
2768 // in any namespace scope in which its definition may be defined (14.5.1
2769 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002770 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002771 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002772 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002773 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002774 if ((!PrevDecl ||
2775 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2776 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2777 // There is no prior declaration of this entity, so this
2778 // specialization must be in the same context as the template
2779 // itself.
2780 if (!DC->Equals(SpecializedContext)) {
2781 if (isa<TranslationUnitDecl>(SpecializedContext))
2782 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2783 << EntityKind << Specialized;
2784 else if (isa<NamespaceDecl>(SpecializedContext))
2785 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2786 << EntityKind << Specialized
2787 << cast<NamedDecl>(SpecializedContext);
2788
2789 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2790 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002791 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002792 }
Douglas Gregor54888652009-10-07 00:13:32 +00002793
2794 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002795 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00002796 // Note that HandleDeclarator() performs this check for explicit
2797 // specializations of function templates, static data members, and member
2798 // functions, so we skip the check here for those kinds of entities.
2799 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00002800 // Should we refactor that check, so that it occurs later?
2801 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002802 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2803 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00002804 if (isa<TranslationUnitDecl>(SpecializedContext))
2805 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2806 << EntityKind << Specialized;
2807 else if (isa<NamespaceDecl>(SpecializedContext))
2808 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2809 << EntityKind << Specialized
2810 << cast<NamedDecl>(SpecializedContext);
2811
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002812 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002813 }
Douglas Gregor54888652009-10-07 00:13:32 +00002814
2815 // FIXME: check for specialization-after-instantiation errors and such.
2816
Douglas Gregorf47b9112009-02-25 22:02:03 +00002817 return false;
2818}
Douglas Gregor54888652009-10-07 00:13:32 +00002819
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002820/// \brief Check the non-type template arguments of a class template
2821/// partial specialization according to C++ [temp.class.spec]p9.
2822///
Douglas Gregor09a30232009-06-12 22:08:06 +00002823/// \param TemplateParams the template parameters of the primary class
2824/// template.
2825///
2826/// \param TemplateArg the template arguments of the class template
2827/// partial specialization.
2828///
2829/// \param MirrorsPrimaryTemplate will be set true if the class
2830/// template partial specialization arguments are identical to the
2831/// implicit template arguments of the primary template. This is not
2832/// necessarily an error (C++0x), and it is left to the caller to diagnose
2833/// this condition when it is an error.
2834///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002835/// \returns true if there was an error, false otherwise.
2836bool Sema::CheckClassTemplatePartialSpecializationArgs(
2837 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002838 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002839 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002840 // FIXME: the interface to this function will have to change to
2841 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002842 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002843
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002844 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002845
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002846 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002847 // Determine whether the template argument list of the partial
2848 // specialization is identical to the implicit argument list of
2849 // the primary template. The caller may need to diagnostic this as
2850 // an error per C++ [temp.class.spec]p9b3.
2851 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002852 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002853 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2854 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002855 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002856 MirrorsPrimaryTemplate = false;
2857 } else if (TemplateTemplateParmDecl *TTP
2858 = dyn_cast<TemplateTemplateParmDecl>(
2859 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002860 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00002861 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002862 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002863 if (!ArgDecl ||
2864 ArgDecl->getIndex() != TTP->getIndex() ||
2865 ArgDecl->getDepth() != TTP->getDepth())
2866 MirrorsPrimaryTemplate = false;
2867 }
2868 }
2869
Mike Stump11289f42009-09-09 15:08:12 +00002870 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002871 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002872 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002873 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002874 }
2875
Anders Carlsson40c1d492009-06-13 18:20:51 +00002876 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002877 if (!ArgExpr) {
2878 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002879 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002880 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002881
2882 // C++ [temp.class.spec]p8:
2883 // A non-type argument is non-specialized if it is the name of a
2884 // non-type parameter. All other non-type arguments are
2885 // specialized.
2886 //
2887 // Below, we check the two conditions that only apply to
2888 // specialized non-type arguments, so skip any non-specialized
2889 // arguments.
2890 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002891 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002892 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002893 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002894 (Param->getIndex() != NTTP->getIndex() ||
2895 Param->getDepth() != NTTP->getDepth()))
2896 MirrorsPrimaryTemplate = false;
2897
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002898 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002899 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002900
2901 // C++ [temp.class.spec]p9:
2902 // Within the argument list of a class template partial
2903 // specialization, the following restrictions apply:
2904 // -- A partially specialized non-type argument expression
2905 // shall not involve a template parameter of the partial
2906 // specialization except when the argument expression is a
2907 // simple identifier.
2908 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002909 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002910 diag::err_dependent_non_type_arg_in_partial_spec)
2911 << ArgExpr->getSourceRange();
2912 return true;
2913 }
2914
2915 // -- The type of a template parameter corresponding to a
2916 // specialized non-type argument shall not be dependent on a
2917 // parameter of the specialization.
2918 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002919 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002920 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2921 << Param->getType()
2922 << ArgExpr->getSourceRange();
2923 Diag(Param->getLocation(), diag::note_template_param_here);
2924 return true;
2925 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002926
2927 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002928 }
2929
2930 return false;
2931}
2932
Douglas Gregorc08f4892009-03-25 00:13:59 +00002933Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002934Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2935 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002936 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002937 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002938 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002939 SourceLocation TemplateNameLoc,
2940 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002941 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002942 SourceLocation RAngleLoc,
2943 AttributeList *Attr,
2944 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00002945 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00002946
Douglas Gregor67a65642009-02-17 23:15:12 +00002947 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002948 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002949 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00002950 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
2951
2952 if (!ClassTemplate) {
2953 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
2954 << (Name.getAsTemplateDecl() &&
2955 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
2956 return true;
2957 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002958
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002959 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00002960 bool isPartialSpecialization = false;
2961
Douglas Gregorf47b9112009-02-25 22:02:03 +00002962 // Check the validity of the template headers that introduce this
2963 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00002964 // FIXME: We probably shouldn't complain about these headers for
2965 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002966 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002967 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2968 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002969 TemplateParameterLists.size(),
2970 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002971 if (TemplateParams && TemplateParams->size() > 0) {
2972 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002973
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002974 // C++ [temp.class.spec]p10:
2975 // The template parameter list of a specialization shall not
2976 // contain default template argument values.
2977 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2978 Decl *Param = TemplateParams->getParam(I);
2979 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2980 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002981 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002982 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00002983 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002984 }
2985 } else if (NonTypeTemplateParmDecl *NTTP
2986 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2987 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002988 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002989 diag::err_default_arg_in_partial_spec)
2990 << DefArg->getSourceRange();
2991 NTTP->setDefaultArgument(0);
2992 DefArg->Destroy(Context);
2993 }
2994 } else {
2995 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002996 if (TTP->hasDefaultArgument()) {
2997 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002998 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002999 << TTP->getDefaultArgument().getSourceRange();
3000 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003001 }
3002 }
3003 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003004 } else if (TemplateParams) {
3005 if (TUK == TUK_Friend)
3006 Diag(KWLoc, diag::err_template_spec_friend)
3007 << CodeModificationHint::CreateRemoval(
3008 SourceRange(TemplateParams->getTemplateLoc(),
3009 TemplateParams->getRAngleLoc()))
3010 << SourceRange(LAngleLoc, RAngleLoc);
3011 else
3012 isExplicitSpecialization = true;
3013 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003014 Diag(KWLoc, diag::err_template_spec_needs_header)
3015 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003016 isExplicitSpecialization = true;
3017 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003018
Douglas Gregor67a65642009-02-17 23:15:12 +00003019 // Check that the specialization uses the same tag kind as the
3020 // original template.
3021 TagDecl::TagKind Kind;
3022 switch (TagSpec) {
3023 default: assert(0 && "Unknown tag type!");
3024 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3025 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3026 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3027 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003028 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003029 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003030 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003031 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003032 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003033 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003034 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003035 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003036 diag::note_previous_use);
3037 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3038 }
3039
Douglas Gregorc40290e2009-03-09 23:48:35 +00003040 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00003041 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003042 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003043
Douglas Gregor67a65642009-02-17 23:15:12 +00003044 // Check that the template argument list is well-formed for this
3045 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003046 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3047 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003048 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003049 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003050 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003051 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003052
Mike Stump11289f42009-09-09 15:08:12 +00003053 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003054 ClassTemplate->getTemplateParameters()->size()) &&
3055 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003056
Douglas Gregor2373c592009-05-31 09:31:02 +00003057 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003058 // corresponds to these arguments.
3059 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003060 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003061 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003062 if (CheckClassTemplatePartialSpecializationArgs(
3063 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003064 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003065 return true;
3066
Douglas Gregor09a30232009-06-12 22:08:06 +00003067 if (MirrorsPrimaryTemplate) {
3068 // C++ [temp.class.spec]p9b3:
3069 //
Mike Stump11289f42009-09-09 15:08:12 +00003070 // -- The argument list of the specialization shall not be identical
3071 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003072 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003073 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003074 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003075 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003076 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003077 ClassTemplate->getIdentifier(),
3078 TemplateNameLoc,
3079 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003080 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003081 AS_none);
3082 }
3083
Douglas Gregor2208a292009-09-26 20:57:03 +00003084 // FIXME: Diagnose friend partial specializations
3085
Douglas Gregor2373c592009-05-31 09:31:02 +00003086 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00003087 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003088 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003089 Converted.flatSize(),
3090 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003091 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003092 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003093 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003094 Converted.flatSize(),
3095 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003096 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003097 ClassTemplateSpecializationDecl *PrevDecl = 0;
3098
3099 if (isPartialSpecialization)
3100 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003101 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003102 InsertPos);
3103 else
3104 PrevDecl
3105 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003106
3107 ClassTemplateSpecializationDecl *Specialization = 0;
3108
Douglas Gregorf47b9112009-02-25 22:02:03 +00003109 // Check whether we can declare a class template specialization in
3110 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003111 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003112 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003113 TemplateNameLoc,
3114 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003115 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003116
Douglas Gregor15301382009-07-30 17:40:51 +00003117 // The canonical type
3118 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003119 if (PrevDecl &&
3120 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3121 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003122 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003123 // arguments was referenced but not declared, or we're only
3124 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003125 // declaration node as our own, updating its source location to
3126 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003127 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003128 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003129 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003130 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003131 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003132 // Build the canonical type that describes the converted template
3133 // arguments of the class template partial specialization.
3134 CanonType = Context.getTemplateSpecializationType(
3135 TemplateName(ClassTemplate),
3136 Converted.getFlatArguments(),
3137 Converted.flatSize());
3138
Douglas Gregor2373c592009-05-31 09:31:02 +00003139 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003140 ClassTemplatePartialSpecializationDecl *PrevPartial
3141 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003142 ClassTemplatePartialSpecializationDecl *Partial
3143 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003144 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003145 TemplateNameLoc,
3146 TemplateParams,
3147 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003148 Converted,
John McCall0ad16662009-10-29 08:12:44 +00003149 TemplateArgs.data(),
3150 TemplateArgs.size(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003151 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003152
3153 if (PrevPartial) {
3154 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3155 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3156 } else {
3157 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3158 }
3159 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003160
Douglas Gregor21610382009-10-29 00:04:11 +00003161 // If we are providing an explicit specialization of a member class
3162 // template specialization, make a note of that.
3163 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3164 PrevPartial->setMemberSpecialization();
3165
Douglas Gregor91772d12009-06-13 00:26:55 +00003166 // Check that all of the template parameters of the class template
3167 // partial specialization are deducible from the template
3168 // arguments. If not, this class template partial specialization
3169 // will never be used.
3170 llvm::SmallVector<bool, 8> DeducibleParams;
3171 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003172 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003173 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003174 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003175 unsigned NumNonDeducible = 0;
3176 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3177 if (!DeducibleParams[I])
3178 ++NumNonDeducible;
3179
3180 if (NumNonDeducible) {
3181 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3182 << (NumNonDeducible > 1)
3183 << SourceRange(TemplateNameLoc, RAngleLoc);
3184 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3185 if (!DeducibleParams[I]) {
3186 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3187 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003188 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003189 diag::note_partial_spec_unused_parameter)
3190 << Param->getDeclName();
3191 else
Mike Stump11289f42009-09-09 15:08:12 +00003192 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003193 diag::note_partial_spec_unused_parameter)
3194 << std::string("<anonymous>");
3195 }
3196 }
3197 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003198 } else {
3199 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003200 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003201 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003202 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003203 ClassTemplate->getDeclContext(),
3204 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003205 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003206 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003207 PrevDecl);
3208
3209 if (PrevDecl) {
3210 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3211 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3212 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003213 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003214 InsertPos);
3215 }
Douglas Gregor15301382009-07-30 17:40:51 +00003216
3217 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003218 }
3219
Douglas Gregor06db9f52009-10-12 20:18:28 +00003220 // C++ [temp.expl.spec]p6:
3221 // If a template, a member template or the member of a class template is
3222 // explicitly specialized then that specialization shall be declared
3223 // before the first use of that specialization that would cause an implicit
3224 // instantiation to take place, in every translation unit in which such a
3225 // use occurs; no diagnostic is required.
3226 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3227 SourceRange Range(TemplateNameLoc, RAngleLoc);
3228 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3229 << Context.getTypeDeclType(Specialization) << Range;
3230
3231 Diag(PrevDecl->getPointOfInstantiation(),
3232 diag::note_instantiation_required_here)
3233 << (PrevDecl->getTemplateSpecializationKind()
3234 != TSK_ImplicitInstantiation);
3235 return true;
3236 }
3237
Douglas Gregor2208a292009-09-26 20:57:03 +00003238 // If this is not a friend, note that this is an explicit specialization.
3239 if (TUK != TUK_Friend)
3240 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003241
3242 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003243 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003244 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003245 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003246 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003247 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003248 Diag(Def->getLocation(), diag::note_previous_definition);
3249 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003250 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003251 }
3252 }
3253
Douglas Gregord56a91e2009-02-26 22:19:44 +00003254 // Build the fully-sugared type for this class template
3255 // specialization as the user wrote in the specialization
3256 // itself. This means that we'll pretty-print the type retrieved
3257 // from the specialization's declaration the way that the user
3258 // actually wrote the specialization, rather than formatting the
3259 // name based on the "canonical" representation used to store the
3260 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003261 QualType WrittenTy
3262 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003263 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00003264 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00003265 CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003266 if (TUK != TUK_Friend)
3267 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003268 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003269
Douglas Gregor1e249f82009-02-25 22:18:32 +00003270 // C++ [temp.expl.spec]p9:
3271 // A template explicit specialization is in the scope of the
3272 // namespace in which the template was defined.
3273 //
3274 // We actually implement this paragraph where we set the semantic
3275 // context (in the creation of the ClassTemplateSpecializationDecl),
3276 // but we also maintain the lexical context where the actual
3277 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003278 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003279
Douglas Gregor67a65642009-02-17 23:15:12 +00003280 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003281 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003282 Specialization->startDefinition();
3283
Douglas Gregor2208a292009-09-26 20:57:03 +00003284 if (TUK == TUK_Friend) {
3285 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3286 TemplateNameLoc,
3287 WrittenTy.getTypePtr(),
3288 /*FIXME:*/KWLoc);
3289 Friend->setAccess(AS_public);
3290 CurContext->addDecl(Friend);
3291 } else {
3292 // Add the specialization into its lexical context, so that it can
3293 // be seen when iterating through the list of declarations in that
3294 // context. However, specializations are not found by name lookup.
3295 CurContext->addDecl(Specialization);
3296 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003297 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003298}
Douglas Gregor333489b2009-03-27 23:10:48 +00003299
Mike Stump11289f42009-09-09 15:08:12 +00003300Sema::DeclPtrTy
3301Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003302 MultiTemplateParamsArg TemplateParameterLists,
3303 Declarator &D) {
3304 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3305}
3306
Mike Stump11289f42009-09-09 15:08:12 +00003307Sema::DeclPtrTy
3308Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003309 MultiTemplateParamsArg TemplateParameterLists,
3310 Declarator &D) {
3311 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3312 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3313 "Not a function declarator!");
3314 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003315
Douglas Gregor17a7c122009-06-24 00:54:41 +00003316 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003317 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003318 }
Mike Stump11289f42009-09-09 15:08:12 +00003319
Douglas Gregor17a7c122009-06-24 00:54:41 +00003320 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003321
3322 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003323 move(TemplateParameterLists),
3324 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003325 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003326 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003327 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003328 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003329 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3330 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003331 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003332}
3333
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003334/// \brief Diagnose cases where we have an explicit template specialization
3335/// before/after an explicit template instantiation, producing diagnostics
3336/// for those cases where they are required and determining whether the
3337/// new specialization/instantiation will have any effect.
3338///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003339/// \param NewLoc the location of the new explicit specialization or
3340/// instantiation.
3341///
3342/// \param NewTSK the kind of the new explicit specialization or instantiation.
3343///
3344/// \param PrevDecl the previous declaration of the entity.
3345///
3346/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3347///
3348/// \param PrevPointOfInstantiation if valid, indicates where the previus
3349/// declaration was instantiated (either implicitly or explicitly).
3350///
3351/// \param SuppressNew will be set to true to indicate that the new
3352/// specialization or instantiation has no effect and should be ignored.
3353///
3354/// \returns true if there was an error that should prevent the introduction of
3355/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003356bool
3357Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3358 TemplateSpecializationKind NewTSK,
3359 NamedDecl *PrevDecl,
3360 TemplateSpecializationKind PrevTSK,
3361 SourceLocation PrevPointOfInstantiation,
3362 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003363 SuppressNew = false;
3364
3365 switch (NewTSK) {
3366 case TSK_Undeclared:
3367 case TSK_ImplicitInstantiation:
3368 assert(false && "Don't check implicit instantiations here");
3369 return false;
3370
3371 case TSK_ExplicitSpecialization:
3372 switch (PrevTSK) {
3373 case TSK_Undeclared:
3374 case TSK_ExplicitSpecialization:
3375 // Okay, we're just specializing something that is either already
3376 // explicitly specialized or has merely been mentioned without any
3377 // instantiation.
3378 return false;
3379
3380 case TSK_ImplicitInstantiation:
3381 if (PrevPointOfInstantiation.isInvalid()) {
3382 // The declaration itself has not actually been instantiated, so it is
3383 // still okay to specialize it.
3384 return false;
3385 }
3386 // Fall through
3387
3388 case TSK_ExplicitInstantiationDeclaration:
3389 case TSK_ExplicitInstantiationDefinition:
3390 assert((PrevTSK == TSK_ImplicitInstantiation ||
3391 PrevPointOfInstantiation.isValid()) &&
3392 "Explicit instantiation without point of instantiation?");
3393
3394 // C++ [temp.expl.spec]p6:
3395 // If a template, a member template or the member of a class template
3396 // is explicitly specialized then that specialization shall be declared
3397 // before the first use of that specialization that would cause an
3398 // implicit instantiation to take place, in every translation unit in
3399 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003400 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003401 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003402 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003403 << (PrevTSK != TSK_ImplicitInstantiation);
3404
3405 return true;
3406 }
3407 break;
3408
3409 case TSK_ExplicitInstantiationDeclaration:
3410 switch (PrevTSK) {
3411 case TSK_ExplicitInstantiationDeclaration:
3412 // This explicit instantiation declaration is redundant (that's okay).
3413 SuppressNew = true;
3414 return false;
3415
3416 case TSK_Undeclared:
3417 case TSK_ImplicitInstantiation:
3418 // We're explicitly instantiating something that may have already been
3419 // implicitly instantiated; that's fine.
3420 return false;
3421
3422 case TSK_ExplicitSpecialization:
3423 // C++0x [temp.explicit]p4:
3424 // For a given set of template parameters, if an explicit instantiation
3425 // of a template appears after a declaration of an explicit
3426 // specialization for that template, the explicit instantiation has no
3427 // effect.
3428 return false;
3429
3430 case TSK_ExplicitInstantiationDefinition:
3431 // C++0x [temp.explicit]p10:
3432 // If an entity is the subject of both an explicit instantiation
3433 // declaration and an explicit instantiation definition in the same
3434 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003435 Diag(NewLoc,
3436 diag::err_explicit_instantiation_declaration_after_definition);
3437 Diag(PrevPointOfInstantiation,
3438 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003439 assert(PrevPointOfInstantiation.isValid() &&
3440 "Explicit instantiation without point of instantiation?");
3441 SuppressNew = true;
3442 return false;
3443 }
3444 break;
3445
3446 case TSK_ExplicitInstantiationDefinition:
3447 switch (PrevTSK) {
3448 case TSK_Undeclared:
3449 case TSK_ImplicitInstantiation:
3450 // We're explicitly instantiating something that may have already been
3451 // implicitly instantiated; that's fine.
3452 return false;
3453
3454 case TSK_ExplicitSpecialization:
3455 // C++ DR 259, C++0x [temp.explicit]p4:
3456 // For a given set of template parameters, if an explicit
3457 // instantiation of a template appears after a declaration of
3458 // an explicit specialization for that template, the explicit
3459 // instantiation has no effect.
3460 //
3461 // In C++98/03 mode, we only give an extension warning here, because it
3462 // is not not harmful to try to explicitly instantiate something that
3463 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003464 if (!getLangOptions().CPlusPlus0x) {
3465 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003466 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003467 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003468 diag::note_previous_template_specialization);
3469 }
3470 SuppressNew = true;
3471 return false;
3472
3473 case TSK_ExplicitInstantiationDeclaration:
3474 // We're explicity instantiating a definition for something for which we
3475 // were previously asked to suppress instantiations. That's fine.
3476 return false;
3477
3478 case TSK_ExplicitInstantiationDefinition:
3479 // C++0x [temp.spec]p5:
3480 // For a given template and a given set of template-arguments,
3481 // - an explicit instantiation definition shall appear at most once
3482 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003483 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003484 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003485 Diag(PrevPointOfInstantiation,
3486 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003487 SuppressNew = true;
3488 return false;
3489 }
3490 break;
3491 }
3492
3493 assert(false && "Missing specialization/instantiation case?");
3494
3495 return false;
3496}
3497
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003498/// \brief Perform semantic analysis for the given function template
3499/// specialization.
3500///
3501/// This routine performs all of the semantic analysis required for an
3502/// explicit function template specialization. On successful completion,
3503/// the function declaration \p FD will become a function template
3504/// specialization.
3505///
3506/// \param FD the function declaration, which will be updated to become a
3507/// function template specialization.
3508///
3509/// \param HasExplicitTemplateArgs whether any template arguments were
3510/// explicitly provided.
3511///
3512/// \param LAngleLoc the location of the left angle bracket ('<'), if
3513/// template arguments were explicitly provided.
3514///
3515/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3516/// if any.
3517///
3518/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3519/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3520/// true as in, e.g., \c void sort<>(char*, char*);
3521///
3522/// \param RAngleLoc the location of the right angle bracket ('>'), if
3523/// template arguments were explicitly provided.
3524///
3525/// \param PrevDecl the set of declarations that
3526bool
3527Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3528 bool HasExplicitTemplateArgs,
3529 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00003530 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003531 unsigned NumExplicitTemplateArgs,
3532 SourceLocation RAngleLoc,
3533 NamedDecl *&PrevDecl) {
3534 // The set of function template specializations that could match this
3535 // explicit function template specialization.
3536 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3537 CandidateSet Candidates;
3538
3539 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3540 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3541 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3542 // Only consider templates found within the same semantic lookup scope as
3543 // FD.
3544 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3545 continue;
3546
3547 // C++ [temp.expl.spec]p11:
3548 // A trailing template-argument can be left unspecified in the
3549 // template-id naming an explicit function template specialization
3550 // provided it can be deduced from the function argument type.
3551 // Perform template argument deduction to determine whether we may be
3552 // specializing this template.
3553 // FIXME: It is somewhat wasteful to build
3554 TemplateDeductionInfo Info(Context);
3555 FunctionDecl *Specialization = 0;
3556 if (TemplateDeductionResult TDK
3557 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3558 ExplicitTemplateArgs,
3559 NumExplicitTemplateArgs,
3560 FD->getType(),
3561 Specialization,
3562 Info)) {
3563 // FIXME: Template argument deduction failed; record why it failed, so
3564 // that we can provide nifty diagnostics.
3565 (void)TDK;
3566 continue;
3567 }
3568
3569 // Record this candidate.
3570 Candidates.push_back(Specialization);
3571 }
3572 }
3573
Douglas Gregor5de279c2009-09-26 03:41:46 +00003574 // Find the most specialized function template.
3575 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3576 Candidates.size(),
3577 TPOC_Other,
3578 FD->getLocation(),
3579 PartialDiagnostic(diag::err_function_template_spec_no_match)
3580 << FD->getDeclName(),
3581 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3582 << FD->getDeclName() << HasExplicitTemplateArgs,
3583 PartialDiagnostic(diag::note_function_template_spec_matched));
3584 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003585 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003586
3587 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003588 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003589
Douglas Gregor54888652009-10-07 00:13:32 +00003590 // Check the scope of this explicit specialization.
3591 if (CheckTemplateSpecializationScope(*this,
3592 Specialization->getPrimaryTemplate(),
3593 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003594 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003595 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003596
3597 // C++ [temp.expl.spec]p6:
3598 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003599 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003600 // before the first use of that specialization that would cause an implicit
3601 // instantiation to take place, in every translation unit in which such a
3602 // use occurs; no diagnostic is required.
3603 FunctionTemplateSpecializationInfo *SpecInfo
3604 = Specialization->getTemplateSpecializationInfo();
3605 assert(SpecInfo && "Function template specialization info missing?");
3606 if (SpecInfo->getPointOfInstantiation().isValid()) {
3607 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3608 << FD;
3609 Diag(SpecInfo->getPointOfInstantiation(),
3610 diag::note_instantiation_required_here)
3611 << (Specialization->getTemplateSpecializationKind()
3612 != TSK_ImplicitInstantiation);
3613 return true;
3614 }
Douglas Gregor54888652009-10-07 00:13:32 +00003615
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003616 // Mark the prior declaration as an explicit specialization, so that later
3617 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003618 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003619
3620 // Turn the given function declaration into a function template
3621 // specialization, with the template arguments from the previous
3622 // specialization.
3623 FD->setFunctionTemplateSpecialization(Context,
3624 Specialization->getPrimaryTemplate(),
3625 new (Context) TemplateArgumentList(
3626 *Specialization->getTemplateSpecializationArgs()),
3627 /*InsertPos=*/0,
3628 TSK_ExplicitSpecialization);
3629
3630 // The "previous declaration" for this function template specialization is
3631 // the prior function template specialization.
3632 PrevDecl = Specialization;
3633 return false;
3634}
3635
Douglas Gregor86d142a2009-10-08 07:24:58 +00003636/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003637/// specialization.
3638///
3639/// This routine performs all of the semantic analysis required for an
3640/// explicit member function specialization. On successful completion,
3641/// the function declaration \p FD will become a member function
3642/// specialization.
3643///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003644/// \param Member the member declaration, which will be updated to become a
3645/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003646///
3647/// \param PrevDecl the set of declarations, one of which may be specialized
3648/// by this function specialization.
3649bool
Douglas Gregor86d142a2009-10-08 07:24:58 +00003650Sema::CheckMemberSpecialization(NamedDecl *Member, NamedDecl *&PrevDecl) {
3651 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3652
3653 // Try to find the member we are instantiating.
3654 NamedDecl *Instantiation = 0;
3655 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003656 MemberSpecializationInfo *MSInfo = 0;
3657
Douglas Gregor86d142a2009-10-08 07:24:58 +00003658 if (!PrevDecl) {
3659 // Nowhere to look anyway.
3660 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3661 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3662 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl)) {
3663 if (Context.hasSameType(Function->getType(), Method->getType())) {
3664 Instantiation = Method;
3665 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003666 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003667 break;
3668 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003669 }
3670 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003671 } else if (isa<VarDecl>(Member)) {
3672 if (VarDecl *PrevVar = dyn_cast<VarDecl>(PrevDecl))
3673 if (PrevVar->isStaticDataMember()) {
3674 Instantiation = PrevDecl;
3675 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)) {
3679 if (CXXRecordDecl *PrevRecord = dyn_cast<CXXRecordDecl>(PrevDecl)) {
3680 Instantiation = PrevDecl;
3681 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003682 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003683 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003684 }
3685
3686 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003687 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003688 // specializations are always out-of-line, the caller will complain about
3689 // this mismatch later.
3690 return false;
3691 }
3692
Douglas Gregor86d142a2009-10-08 07:24:58 +00003693 // Make sure that this is a specialization of a member.
3694 if (!InstantiatedFrom) {
3695 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3696 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003697 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3698 return true;
3699 }
3700
Douglas Gregor06db9f52009-10-12 20:18:28 +00003701 // C++ [temp.expl.spec]p6:
3702 // If a template, a member template or the member of a class template is
3703 // explicitly specialized then that spe- cialization shall be declared
3704 // before the first use of that specialization that would cause an implicit
3705 // instantiation to take place, in every translation unit in which such a
3706 // use occurs; no diagnostic is required.
3707 assert(MSInfo && "Member specialization info missing?");
3708 if (MSInfo->getPointOfInstantiation().isValid()) {
3709 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3710 << Member;
3711 Diag(MSInfo->getPointOfInstantiation(),
3712 diag::note_instantiation_required_here)
3713 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3714 return true;
3715 }
3716
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003717 // Check the scope of this explicit specialization.
3718 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003719 InstantiatedFrom,
3720 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003721 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003722 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003723
Douglas Gregor86d142a2009-10-08 07:24:58 +00003724 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003725 // the original declaration to note that it is an explicit specialization
3726 // (if it was previously an implicit instantiation). This latter step
3727 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003728 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003729 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3730 if (InstantiationFunction->getTemplateSpecializationKind() ==
3731 TSK_ImplicitInstantiation) {
3732 InstantiationFunction->setTemplateSpecializationKind(
3733 TSK_ExplicitSpecialization);
3734 InstantiationFunction->setLocation(Member->getLocation());
3735 }
3736
Douglas Gregor86d142a2009-10-08 07:24:58 +00003737 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3738 cast<CXXMethodDecl>(InstantiatedFrom),
3739 TSK_ExplicitSpecialization);
3740 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003741 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3742 if (InstantiationVar->getTemplateSpecializationKind() ==
3743 TSK_ImplicitInstantiation) {
3744 InstantiationVar->setTemplateSpecializationKind(
3745 TSK_ExplicitSpecialization);
3746 InstantiationVar->setLocation(Member->getLocation());
3747 }
3748
Douglas Gregor86d142a2009-10-08 07:24:58 +00003749 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3750 cast<VarDecl>(InstantiatedFrom),
3751 TSK_ExplicitSpecialization);
3752 } else {
3753 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003754 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3755 if (InstantiationClass->getTemplateSpecializationKind() ==
3756 TSK_ImplicitInstantiation) {
3757 InstantiationClass->setTemplateSpecializationKind(
3758 TSK_ExplicitSpecialization);
3759 InstantiationClass->setLocation(Member->getLocation());
3760 }
3761
Douglas Gregor86d142a2009-10-08 07:24:58 +00003762 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003763 cast<CXXRecordDecl>(InstantiatedFrom),
3764 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003765 }
3766
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003767 // Save the caller the trouble of having to figure out which declaration
3768 // this specialization matches.
3769 PrevDecl = Instantiation;
3770 return false;
3771}
3772
Douglas Gregore47f5a72009-10-14 23:41:34 +00003773/// \brief Check the scope of an explicit instantiation.
3774static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3775 SourceLocation InstLoc,
3776 bool WasQualifiedName) {
3777 DeclContext *ExpectedContext
3778 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3779 DeclContext *CurContext = S.CurContext->getLookupContext();
3780
3781 // C++0x [temp.explicit]p2:
3782 // An explicit instantiation shall appear in an enclosing namespace of its
3783 // template.
3784 //
3785 // This is DR275, which we do not retroactively apply to C++98/03.
3786 if (S.getLangOptions().CPlusPlus0x &&
3787 !CurContext->Encloses(ExpectedContext)) {
3788 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3789 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3790 << D << NS;
3791 else
3792 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3793 << D;
3794 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3795 return;
3796 }
3797
3798 // C++0x [temp.explicit]p2:
3799 // If the name declared in the explicit instantiation is an unqualified
3800 // name, the explicit instantiation shall appear in the namespace where
3801 // its template is declared or, if that namespace is inline (7.3.1), any
3802 // namespace from its enclosing namespace set.
3803 if (WasQualifiedName)
3804 return;
3805
3806 if (CurContext->Equals(ExpectedContext))
3807 return;
3808
3809 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3810 << D << ExpectedContext;
3811 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3812}
3813
3814/// \brief Determine whether the given scope specifier has a template-id in it.
3815static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3816 if (!SS.isSet())
3817 return false;
3818
3819 // C++0x [temp.explicit]p2:
3820 // If the explicit instantiation is for a member function, a member class
3821 // or a static data member of a class template specialization, the name of
3822 // the class template specialization in the qualified-id for the member
3823 // name shall be a simple-template-id.
3824 //
3825 // C++98 has the same restriction, just worded differently.
3826 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3827 NNS; NNS = NNS->getPrefix())
3828 if (Type *T = NNS->getAsType())
3829 if (isa<TemplateSpecializationType>(T))
3830 return true;
3831
3832 return false;
3833}
3834
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003835// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003836// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003837Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003838Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003839 SourceLocation ExternLoc,
3840 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003841 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003842 SourceLocation KWLoc,
3843 const CXXScopeSpec &SS,
3844 TemplateTy TemplateD,
3845 SourceLocation TemplateNameLoc,
3846 SourceLocation LAngleLoc,
3847 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00003848 SourceLocation RAngleLoc,
3849 AttributeList *Attr) {
3850 // Find the class template we're specializing
3851 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003852 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003853 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3854
3855 // Check that the specialization uses the same tag kind as the
3856 // original template.
3857 TagDecl::TagKind Kind;
3858 switch (TagSpec) {
3859 default: assert(0 && "Unknown tag type!");
3860 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3861 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3862 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3863 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003864 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003865 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003866 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003867 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003868 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003869 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003870 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003871 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003872 diag::note_previous_use);
3873 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3874 }
3875
Douglas Gregore47f5a72009-10-14 23:41:34 +00003876 // C++0x [temp.explicit]p2:
3877 // There are two forms of explicit instantiation: an explicit instantiation
3878 // definition and an explicit instantiation declaration. An explicit
3879 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00003880 TemplateSpecializationKind TSK
3881 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3882 : TSK_ExplicitInstantiationDeclaration;
3883
Douglas Gregora1f49972009-05-13 00:25:59 +00003884 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00003885 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003886 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00003887
3888 // Check that the template argument list is well-formed for this
3889 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003890 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3891 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003892 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003893 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003894 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003895 return true;
3896
Mike Stump11289f42009-09-09 15:08:12 +00003897 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003898 ClassTemplate->getTemplateParameters()->size()) &&
3899 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003900
Douglas Gregora1f49972009-05-13 00:25:59 +00003901 // Find the class template specialization declaration that
3902 // corresponds to these arguments.
3903 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003904 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003905 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003906 Converted.flatSize(),
3907 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003908 void *InsertPos = 0;
3909 ClassTemplateSpecializationDecl *PrevDecl
3910 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3911
Douglas Gregor54888652009-10-07 00:13:32 +00003912 // C++0x [temp.explicit]p2:
3913 // [...] An explicit instantiation shall appear in an enclosing
3914 // namespace of its template. [...]
3915 //
3916 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00003917 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
3918 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00003919
Douglas Gregora1f49972009-05-13 00:25:59 +00003920 ClassTemplateSpecializationDecl *Specialization = 0;
3921
3922 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00003923 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003924 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00003925 PrevDecl,
3926 PrevDecl->getSpecializationKind(),
3927 PrevDecl->getPointOfInstantiation(),
3928 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00003929 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003930
Douglas Gregor12e49d32009-10-15 22:53:21 +00003931 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003932 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00003933
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003934 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3935 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3936 // Since the only prior class template specialization with these
3937 // arguments was referenced but not declared, reuse that
3938 // declaration node as our own, updating its source location to
3939 // reflect our new declaration.
3940 Specialization = PrevDecl;
3941 Specialization->setLocation(TemplateNameLoc);
3942 PrevDecl = 0;
3943 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00003944 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003945
3946 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003947 // Create a new class template specialization declaration node for
3948 // this explicit specialization.
3949 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003950 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003951 ClassTemplate->getDeclContext(),
3952 TemplateNameLoc,
3953 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003954 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003955
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003956 if (PrevDecl) {
3957 // Remove the previous declaration from the folding set, since we want
3958 // to introduce a new declaration.
3959 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3960 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3961 }
3962
3963 // Insert the new specialization.
3964 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003965 }
3966
3967 // Build the fully-sugared type for this explicit instantiation as
3968 // the user wrote in the explicit instantiation itself. This means
3969 // that we'll pretty-print the type retrieved from the
3970 // specialization's declaration the way that the user actually wrote
3971 // the explicit instantiation, rather than formatting the name based
3972 // on the "canonical" representation used to store the template
3973 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003974 QualType WrittenTy
3975 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003976 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003977 TemplateArgs.size(),
3978 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 McCall9f3059a2009-10-09 21:13:30 +00004188 LookupResult Previous;
4189 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
4190 Name, LookupOrdinaryName);
Douglas Gregor450f00842009-09-25 18:43:00 +00004191
4192 if (!R->isFunctionType()) {
4193 // C++ [temp.explicit]p1:
4194 // A [...] static data member of a class template can be explicitly
4195 // instantiated from the member definition associated with its class
4196 // template.
4197 if (Previous.isAmbiguous()) {
4198 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
4199 D.getSourceRange());
4200 }
4201
John McCall9f3059a2009-10-09 21:13:30 +00004202 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4203 Previous.getAsSingleDecl(Context));
Douglas Gregor450f00842009-09-25 18:43:00 +00004204 if (!Prev || !Prev->isStaticDataMember()) {
4205 // We expect to see a data data member here.
4206 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4207 << Name;
4208 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4209 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004210 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004211 return true;
4212 }
4213
4214 if (!Prev->getInstantiatedFromStaticDataMember()) {
4215 // FIXME: Check for explicit specialization?
4216 Diag(D.getIdentifierLoc(),
4217 diag::err_explicit_instantiation_data_member_not_instantiated)
4218 << Prev;
4219 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4220 // FIXME: Can we provide a note showing where this was declared?
4221 return true;
4222 }
4223
Douglas Gregore47f5a72009-10-14 23:41:34 +00004224 // C++0x [temp.explicit]p2:
4225 // If the explicit instantiation is for a member function, a member class
4226 // or a static data member of a class template specialization, the name of
4227 // the class template specialization in the qualified-id for the member
4228 // name shall be a simple-template-id.
4229 //
4230 // C++98 has the same restriction, just worded differently.
4231 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4232 Diag(D.getIdentifierLoc(),
4233 diag::err_explicit_instantiation_without_qualified_id)
4234 << Prev << D.getCXXScopeSpec().getRange();
4235
4236 // Check the scope of this explicit instantiation.
4237 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4238
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004239 // Verify that it is okay to explicitly instantiate here.
4240 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4241 assert(MSInfo && "Missing static data member specialization info?");
4242 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004243 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004244 MSInfo->getTemplateSpecializationKind(),
4245 MSInfo->getPointOfInstantiation(),
4246 SuppressNew))
4247 return true;
4248 if (SuppressNew)
4249 return DeclPtrTy();
4250
Douglas Gregor450f00842009-09-25 18:43:00 +00004251 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004252 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004253 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004254 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4255 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004256
4257 // FIXME: Create an ExplicitInstantiation node?
4258 return DeclPtrTy();
4259 }
4260
Douglas Gregor0e876e02009-09-25 23:53:26 +00004261 // If the declarator is a template-id, translate the parser's template
4262 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004263 bool HasExplicitTemplateArgs = false;
John McCall0ad16662009-10-29 08:12:44 +00004264 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004265 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4266 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Douglas Gregord90fd522009-09-25 21:45:23 +00004267 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4268 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004269 TemplateId->NumArgs);
4270 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregord90fd522009-09-25 21:45:23 +00004271 TemplateArgs);
4272 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004273 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004274 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004275
Douglas Gregor450f00842009-09-25 18:43:00 +00004276 // C++ [temp.explicit]p1:
4277 // A [...] function [...] can be explicitly instantiated from its template.
4278 // A member function [...] of a class template can be explicitly
4279 // instantiated from the member definition associated with its class
4280 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004281 llvm::SmallVector<FunctionDecl *, 8> Matches;
4282 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4283 P != PEnd; ++P) {
4284 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004285 if (!HasExplicitTemplateArgs) {
4286 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4287 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4288 Matches.clear();
4289 Matches.push_back(Method);
4290 break;
4291 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004292 }
4293 }
4294
4295 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4296 if (!FunTmpl)
4297 continue;
4298
4299 TemplateDeductionInfo Info(Context);
4300 FunctionDecl *Specialization = 0;
4301 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00004302 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
4303 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00004304 R, Specialization, Info)) {
4305 // FIXME: Keep track of almost-matches?
4306 (void)TDK;
4307 continue;
4308 }
4309
4310 Matches.push_back(Specialization);
4311 }
4312
4313 // Find the most specialized function template specialization.
4314 FunctionDecl *Specialization
4315 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4316 D.getIdentifierLoc(),
4317 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4318 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4319 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4320
4321 if (!Specialization)
4322 return true;
4323
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004324 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004325 Diag(D.getIdentifierLoc(),
4326 diag::err_explicit_instantiation_member_function_not_instantiated)
4327 << Specialization
4328 << (Specialization->getTemplateSpecializationKind() ==
4329 TSK_ExplicitSpecialization);
4330 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4331 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004332 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004333
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004334 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004335 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4336 PrevDecl = Specialization;
4337
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004338 if (PrevDecl) {
4339 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004340 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004341 PrevDecl,
4342 PrevDecl->getTemplateSpecializationKind(),
4343 PrevDecl->getPointOfInstantiation(),
4344 SuppressNew))
4345 return true;
4346
4347 // FIXME: We may still want to build some representation of this
4348 // explicit specialization.
4349 if (SuppressNew)
4350 return DeclPtrTy();
4351 }
4352
4353 if (TSK == TSK_ExplicitInstantiationDefinition)
4354 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4355 false, /*DefinitionRequired=*/true);
4356
4357 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4358
Douglas Gregore47f5a72009-10-14 23:41:34 +00004359 // C++0x [temp.explicit]p2:
4360 // If the explicit instantiation is for a member function, a member class
4361 // or a static data member of a class template specialization, the name of
4362 // the class template specialization in the qualified-id for the member
4363 // name shall be a simple-template-id.
4364 //
4365 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004366 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004367 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004368 D.getCXXScopeSpec().isSet() &&
4369 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4370 Diag(D.getIdentifierLoc(),
4371 diag::err_explicit_instantiation_without_qualified_id)
4372 << Specialization << D.getCXXScopeSpec().getRange();
4373
4374 CheckExplicitInstantiationScope(*this,
4375 FunTmpl? (NamedDecl *)FunTmpl
4376 : Specialization->getInstantiatedFromMemberFunction(),
4377 D.getIdentifierLoc(),
4378 D.getCXXScopeSpec().isSet());
4379
Douglas Gregor450f00842009-09-25 18:43:00 +00004380 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4381 return DeclPtrTy();
4382}
4383
Douglas Gregor333489b2009-03-27 23:10:48 +00004384Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004385Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4386 const CXXScopeSpec &SS, IdentifierInfo *Name,
4387 SourceLocation TagLoc, SourceLocation NameLoc) {
4388 // This has to hold, because SS is expected to be defined.
4389 assert(Name && "Expected a name in a dependent tag");
4390
4391 NestedNameSpecifier *NNS
4392 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4393 if (!NNS)
4394 return true;
4395
4396 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4397 if (T.isNull())
4398 return true;
4399
4400 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4401 QualType ElabType = Context.getElaboratedType(T, TagKind);
4402
4403 return ElabType.getAsOpaquePtr();
4404}
4405
4406Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004407Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4408 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004409 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004410 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4411 if (!NNS)
4412 return true;
4413
4414 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004415 if (T.isNull())
4416 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004417 return T.getAsOpaquePtr();
4418}
4419
Douglas Gregordce2b622009-04-01 00:28:59 +00004420Sema::TypeResult
4421Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4422 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004423 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004424 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004425 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004426 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004427 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004428 assert(TemplateId && "Expected a template specialization type");
4429
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004430 if (computeDeclContext(SS, false)) {
4431 // If we can compute a declaration context, then the "typename"
4432 // keyword was superfluous. Just build a QualifiedNameType to keep
4433 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004434
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004435 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4436 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4437 }
Mike Stump11289f42009-09-09 15:08:12 +00004438
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004439 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004440}
4441
Douglas Gregor333489b2009-03-27 23:10:48 +00004442/// \brief Build the type that describes a C++ typename specifier,
4443/// e.g., "typename T::type".
4444QualType
4445Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4446 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004447 CXXRecordDecl *CurrentInstantiation = 0;
4448 if (NNS->isDependent()) {
4449 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004450
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004451 // If the nested-name-specifier does not refer to the current
4452 // instantiation, then build a typename type.
4453 if (!CurrentInstantiation)
4454 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004455
Douglas Gregorc707da62009-09-02 13:12:51 +00004456 // The nested-name-specifier refers to the current instantiation, so the
4457 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004458 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004459 // extraneous "typename" keywords, and we retroactively apply this DR to
4460 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004461 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004462
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004463 DeclContext *Ctx = 0;
4464
4465 if (CurrentInstantiation)
4466 Ctx = CurrentInstantiation;
4467 else {
4468 CXXScopeSpec SS;
4469 SS.setScopeRep(NNS);
4470 SS.setRange(Range);
4471 if (RequireCompleteDeclContext(SS))
4472 return QualType();
4473
4474 Ctx = computeDeclContext(SS);
4475 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004476 assert(Ctx && "No declaration context?");
4477
4478 DeclarationName Name(&II);
John McCall9f3059a2009-10-09 21:13:30 +00004479 LookupResult Result;
4480 LookupQualifiedName(Result, Ctx, Name, LookupOrdinaryName, false);
Douglas Gregor333489b2009-03-27 23:10:48 +00004481 unsigned DiagID = 0;
4482 Decl *Referenced = 0;
4483 switch (Result.getKind()) {
4484 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004485 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004486 break;
4487
4488 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004489 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004490 // We found a type. Build a QualifiedNameType, since the
4491 // typename-specifier was just sugar. FIXME: Tell
4492 // QualifiedNameType that it has a "typename" prefix.
4493 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4494 }
4495
4496 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004497 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004498 break;
4499
4500 case LookupResult::FoundOverloaded:
4501 DiagID = diag::err_typename_nested_not_type;
4502 Referenced = *Result.begin();
4503 break;
4504
John McCall6538c932009-10-10 05:48:19 +00004505 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004506 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
4507 return QualType();
4508 }
4509
4510 // If we get here, it's because name lookup did not find a
4511 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004512 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004513 if (Referenced)
4514 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4515 << Name;
4516 return QualType();
4517}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004518
4519namespace {
4520 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00004521 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4522 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004523 SourceLocation Loc;
4524 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004525
Douglas Gregor15acfb92009-08-06 16:20:37 +00004526 public:
Mike Stump11289f42009-09-09 15:08:12 +00004527 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004528 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004529 DeclarationName Entity)
4530 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004531 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004532
4533 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004534 /// transformed.
4535 ///
4536 /// For the purposes of type reconstruction, a type has already been
4537 /// transformed if it is NULL or if it is not dependent.
4538 bool AlreadyTransformed(QualType T) {
4539 return T.isNull() || !T->isDependentType();
4540 }
Mike Stump11289f42009-09-09 15:08:12 +00004541
4542 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004543 /// rebuilt.
4544 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004545
Douglas Gregor15acfb92009-08-06 16:20:37 +00004546 /// \brief Returns the name of the entity whose type is being rebuilt.
4547 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004548
Douglas Gregoref6ab412009-10-27 06:26:26 +00004549 /// \brief Sets the "base" location and entity when that
4550 /// information is known based on another transformation.
4551 void setBase(SourceLocation Loc, DeclarationName Entity) {
4552 this->Loc = Loc;
4553 this->Entity = Entity;
4554 }
4555
Douglas Gregor15acfb92009-08-06 16:20:37 +00004556 /// \brief Transforms an expression by returning the expression itself
4557 /// (an identity function).
4558 ///
4559 /// FIXME: This is completely unsafe; we will need to actually clone the
4560 /// expressions.
4561 Sema::OwningExprResult TransformExpr(Expr *E) {
4562 return getSema().Owned(E);
4563 }
Mike Stump11289f42009-09-09 15:08:12 +00004564
Douglas Gregor15acfb92009-08-06 16:20:37 +00004565 /// \brief Transforms a typename type by determining whether the type now
4566 /// refers to a member of the current instantiation, and then
4567 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004568 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004569 };
4570}
4571
Mike Stump11289f42009-09-09 15:08:12 +00004572QualType
John McCall550e0c22009-10-21 00:40:46 +00004573CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4574 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004575 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004576
Douglas Gregor15acfb92009-08-06 16:20:37 +00004577 NestedNameSpecifier *NNS
4578 = TransformNestedNameSpecifier(T->getQualifier(),
4579 /*FIXME:*/SourceRange(getBaseLocation()));
4580 if (!NNS)
4581 return QualType();
4582
4583 // If the nested-name-specifier did not change, and we cannot compute the
4584 // context corresponding to the nested-name-specifier, then this
4585 // typename type will not change; exit early.
4586 CXXScopeSpec SS;
4587 SS.setRange(SourceRange(getBaseLocation()));
4588 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004589
4590 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004591 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004592 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004593
4594 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004595 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004596 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004597 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004598 = TransformType(QualType(TemplateId, 0));
4599 if (NewTemplateId.isNull())
4600 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004601
Douglas Gregor15acfb92009-08-06 16:20:37 +00004602 if (NNS == T->getQualifier() &&
4603 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004604 Result = QualType(T, 0);
4605 else
4606 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4607 } else
4608 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4609 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004610
John McCall0ad16662009-10-29 08:12:44 +00004611 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4612 NewTL.setNameLoc(TL.getNameLoc());
4613 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004614}
4615
4616/// \brief Rebuilds a type within the context of the current instantiation.
4617///
Mike Stump11289f42009-09-09 15:08:12 +00004618/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004619/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004620/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004621/// partial specialization thereof). This routine will rebuild that type now
4622/// that we have entered the declarator's scope, which may produce different
4623/// canonical types, e.g.,
4624///
4625/// \code
4626/// template<typename T>
4627/// struct X {
4628/// typedef T* pointer;
4629/// pointer data();
4630/// };
4631///
4632/// template<typename T>
4633/// typename X<T>::pointer X<T>::data() { ... }
4634/// \endcode
4635///
4636/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4637/// since we do not know that we can look into X<T> when we parsed the type.
4638/// This function will rebuild the type, performing the lookup of "pointer"
4639/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4640/// as the canonical type of T*, allowing the return types of the out-of-line
4641/// definition and the declaration to match.
4642QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4643 DeclarationName Name) {
4644 if (T.isNull() || !T->isDependentType())
4645 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004646
Douglas Gregor15acfb92009-08-06 16:20:37 +00004647 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4648 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004649}
Douglas Gregorbe999392009-09-15 16:23:51 +00004650
4651/// \brief Produces a formatted string that describes the binding of
4652/// template parameters to template arguments.
4653std::string
4654Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4655 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004656 // FIXME: For variadic templates, we'll need to get the structured list.
4657 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4658 Args.flat_size());
4659}
4660
4661std::string
4662Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4663 const TemplateArgument *Args,
4664 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004665 std::string Result;
4666
Douglas Gregore62e6a02009-11-11 19:13:48 +00004667 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00004668 return Result;
4669
4670 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004671 if (I >= NumArgs)
4672 break;
4673
Douglas Gregorbe999392009-09-15 16:23:51 +00004674 if (I == 0)
4675 Result += "[with ";
4676 else
4677 Result += ", ";
4678
4679 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4680 Result += Id->getName();
4681 } else {
4682 Result += '$';
4683 Result += llvm::utostr(I);
4684 }
4685
4686 Result += " = ";
4687
4688 switch (Args[I].getKind()) {
4689 case TemplateArgument::Null:
4690 Result += "<no value>";
4691 break;
4692
4693 case TemplateArgument::Type: {
4694 std::string TypeStr;
4695 Args[I].getAsType().getAsStringInternal(TypeStr,
4696 Context.PrintingPolicy);
4697 Result += TypeStr;
4698 break;
4699 }
4700
4701 case TemplateArgument::Declaration: {
4702 bool Unnamed = true;
4703 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4704 if (ND->getDeclName()) {
4705 Unnamed = false;
4706 Result += ND->getNameAsString();
4707 }
4708 }
4709
4710 if (Unnamed) {
4711 Result += "<anonymous>";
4712 }
4713 break;
4714 }
4715
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004716 case TemplateArgument::Template: {
4717 std::string Str;
4718 llvm::raw_string_ostream OS(Str);
4719 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4720 Result += OS.str();
4721 break;
4722 }
4723
Douglas Gregorbe999392009-09-15 16:23:51 +00004724 case TemplateArgument::Integral: {
4725 Result += Args[I].getAsIntegral()->toString(10);
4726 break;
4727 }
4728
4729 case TemplateArgument::Expression: {
4730 assert(false && "No expressions in deduced template arguments!");
4731 Result += "<expression>";
4732 break;
4733 }
4734
4735 case TemplateArgument::Pack:
4736 // FIXME: Format template argument packs
4737 Result += "<template argument pack>";
4738 break;
4739 }
4740 }
4741
4742 Result += ']';
4743 return Result;
4744}