blob: aace9834416e179ebd69c6af2c4f47f27f251e2f [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(),
709 /*Complain=*/true))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000710 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000711
712 // C++ [temp.class]p4:
713 // In a redeclaration, partial specialization, explicit
714 // specialization or explicit instantiation of a class template,
715 // the class-key shall agree in kind with the original class
716 // template declaration (7.1.5.3).
717 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000718 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000719 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000720 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000721 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000722 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000723 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000724 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000725 }
726
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000727 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000728 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000729 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
730 Diag(NameLoc, diag::err_redefinition) << Name;
731 Diag(Def->getLocation(), diag::note_previous_definition);
732 // FIXME: Would it make sense to try to "forget" the previous
733 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000734 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000735 }
736 }
737 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
738 // Maybe we will complain about the shadowed template parameter.
739 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
740 // Just pretend that we didn't see the previous declaration.
741 PrevDecl = 0;
742 } else if (PrevDecl) {
743 // C++ [temp]p5:
744 // A class template shall not have the same name as any other
745 // template, class, function, object, enumeration, enumerator,
746 // namespace, or type in the same scope (3.3), except as specified
747 // in (14.5.4).
748 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
749 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000750 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000751 }
752
Douglas Gregordba32632009-02-10 19:49:53 +0000753 // Check the template parameter list of this declaration, possibly
754 // merging in the template parameter list from the previous class
755 // template declaration.
756 if (CheckTemplateParameterList(TemplateParams,
757 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
758 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000759
Douglas Gregore362cea2009-05-10 22:57:19 +0000760 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000761 // declaration!
762
Mike Stump11289f42009-09-09 15:08:12 +0000763 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000764 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000765 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000766 PrevClassTemplate->getTemplatedDecl() : 0,
767 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000768
769 ClassTemplateDecl *NewTemplate
770 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
771 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000772 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000773 NewClass->setDescribedClassTemplate(NewTemplate);
774
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000775 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000776 QualType T =
777 Context.getTypeDeclType(NewClass,
778 PrevClassTemplate?
779 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000780 assert(T->isDependentType() && "Class template type is not dependent?");
781 (void)T;
782
Douglas Gregorcf915552009-10-13 16:30:37 +0000783 // If we are providing an explicit specialization of a member that is a
784 // class template, make a note of that.
785 if (PrevClassTemplate &&
786 PrevClassTemplate->getInstantiatedFromMemberTemplate())
787 PrevClassTemplate->setMemberSpecialization();
788
Anders Carlsson137108d2009-03-26 01:24:28 +0000789 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000790 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000791 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000792
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000793 // Set the lexical context of these templates
794 NewClass->setLexicalDeclContext(CurContext);
795 NewTemplate->setLexicalDeclContext(CurContext);
796
John McCall9bb74a52009-07-31 02:45:11 +0000797 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000798 NewClass->startDefinition();
799
800 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000801 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000802
John McCall27b5c252009-09-14 21:59:20 +0000803 if (TUK != TUK_Friend)
804 PushOnScopeChains(NewTemplate, S);
805 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000806 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000807 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000808 NewClass->setAccess(PrevClassTemplate->getAccess());
809 }
John McCall27b5c252009-09-14 21:59:20 +0000810
Douglas Gregor3dad8422009-09-26 06:47:28 +0000811 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
812 PrevClassTemplate != NULL);
813
John McCall27b5c252009-09-14 21:59:20 +0000814 // Friend templates are visible in fairly strange ways.
815 if (!CurContext->isDependentContext()) {
816 DeclContext *DC = SemanticContext->getLookupContext();
817 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
818 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
819 PushOnScopeChains(NewTemplate, EnclosingScope,
820 /* AddToContext = */ false);
821 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000822
823 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
824 NewClass->getLocation(),
825 NewTemplate,
826 /*FIXME:*/NewClass->getLocation());
827 Friend->setAccess(AS_public);
828 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000829 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000830
Douglas Gregordba32632009-02-10 19:49:53 +0000831 if (Invalid) {
832 NewTemplate->setInvalidDecl();
833 NewClass->setInvalidDecl();
834 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000835 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000836}
837
Douglas Gregordba32632009-02-10 19:49:53 +0000838/// \brief Checks the validity of a template parameter list, possibly
839/// considering the template parameter list from a previous
840/// declaration.
841///
842/// If an "old" template parameter list is provided, it must be
843/// equivalent (per TemplateParameterListsAreEqual) to the "new"
844/// template parameter list.
845///
846/// \param NewParams Template parameter list for a new template
847/// declaration. This template parameter list will be updated with any
848/// default arguments that are carried through from the previous
849/// template parameter list.
850///
851/// \param OldParams If provided, template parameter list from a
852/// previous declaration of the same template. Default template
853/// arguments will be merged from the old template parameter list to
854/// the new template parameter list.
855///
856/// \returns true if an error occurred, false otherwise.
857bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
858 TemplateParameterList *OldParams) {
859 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000860
Douglas Gregordba32632009-02-10 19:49:53 +0000861 // C++ [temp.param]p10:
862 // The set of default template-arguments available for use with a
863 // template declaration or definition is obtained by merging the
864 // default arguments from the definition (if in scope) and all
865 // declarations in scope in the same way default function
866 // arguments are (8.3.6).
867 bool SawDefaultArgument = false;
868 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000869
Anders Carlsson327865d2009-06-12 23:20:15 +0000870 bool SawParameterPack = false;
871 SourceLocation ParameterPackLoc;
872
Mike Stumpc89c8e32009-02-11 23:03:27 +0000873 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000874 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000875 if (OldParams)
876 OldParam = OldParams->begin();
877
878 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
879 NewParamEnd = NewParams->end();
880 NewParam != NewParamEnd; ++NewParam) {
881 // Variables used to diagnose redundant default arguments
882 bool RedundantDefaultArg = false;
883 SourceLocation OldDefaultLoc;
884 SourceLocation NewDefaultLoc;
885
886 // Variables used to diagnose missing default arguments
887 bool MissingDefaultArg = false;
888
Anders Carlsson327865d2009-06-12 23:20:15 +0000889 // C++0x [temp.param]p11:
890 // If a template parameter of a class template is a template parameter pack,
891 // it must be the last template parameter.
892 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +0000893 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +0000894 diag::err_template_param_pack_must_be_last_template_parameter);
895 Invalid = true;
896 }
897
Douglas Gregordba32632009-02-10 19:49:53 +0000898 // Merge default arguments for template type parameters.
899 if (TemplateTypeParmDecl *NewTypeParm
900 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump11289f42009-09-09 15:08:12 +0000901 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000902 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000903
Anders Carlsson327865d2009-06-12 23:20:15 +0000904 if (NewTypeParm->isParameterPack()) {
905 assert(!NewTypeParm->hasDefaultArgument() &&
906 "Parameter packs can't have a default argument!");
907 SawParameterPack = true;
908 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000909 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +0000910 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +0000911 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
912 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
913 SawDefaultArgument = true;
914 RedundantDefaultArg = true;
915 PreviousDefaultArgLoc = NewDefaultLoc;
916 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
917 // Merge the default argument from the old declaration to the
918 // new declaration.
919 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +0000920 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +0000921 true);
922 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
923 } else if (NewTypeParm->hasDefaultArgument()) {
924 SawDefaultArgument = true;
925 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
926 } else if (SawDefaultArgument)
927 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000928 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000929 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000930 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000931 NonTypeTemplateParmDecl *OldNonTypeParm
932 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000933 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000934 NewNonTypeParm->hasDefaultArgument()) {
935 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
936 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
937 SawDefaultArgument = true;
938 RedundantDefaultArg = true;
939 PreviousDefaultArgLoc = NewDefaultLoc;
940 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
941 // Merge the default argument from the old declaration to the
942 // new declaration.
943 SawDefaultArgument = true;
944 // FIXME: We need to create a new kind of "default argument"
945 // expression that points to a previous template template
946 // parameter.
947 NewNonTypeParm->setDefaultArgument(
948 OldNonTypeParm->getDefaultArgument());
949 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
950 } else if (NewNonTypeParm->hasDefaultArgument()) {
951 SawDefaultArgument = true;
952 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
953 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000954 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000955 } else {
Douglas Gregordba32632009-02-10 19:49:53 +0000956 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000957 TemplateTemplateParmDecl *NewTemplateParm
958 = cast<TemplateTemplateParmDecl>(*NewParam);
959 TemplateTemplateParmDecl *OldTemplateParm
960 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000961 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000962 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000963 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
964 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +0000965 SawDefaultArgument = true;
966 RedundantDefaultArg = true;
967 PreviousDefaultArgLoc = NewDefaultLoc;
968 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
969 // Merge the default argument from the old declaration to the
970 // new declaration.
971 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +0000972 // FIXME: We need to create a new kind of "default argument" expression
973 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +0000974 NewTemplateParm->setDefaultArgument(
975 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000976 PreviousDefaultArgLoc
977 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +0000978 } else if (NewTemplateParm->hasDefaultArgument()) {
979 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000980 PreviousDefaultArgLoc
981 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +0000982 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000983 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +0000984 }
985
986 if (RedundantDefaultArg) {
987 // C++ [temp.param]p12:
988 // A template-parameter shall not be given default arguments
989 // by two different declarations in the same scope.
990 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
991 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
992 Invalid = true;
993 } else if (MissingDefaultArg) {
994 // C++ [temp.param]p11:
995 // If a template-parameter has a default template-argument,
996 // all subsequent template-parameters shall have a default
997 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +0000998 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +0000999 diag::err_template_param_default_arg_missing);
1000 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1001 Invalid = true;
1002 }
1003
1004 // If we have an old template parameter list that we're merging
1005 // in, move on to the next parameter.
1006 if (OldParams)
1007 ++OldParam;
1008 }
1009
1010 return Invalid;
1011}
Douglas Gregord32e0282009-02-09 23:23:08 +00001012
Mike Stump11289f42009-09-09 15:08:12 +00001013/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001014/// specifier, returning the template parameter list that applies to the
1015/// name.
1016///
1017/// \param DeclStartLoc the start of the declaration that has a scope
1018/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001019///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001020/// \param SS the scope specifier that will be matched to the given template
1021/// parameter lists. This scope specifier precedes a qualified name that is
1022/// being declared.
1023///
1024/// \param ParamLists the template parameter lists, from the outermost to the
1025/// innermost template parameter lists.
1026///
1027/// \param NumParamLists the number of template parameter lists in ParamLists.
1028///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001029/// \param IsExplicitSpecialization will be set true if the entity being
1030/// declared is an explicit specialization, false otherwise.
1031///
Mike Stump11289f42009-09-09 15:08:12 +00001032/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001033/// name that is preceded by the scope specifier @p SS. This template
1034/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001035/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001036/// template specialization), or may be NULL (if we were's declaring isn't
1037/// itself a template).
1038TemplateParameterList *
1039Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1040 const CXXScopeSpec &SS,
1041 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001042 unsigned NumParamLists,
1043 bool &IsExplicitSpecialization) {
1044 IsExplicitSpecialization = false;
1045
Douglas Gregord8d297c2009-07-21 23:53:31 +00001046 // Find the template-ids that occur within the nested-name-specifier. These
1047 // template-ids will match up with the template parameter lists.
1048 llvm::SmallVector<const TemplateSpecializationType *, 4>
1049 TemplateIdsInSpecifier;
1050 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1051 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +00001052 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +00001053 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1054 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1055 if (!Template)
1056 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001057
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001058 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001059 ClassTemplateSpecializationDecl *SpecDecl
1060 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1061 // If the nested name specifier refers to an explicit specialization,
1062 // we don't need a template<> header.
Douglas Gregor82e22862009-09-16 00:01:48 +00001063 // FIXME: revisit this approach once we cope with specializations
Douglas Gregor15301382009-07-30 17:40:51 +00001064 // properly.
Douglas Gregord8d297c2009-07-21 23:53:31 +00001065 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
1066 continue;
1067 }
Mike Stump11289f42009-09-09 15:08:12 +00001068
Douglas Gregord8d297c2009-07-21 23:53:31 +00001069 TemplateIdsInSpecifier.push_back(SpecType);
1070 }
1071 }
Mike Stump11289f42009-09-09 15:08:12 +00001072
Douglas Gregord8d297c2009-07-21 23:53:31 +00001073 // Reverse the list of template-ids in the scope specifier, so that we can
1074 // more easily match up the template-ids and the template parameter lists.
1075 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001076
Douglas Gregord8d297c2009-07-21 23:53:31 +00001077 SourceLocation FirstTemplateLoc = DeclStartLoc;
1078 if (NumParamLists)
1079 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001080
Douglas Gregord8d297c2009-07-21 23:53:31 +00001081 // Match the template-ids found in the specifier to the template parameter
1082 // lists.
1083 unsigned Idx = 0;
1084 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1085 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001086 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1087 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001088 if (Idx >= NumParamLists) {
1089 // We have a template-id without a corresponding template parameter
1090 // list.
1091 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001092 // FIXME: the location information here isn't great.
1093 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001094 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001095 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001096 << SS.getRange();
1097 } else {
1098 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1099 << SS.getRange()
1100 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1101 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001102 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001103 }
1104 return 0;
1105 }
Mike Stump11289f42009-09-09 15:08:12 +00001106
Douglas Gregord8d297c2009-07-21 23:53:31 +00001107 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001108 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001109 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001110 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1111
Mike Stump11289f42009-09-09 15:08:12 +00001112 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001113 = dyn_cast<ClassTemplateDecl>(Template)) {
1114 TemplateParameterList *ExpectedTemplateParams = 0;
1115 // Is this template-id naming the primary template?
1116 if (Context.hasSameType(TemplateId,
1117 ClassTemplate->getInjectedClassNameType(Context)))
1118 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1119 // ... or a partial specialization?
1120 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1121 = ClassTemplate->findPartialSpecialization(TemplateId))
1122 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1123
1124 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001125 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001126 ExpectedTemplateParams,
1127 true);
Mike Stump11289f42009-09-09 15:08:12 +00001128 }
Douglas Gregor15301382009-07-30 17:40:51 +00001129 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001130 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001131 diag::err_template_param_list_matches_nontemplate)
1132 << TemplateId
1133 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001134 else
1135 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001136 }
Mike Stump11289f42009-09-09 15:08:12 +00001137
Douglas Gregord8d297c2009-07-21 23:53:31 +00001138 // If there were at least as many template-ids as there were template
1139 // parameter lists, then there are no template parameter lists remaining for
1140 // the declaration itself.
1141 if (Idx >= NumParamLists)
1142 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001143
Douglas Gregord8d297c2009-07-21 23:53:31 +00001144 // If there were too many template parameter lists, complain about that now.
1145 if (Idx != NumParamLists - 1) {
1146 while (Idx < NumParamLists - 1) {
Mike Stump11289f42009-09-09 15:08:12 +00001147 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001148 diag::err_template_spec_extra_headers)
1149 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1150 ParamLists[Idx]->getRAngleLoc());
1151 ++Idx;
1152 }
1153 }
Mike Stump11289f42009-09-09 15:08:12 +00001154
Douglas Gregord8d297c2009-07-21 23:53:31 +00001155 // Return the last template parameter list, which corresponds to the
1156 // entity being declared.
1157 return ParamLists[NumParamLists - 1];
1158}
1159
Douglas Gregordc572a32009-03-30 22:58:21 +00001160QualType Sema::CheckTemplateIdType(TemplateName Name,
1161 SourceLocation TemplateLoc,
1162 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001163 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregordc572a32009-03-30 22:58:21 +00001164 unsigned NumTemplateArgs,
1165 SourceLocation RAngleLoc) {
1166 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001167 if (!Template) {
1168 // The template name does not resolve to a template, so we just
1169 // build a dependent template-id type.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001170 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001171 NumTemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001172 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001173
Douglas Gregorc40290e2009-03-09 23:48:35 +00001174 // Check that the template argument list is well-formed for this
1175 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001176 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1177 NumTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001178 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001179 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001180 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001181 return QualType();
1182
Mike Stump11289f42009-09-09 15:08:12 +00001183 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001184 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001185 "Converted template argument list is too short!");
1186
1187 QualType CanonType;
1188
Douglas Gregordc572a32009-03-30 22:58:21 +00001189 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorc40290e2009-03-09 23:48:35 +00001190 TemplateArgs,
1191 NumTemplateArgs)) {
1192 // This class template specialization is a dependent
1193 // type. Therefore, its canonical type is another class template
1194 // specialization type that contains all of the converted
1195 // arguments in canonical form. This ensures that, e.g., A<T> and
1196 // A<T, T> have identical types when A is declared as:
1197 //
1198 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001199 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001200 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001201 Converted.getFlatArguments(),
1202 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001203
Douglas Gregora8e02e72009-07-28 23:00:59 +00001204 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001205 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001206 // In the future, we need to teach getTemplateSpecializationType to only
1207 // build the canonical type and return that to us.
1208 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001209 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001210 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001211 // Find the class template specialization declaration that
1212 // corresponds to these arguments.
1213 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001214 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001215 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001216 Converted.flatSize(),
1217 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001218 void *InsertPos = 0;
1219 ClassTemplateSpecializationDecl *Decl
1220 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1221 if (!Decl) {
1222 // This is the first time we have referenced this class template
1223 // specialization. Create the canonical declaration and add it to
1224 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001225 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001226 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001227 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001228 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001229 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001230 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1231 Decl->setLexicalDeclContext(CurContext);
1232 }
1233
1234 CanonType = Context.getTypeDeclType(Decl);
1235 }
Mike Stump11289f42009-09-09 15:08:12 +00001236
Douglas Gregorc40290e2009-03-09 23:48:35 +00001237 // Build the fully-sugared type for this class template
1238 // specialization, which refers back to the class template
1239 // specialization we created or found.
Douglas Gregordc572a32009-03-30 22:58:21 +00001240 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1241 NumTemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001242}
1243
Douglas Gregor67a65642009-02-17 23:15:12 +00001244Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001245Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001246 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001247 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001248 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001249 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001250
Douglas Gregorc40290e2009-03-09 23:48:35 +00001251 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00001252 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001253 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001254
Douglas Gregordc572a32009-03-30 22:58:21 +00001255 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +00001256 TemplateArgs.data(),
1257 TemplateArgs.size(),
Douglas Gregordc572a32009-03-30 22:58:21 +00001258 RAngleLoc);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001259 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001260
1261 if (Result.isNull())
1262 return true;
1263
John McCall0ad16662009-10-29 08:12:44 +00001264 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1265 TemplateSpecializationTypeLoc TL
1266 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1267 TL.setTemplateNameLoc(TemplateLoc);
1268 TL.setLAngleLoc(LAngleLoc);
1269 TL.setRAngleLoc(RAngleLoc);
1270 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1271 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1272
1273 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001274}
John McCall06f6fe8d2009-09-04 01:14:41 +00001275
John McCalld8fe9af2009-09-08 17:47:29 +00001276Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1277 TagUseKind TUK,
1278 DeclSpec::TST TagSpec,
1279 SourceLocation TagLoc) {
1280 if (TypeResult.isInvalid())
1281 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001282
John McCall0ad16662009-10-29 08:12:44 +00001283 // FIXME: preserve source info, ideally without copying the DI.
1284 DeclaratorInfo *DI;
1285 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001286
John McCalld8fe9af2009-09-08 17:47:29 +00001287 // Verify the tag specifier.
1288 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001289
John McCalld8fe9af2009-09-08 17:47:29 +00001290 if (const RecordType *RT = Type->getAs<RecordType>()) {
1291 RecordDecl *D = RT->getDecl();
1292
1293 IdentifierInfo *Id = D->getIdentifier();
1294 assert(Id && "templated class must have an identifier");
1295
1296 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1297 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001298 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001299 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1300 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001301 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001302 }
1303 }
1304
John McCalld8fe9af2009-09-08 17:47:29 +00001305 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1306
1307 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001308}
1309
Douglas Gregord019ff62009-10-22 17:20:55 +00001310Sema::OwningExprResult Sema::BuildTemplateIdExpr(NestedNameSpecifier *Qualifier,
1311 SourceRange QualifierRange,
1312 TemplateName Template,
Douglas Gregora727cb92009-06-30 22:34:41 +00001313 SourceLocation TemplateNameLoc,
1314 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001315 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001316 unsigned NumTemplateArgs,
1317 SourceLocation RAngleLoc) {
1318 // FIXME: Can we do any checking at this point? I guess we could check the
1319 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001320 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001321 // though.
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001322
1323 // Cope with an implicit member access in a C++ non-static member function.
1324 NamedDecl *D = Template.getAsTemplateDecl();
1325 if (!D)
1326 D = Template.getAsOverloadedFunctionDecl();
1327
Douglas Gregord019ff62009-10-22 17:20:55 +00001328 CXXScopeSpec SS;
1329 SS.setRange(QualifierRange);
1330 SS.setScopeRep(Qualifier);
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001331 QualType ThisType, MemberType;
Douglas Gregord019ff62009-10-22 17:20:55 +00001332 if (D && isImplicitMemberReference(&SS, D, TemplateNameLoc,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001333 ThisType, MemberType)) {
1334 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
1335 return Owned(MemberExpr::Create(Context, This, true,
Douglas Gregord019ff62009-10-22 17:20:55 +00001336 Qualifier, QualifierRange,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001337 D, TemplateNameLoc, true,
1338 LAngleLoc, TemplateArgs,
1339 NumTemplateArgs, RAngleLoc,
1340 Context.OverloadTy));
1341 }
1342
Douglas Gregord019ff62009-10-22 17:20:55 +00001343 return Owned(TemplateIdRefExpr::Create(Context, Context.OverloadTy,
1344 Qualifier, QualifierRange,
Douglas Gregora727cb92009-06-30 22:34:41 +00001345 Template, TemplateNameLoc, LAngleLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001346 TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001347 NumTemplateArgs, RAngleLoc));
1348}
1349
Douglas Gregord019ff62009-10-22 17:20:55 +00001350Sema::OwningExprResult Sema::ActOnTemplateIdExpr(const CXXScopeSpec &SS,
1351 TemplateTy TemplateD,
Douglas Gregora727cb92009-06-30 22:34:41 +00001352 SourceLocation TemplateNameLoc,
1353 SourceLocation LAngleLoc,
1354 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora727cb92009-06-30 22:34:41 +00001355 SourceLocation RAngleLoc) {
1356 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001357
Douglas Gregora727cb92009-06-30 22:34:41 +00001358 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00001359 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001360 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001361 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001362
Douglas Gregord019ff62009-10-22 17:20:55 +00001363 return BuildTemplateIdExpr((NestedNameSpecifier *)SS.getScopeRep(),
1364 SS.getRange(),
1365 Template, TemplateNameLoc, LAngleLoc,
Douglas Gregora727cb92009-06-30 22:34:41 +00001366 TemplateArgs.data(), TemplateArgs.size(),
1367 RAngleLoc);
1368}
1369
Douglas Gregorb67535d2009-03-31 00:43:58 +00001370/// \brief Form a dependent template name.
1371///
1372/// This action forms a dependent template name given the template
1373/// name and its (presumably dependent) scope specifier. For
1374/// example, given "MetaFun::template apply", the scope specifier \p
1375/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1376/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001377Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001378Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001379 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001380 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001381 TypeTy *ObjectType) {
Mike Stump11289f42009-09-09 15:08:12 +00001382 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001383 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1384 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001385 // C++0x [temp.names]p5:
1386 // If a name prefixed by the keyword template is not the name of
1387 // a template, the program is ill-formed. [Note: the keyword
1388 // template may not be applied to non-template members of class
1389 // templates. -end note ] [ Note: as is the case with the
1390 // typename prefix, the template prefix is allowed in cases
1391 // where it is not strictly necessary; i.e., when the
1392 // nested-name-specifier or the expression on the left of the ->
1393 // or . is not dependent on a template-parameter, or the use
1394 // does not appear in the scope of a template. -end note]
1395 //
1396 // Note: C++03 was more strict here, because it banned the use of
1397 // the "template" keyword prior to a template-name that was not a
1398 // dependent name. C++ DR468 relaxed this requirement (the
1399 // "template" keyword is now permitted). We follow the C++0x
1400 // rules, even in C++03 mode, retroactively applying the DR.
1401 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001402 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001403 false, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001404 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001405 Diag(Name.getSourceRange().getBegin(),
1406 diag::err_template_kw_refers_to_non_template)
1407 << GetNameFromUnqualifiedId(Name)
1408 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001409 return TemplateTy();
1410 }
1411
1412 return Template;
1413 }
1414
Mike Stump11289f42009-09-09 15:08:12 +00001415 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001416 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001417
1418 switch (Name.getKind()) {
1419 case UnqualifiedId::IK_Identifier:
1420 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1421 Name.Identifier));
1422
Douglas Gregor71395fa2009-11-04 00:56:37 +00001423 case UnqualifiedId::IK_OperatorFunctionId:
1424 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1425 Name.OperatorFunctionId.Operator));
1426
Douglas Gregor3cf81312009-11-03 23:16:33 +00001427 default:
1428 break;
1429 }
1430
1431 Diag(Name.getSourceRange().getBegin(),
1432 diag::err_template_kw_refers_to_non_template)
1433 << GetNameFromUnqualifiedId(Name)
1434 << Name.getSourceRange();
1435 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001436}
1437
Mike Stump11289f42009-09-09 15:08:12 +00001438bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001439 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001440 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001441 const TemplateArgument &Arg = AL.getArgument();
1442
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001443 // Check template type parameter.
1444 if (Arg.getKind() != TemplateArgument::Type) {
1445 // C++ [temp.arg.type]p1:
1446 // A template-argument for a template-parameter which is a
1447 // type shall be a type-id.
1448
1449 // We have a template type parameter but the template argument
1450 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001451 SourceRange SR = AL.getSourceRange();
1452 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001453 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001454
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001455 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001456 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001457
John McCall0ad16662009-10-29 08:12:44 +00001458 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001459 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001460
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001461 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001462 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001463 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001464 return false;
1465}
1466
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001467/// \brief Substitute template arguments into the default template argument for
1468/// the given template type parameter.
1469///
1470/// \param SemaRef the semantic analysis object for which we are performing
1471/// the substitution.
1472///
1473/// \param Template the template that we are synthesizing template arguments
1474/// for.
1475///
1476/// \param TemplateLoc the location of the template name that started the
1477/// template-id we are checking.
1478///
1479/// \param RAngleLoc the location of the right angle bracket ('>') that
1480/// terminates the template-id.
1481///
1482/// \param Param the template template parameter whose default we are
1483/// substituting into.
1484///
1485/// \param Converted the list of template arguments provided for template
1486/// parameters that precede \p Param in the template parameter list.
1487///
1488/// \returns the substituted template argument, or NULL if an error occurred.
1489static DeclaratorInfo *
1490SubstDefaultTemplateArgument(Sema &SemaRef,
1491 TemplateDecl *Template,
1492 SourceLocation TemplateLoc,
1493 SourceLocation RAngleLoc,
1494 TemplateTypeParmDecl *Param,
1495 TemplateArgumentListBuilder &Converted) {
1496 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1497
1498 // If the argument type is dependent, instantiate it now based
1499 // on the previously-computed template arguments.
1500 if (ArgType->getType()->isDependentType()) {
1501 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1502 /*TakeArgs=*/false);
1503
1504 MultiLevelTemplateArgumentList AllTemplateArgs
1505 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1506
1507 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1508 Template, Converted.getFlatArguments(),
1509 Converted.flatSize(),
1510 SourceRange(TemplateLoc, RAngleLoc));
1511
1512 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1513 Param->getDefaultArgumentLoc(),
1514 Param->getDeclName());
1515 }
1516
1517 return ArgType;
1518}
1519
1520/// \brief Substitute template arguments into the default template argument for
1521/// the given non-type template parameter.
1522///
1523/// \param SemaRef the semantic analysis object for which we are performing
1524/// the substitution.
1525///
1526/// \param Template the template that we are synthesizing template arguments
1527/// for.
1528///
1529/// \param TemplateLoc the location of the template name that started the
1530/// template-id we are checking.
1531///
1532/// \param RAngleLoc the location of the right angle bracket ('>') that
1533/// terminates the template-id.
1534///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001535/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001536/// substituting into.
1537///
1538/// \param Converted the list of template arguments provided for template
1539/// parameters that precede \p Param in the template parameter list.
1540///
1541/// \returns the substituted template argument, or NULL if an error occurred.
1542static Sema::OwningExprResult
1543SubstDefaultTemplateArgument(Sema &SemaRef,
1544 TemplateDecl *Template,
1545 SourceLocation TemplateLoc,
1546 SourceLocation RAngleLoc,
1547 NonTypeTemplateParmDecl *Param,
1548 TemplateArgumentListBuilder &Converted) {
1549 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1550 /*TakeArgs=*/false);
1551
1552 MultiLevelTemplateArgumentList AllTemplateArgs
1553 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1554
1555 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1556 Template, Converted.getFlatArguments(),
1557 Converted.flatSize(),
1558 SourceRange(TemplateLoc, RAngleLoc));
1559
1560 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1561}
1562
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001563/// \brief Substitute template arguments into the default template argument for
1564/// the given template template parameter.
1565///
1566/// \param SemaRef the semantic analysis object for which we are performing
1567/// the substitution.
1568///
1569/// \param Template the template that we are synthesizing template arguments
1570/// for.
1571///
1572/// \param TemplateLoc the location of the template name that started the
1573/// template-id we are checking.
1574///
1575/// \param RAngleLoc the location of the right angle bracket ('>') that
1576/// terminates the template-id.
1577///
1578/// \param Param the template template parameter whose default we are
1579/// substituting into.
1580///
1581/// \param Converted the list of template arguments provided for template
1582/// parameters that precede \p Param in the template parameter list.
1583///
1584/// \returns the substituted template argument, or NULL if an error occurred.
1585static TemplateName
1586SubstDefaultTemplateArgument(Sema &SemaRef,
1587 TemplateDecl *Template,
1588 SourceLocation TemplateLoc,
1589 SourceLocation RAngleLoc,
1590 TemplateTemplateParmDecl *Param,
1591 TemplateArgumentListBuilder &Converted) {
1592 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1593 /*TakeArgs=*/false);
1594
1595 MultiLevelTemplateArgumentList AllTemplateArgs
1596 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1597
1598 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1599 Template, Converted.getFlatArguments(),
1600 Converted.flatSize(),
1601 SourceRange(TemplateLoc, RAngleLoc));
1602
1603 return SemaRef.SubstTemplateName(
1604 Param->getDefaultArgument().getArgument().getAsTemplate(),
1605 Param->getDefaultArgument().getTemplateNameLoc(),
1606 AllTemplateArgs);
1607}
1608
Douglas Gregorda0fb532009-11-11 19:31:23 +00001609/// \brief Check that the given template argument corresponds to the given
1610/// template parameter.
1611bool Sema::CheckTemplateArgument(NamedDecl *Param,
1612 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001613 TemplateDecl *Template,
1614 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001615 SourceLocation RAngleLoc,
1616 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001617 // Check template type parameters.
1618 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001619 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001620
Douglas Gregoreebed722009-11-11 19:41:09 +00001621 // Check non-type template parameters.
1622 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001623 // Do substitution on the type of the non-type template parameter
1624 // with the template arguments we've seen thus far.
1625 QualType NTTPType = NTTP->getType();
1626 if (NTTPType->isDependentType()) {
1627 // Do substitution on the type of the non-type template parameter.
1628 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1629 NTTP, Converted.getFlatArguments(),
1630 Converted.flatSize(),
1631 SourceRange(TemplateLoc, RAngleLoc));
1632
1633 TemplateArgumentList TemplateArgs(Context, Converted,
1634 /*TakeArgs=*/false);
1635 NTTPType = SubstType(NTTPType,
1636 MultiLevelTemplateArgumentList(TemplateArgs),
1637 NTTP->getLocation(),
1638 NTTP->getDeclName());
1639 // If that worked, check the non-type template parameter type
1640 // for validity.
1641 if (!NTTPType.isNull())
1642 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1643 NTTP->getLocation());
1644 if (NTTPType.isNull())
1645 return true;
1646 }
1647
1648 switch (Arg.getArgument().getKind()) {
1649 case TemplateArgument::Null:
1650 assert(false && "Should never see a NULL template argument here");
1651 return true;
1652
1653 case TemplateArgument::Expression: {
1654 Expr *E = Arg.getArgument().getAsExpr();
1655 TemplateArgument Result;
1656 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1657 return true;
1658
1659 Converted.Append(Result);
1660 break;
1661 }
1662
1663 case TemplateArgument::Declaration:
1664 case TemplateArgument::Integral:
1665 // We've already checked this template argument, so just copy
1666 // it to the list of converted arguments.
1667 Converted.Append(Arg.getArgument());
1668 break;
1669
1670 case TemplateArgument::Template:
1671 // We were given a template template argument. It may not be ill-formed;
1672 // see below.
1673 if (DependentTemplateName *DTN
1674 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1675 // We have a template argument such as \c T::template X, which we
1676 // parsed as a template template argument. However, since we now
1677 // know that we need a non-type template argument, convert this
1678 // template name into an expression.
1679 Expr *E = new (Context) UnresolvedDeclRefExpr(DTN->getIdentifier(),
1680 Context.DependentTy,
1681 Arg.getTemplateNameLoc(),
1682 Arg.getTemplateQualifierRange(),
1683 DTN->getQualifier(),
1684 /*isAddressOfOperand=*/false);
1685
1686 TemplateArgument Result;
1687 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1688 return true;
1689
1690 Converted.Append(Result);
1691 break;
1692 }
1693
1694 // We have a template argument that actually does refer to a class
1695 // template, template alias, or template template parameter, and
1696 // therefore cannot be a non-type template argument.
1697 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1698 << Arg.getSourceRange();
1699
1700 Diag(Param->getLocation(), diag::note_template_param_here);
1701 return true;
1702
1703 case TemplateArgument::Type: {
1704 // We have a non-type template parameter but the template
1705 // argument is a type.
1706
1707 // C++ [temp.arg]p2:
1708 // In a template-argument, an ambiguity between a type-id and
1709 // an expression is resolved to a type-id, regardless of the
1710 // form of the corresponding template-parameter.
1711 //
1712 // We warn specifically about this case, since it can be rather
1713 // confusing for users.
1714 QualType T = Arg.getArgument().getAsType();
1715 SourceRange SR = Arg.getSourceRange();
1716 if (T->isFunctionType())
1717 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1718 else
1719 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1720 Diag(Param->getLocation(), diag::note_template_param_here);
1721 return true;
1722 }
1723
1724 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00001725 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001726 break;
1727 }
1728
1729 return false;
1730 }
1731
1732
1733 // Check template template parameters.
1734 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1735
1736 // Substitute into the template parameter list of the template
1737 // template parameter, since previously-supplied template arguments
1738 // may appear within the template template parameter.
1739 {
1740 // Set up a template instantiation context.
1741 LocalInstantiationScope Scope(*this);
1742 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1743 TempParm, Converted.getFlatArguments(),
1744 Converted.flatSize(),
1745 SourceRange(TemplateLoc, RAngleLoc));
1746
1747 TemplateArgumentList TemplateArgs(Context, Converted,
1748 /*TakeArgs=*/false);
1749 TempParm = cast_or_null<TemplateTemplateParmDecl>(
1750 SubstDecl(TempParm, CurContext,
1751 MultiLevelTemplateArgumentList(TemplateArgs)));
1752 if (!TempParm)
1753 return true;
1754
1755 // FIXME: TempParam is leaked.
1756 }
1757
1758 switch (Arg.getArgument().getKind()) {
1759 case TemplateArgument::Null:
1760 assert(false && "Should never see a NULL template argument here");
1761 return true;
1762
1763 case TemplateArgument::Template:
1764 if (CheckTemplateArgument(TempParm, Arg))
1765 return true;
1766
1767 Converted.Append(Arg.getArgument());
1768 break;
1769
1770 case TemplateArgument::Expression:
1771 case TemplateArgument::Type:
1772 // We have a template template parameter but the template
1773 // argument does not refer to a template.
1774 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1775 return true;
1776
1777 case TemplateArgument::Declaration:
1778 llvm::llvm_unreachable(
1779 "Declaration argument with template template parameter");
1780 break;
1781 case TemplateArgument::Integral:
1782 llvm::llvm_unreachable(
1783 "Integral argument with template template parameter");
1784 break;
1785
1786 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00001787 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001788 break;
1789 }
1790
1791 return false;
1792}
1793
Douglas Gregord32e0282009-02-09 23:23:08 +00001794/// \brief Check that the given template argument list is well-formed
1795/// for specializing the given template.
1796bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1797 SourceLocation TemplateLoc,
1798 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001799 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001800 unsigned NumTemplateArgs,
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001801 SourceLocation RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001802 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001803 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001804 TemplateParameterList *Params = Template->getTemplateParameters();
1805 unsigned NumParams = Params->size();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001806 unsigned NumArgs = NumTemplateArgs;
Douglas Gregord32e0282009-02-09 23:23:08 +00001807 bool Invalid = false;
1808
Mike Stump11289f42009-09-09 15:08:12 +00001809 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001810 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001811
Anders Carlsson15201f12009-06-13 02:08:00 +00001812 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001813 (NumArgs < Params->getMinRequiredArguments() &&
1814 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001815 // FIXME: point at either the first arg beyond what we can handle,
1816 // or the '>', depending on whether we have too many or too few
1817 // arguments.
1818 SourceRange Range;
1819 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001820 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001821 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1822 << (NumArgs > NumParams)
1823 << (isa<ClassTemplateDecl>(Template)? 0 :
1824 isa<FunctionTemplateDecl>(Template)? 1 :
1825 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1826 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001827 Diag(Template->getLocation(), diag::note_template_decl_here)
1828 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001829 Invalid = true;
1830 }
Mike Stump11289f42009-09-09 15:08:12 +00001831
1832 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001833 // [...] The type and form of each template-argument specified in
1834 // a template-id shall match the type and form specified for the
1835 // corresponding parameter declared by the template in its
1836 // template-parameter-list.
1837 unsigned ArgIdx = 0;
1838 for (TemplateParameterList::iterator Param = Params->begin(),
1839 ParamEnd = Params->end();
1840 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001841 if (ArgIdx > NumArgs && PartialTemplateArgs)
1842 break;
Mike Stump11289f42009-09-09 15:08:12 +00001843
Douglas Gregoreebed722009-11-11 19:41:09 +00001844 // If we have a template parameter pack, check every remaining template
1845 // argument against that template parameter pack.
1846 if ((*Param)->isTemplateParameterPack()) {
1847 Converted.BeginPack();
1848 for (; ArgIdx < NumArgs; ++ArgIdx) {
1849 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
1850 TemplateLoc, RAngleLoc, Converted)) {
1851 Invalid = true;
1852 break;
1853 }
1854 }
1855 Converted.EndPack();
1856 continue;
1857 }
1858
Douglas Gregord32e0282009-02-09 23:23:08 +00001859 // Decode the template argument
John McCall0ad16662009-10-29 08:12:44 +00001860 TemplateArgumentLoc Arg;
1861
Douglas Gregord32e0282009-02-09 23:23:08 +00001862 if (ArgIdx >= NumArgs) {
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001863 // Retrieve the default template argument from the template
1864 // parameter.
1865 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001866 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001867 // We have an empty argument pack.
1868 Converted.BeginPack();
1869 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001870 break;
1871 }
Mike Stump11289f42009-09-09 15:08:12 +00001872
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001873 if (!TTP->hasDefaultArgument())
1874 break;
1875
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001876 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
1877 Template,
1878 TemplateLoc,
1879 RAngleLoc,
1880 TTP,
1881 Converted);
John McCall0ad16662009-10-29 08:12:44 +00001882 if (!ArgType)
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001883 return true;
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001884
1885 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
1886 ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001887 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001888 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1889 if (!NTTP->hasDefaultArgument())
1890 break;
1891
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001892 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
1893 TemplateLoc,
1894 RAngleLoc,
1895 NTTP,
1896 Converted);
Anders Carlsson40ed3442009-06-11 16:06:49 +00001897 if (E.isInvalid())
1898 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001899
John McCall0ad16662009-10-29 08:12:44 +00001900 Expr *Ex = E.takeAs<Expr>();
1901 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001902 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001903 TemplateTemplateParmDecl *TempParm
1904 = cast<TemplateTemplateParmDecl>(*Param);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001905
1906 if (!TempParm->hasDefaultArgument())
1907 break;
1908
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001909 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
1910 TemplateLoc,
1911 RAngleLoc,
1912 TempParm,
1913 Converted);
1914 if (Name.isNull())
1915 return true;
1916
1917 Arg = TemplateArgumentLoc(TemplateArgument(Name),
1918 TempParm->getDefaultArgument().getTemplateQualifierRange(),
1919 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001920 }
1921 } else {
1922 // Retrieve the template argument produced by the user.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001923 Arg = TemplateArgs[ArgIdx];
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001924 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00001925
Douglas Gregoreebed722009-11-11 19:41:09 +00001926 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001927 RAngleLoc, Converted))
1928 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00001929 }
1930
1931 return Invalid;
1932}
1933
1934/// \brief Check a template argument against its corresponding
1935/// template type parameter.
1936///
1937/// This routine implements the semantics of C++ [temp.arg.type]. It
1938/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001939bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001940 DeclaratorInfo *ArgInfo) {
1941 assert(ArgInfo && "invalid DeclaratorInfo");
1942 QualType Arg = ArgInfo->getType();
1943
Douglas Gregord32e0282009-02-09 23:23:08 +00001944 // C++ [temp.arg.type]p2:
1945 // A local type, a type with no linkage, an unnamed type or a type
1946 // compounded from any of these types shall not be used as a
1947 // template-argument for a template type-parameter.
1948 //
1949 // FIXME: Perform the recursive and no-linkage type checks.
1950 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001951 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001952 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001953 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001954 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00001955 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
1956 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1957 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
1958 << QualType(Tag, 0) << SR;
1959 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001960 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00001961 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1962 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00001963 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1964 return true;
1965 }
1966
1967 return false;
1968}
1969
Douglas Gregorccb07762009-02-11 19:52:55 +00001970/// \brief Checks whether the given template argument is the address
1971/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001972bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1973 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001974 bool Invalid = false;
1975
1976 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00001977 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00001978 Arg = Cast->getSubExpr();
1979
Sebastian Redl576fd422009-05-10 18:38:11 +00001980 // C++0x allows nullptr, and there's no further checking to be done for that.
1981 if (Arg->getType()->isNullPtrType())
1982 return false;
1983
Douglas Gregorccb07762009-02-11 19:52:55 +00001984 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001985 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001986 // A template-argument for a non-type, non-template
1987 // template-parameter shall be one of: [...]
1988 //
1989 // -- the address of an object or function with external
1990 // linkage, including function templates and function
1991 // template-ids but excluding non-static class members,
1992 // expressed as & id-expression where the & is optional if
1993 // the name refers to a function or array, or if the
1994 // corresponding template-parameter is a reference; or
1995 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001996
Douglas Gregorccb07762009-02-11 19:52:55 +00001997 // Ignore (and complain about) any excess parentheses.
1998 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1999 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002000 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002001 diag::err_template_arg_extra_parens)
2002 << Arg->getSourceRange();
2003 Invalid = true;
2004 }
2005
2006 Arg = Parens->getSubExpr();
2007 }
2008
2009 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2010 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2011 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2012 } else
2013 DRE = dyn_cast<DeclRefExpr>(Arg);
2014
2015 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002016 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002017 diag::err_template_arg_not_object_or_func_form)
2018 << Arg->getSourceRange();
2019
2020 // Cannot refer to non-static data members
2021 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2022 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2023 << Field << Arg->getSourceRange();
2024
2025 // Cannot refer to non-static member functions
2026 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2027 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002028 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002029 diag::err_template_arg_method)
2030 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002031
Douglas Gregorccb07762009-02-11 19:52:55 +00002032 // Functions must have external linkage.
2033 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2034 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00002035 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002036 diag::err_template_arg_function_not_extern)
2037 << Func << Arg->getSourceRange();
2038 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2039 << true;
2040 return true;
2041 }
2042
2043 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002044 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002045 return Invalid;
2046 }
2047
2048 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2049 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00002050 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002051 diag::err_template_arg_object_not_extern)
2052 << Var << Arg->getSourceRange();
2053 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2054 << true;
2055 return true;
2056 }
2057
2058 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002059 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002060 return Invalid;
2061 }
Mike Stump11289f42009-09-09 15:08:12 +00002062
Douglas Gregorccb07762009-02-11 19:52:55 +00002063 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002064 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002065 diag::err_template_arg_not_object_or_func)
2066 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002067 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002068 diag::note_template_arg_refers_here);
2069 return true;
2070}
2071
2072/// \brief Checks whether the given template argument is a pointer to
2073/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump11289f42009-09-09 15:08:12 +00002074bool
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002075Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002076 bool Invalid = false;
2077
2078 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002079 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002080 Arg = Cast->getSubExpr();
2081
Sebastian Redl576fd422009-05-10 18:38:11 +00002082 // C++0x allows nullptr, and there's no further checking to be done for that.
2083 if (Arg->getType()->isNullPtrType())
2084 return false;
2085
Douglas Gregorccb07762009-02-11 19:52:55 +00002086 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002087 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002088 // A template-argument for a non-type, non-template
2089 // template-parameter shall be one of: [...]
2090 //
2091 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002092 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002093
2094 // Ignore (and complain about) any excess parentheses.
2095 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2096 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002097 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002098 diag::err_template_arg_extra_parens)
2099 << Arg->getSourceRange();
2100 Invalid = true;
2101 }
2102
2103 Arg = Parens->getSubExpr();
2104 }
2105
2106 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002107 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2108 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2109 if (DRE && !DRE->getQualifier())
2110 DRE = 0;
2111 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002112
2113 if (!DRE)
2114 return Diag(Arg->getSourceRange().getBegin(),
2115 diag::err_template_arg_not_pointer_to_member_form)
2116 << Arg->getSourceRange();
2117
2118 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2119 assert((isa<FieldDecl>(DRE->getDecl()) ||
2120 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2121 "Only non-static member pointers can make it here");
2122
2123 // Okay: this is the address of a non-static member, and therefore
2124 // a member pointer constant.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002125 Member = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00002126 return Invalid;
2127 }
2128
2129 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002130 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002131 diag::err_template_arg_not_pointer_to_member_form)
2132 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002133 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002134 diag::note_template_arg_refers_here);
2135 return true;
2136}
2137
Douglas Gregord32e0282009-02-09 23:23:08 +00002138/// \brief Check a template argument against its corresponding
2139/// non-type template parameter.
2140///
Douglas Gregor463421d2009-03-03 04:44:36 +00002141/// This routine implements the semantics of C++ [temp.arg.nontype].
2142/// It returns true if an error occurred, and false otherwise. \p
2143/// InstantiatedParamType is the type of the non-type template
2144/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002145///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002146/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002147bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002148 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002149 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002150 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2151
Douglas Gregor86560402009-02-10 23:36:10 +00002152 // If either the parameter has a dependent type or the argument is
2153 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002154 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002155 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2156 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002157 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002158 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002159 }
Douglas Gregor86560402009-02-10 23:36:10 +00002160
2161 // C++ [temp.arg.nontype]p5:
2162 // The following conversions are performed on each expression used
2163 // as a non-type template-argument. If a non-type
2164 // template-argument cannot be converted to the type of the
2165 // corresponding template-parameter then the program is
2166 // ill-formed.
2167 //
2168 // -- for a non-type template-parameter of integral or
2169 // enumeration type, integral promotions (4.5) and integral
2170 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002171 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002172 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002173 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002174 // C++ [temp.arg.nontype]p1:
2175 // A template-argument for a non-type, non-template
2176 // template-parameter shall be one of:
2177 //
2178 // -- an integral constant-expression of integral or enumeration
2179 // type; or
2180 // -- the name of a non-type template-parameter; or
2181 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002182 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002183 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002184 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002185 diag::err_template_arg_not_integral_or_enumeral)
2186 << ArgType << Arg->getSourceRange();
2187 Diag(Param->getLocation(), diag::note_template_param_here);
2188 return true;
2189 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002190 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002191 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2192 << ArgType << Arg->getSourceRange();
2193 return true;
2194 }
2195
2196 // FIXME: We need some way to more easily get the unqualified form
2197 // of the types without going all the way to the
2198 // canonical type.
2199 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2200 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2201 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2202 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2203
2204 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002205 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002206 // Okay: no conversion necessary
2207 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2208 !ParamType->isEnumeralType()) {
2209 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002210 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002211 } else {
2212 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002213 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002214 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002215 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002216 Diag(Param->getLocation(), diag::note_template_param_here);
2217 return true;
2218 }
2219
Douglas Gregor52aba872009-03-14 00:20:21 +00002220 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002221 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002222 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002223
2224 if (!Arg->isValueDependent()) {
2225 // Check that an unsigned parameter does not receive a negative
2226 // value.
2227 if (IntegerType->isUnsignedIntegerType()
2228 && (Value.isSigned() && Value.isNegative())) {
2229 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2230 << Value.toString(10) << Param->getType()
2231 << Arg->getSourceRange();
2232 Diag(Param->getLocation(), diag::note_template_param_here);
2233 return true;
2234 }
2235
2236 // Check that we don't overflow the template parameter type.
2237 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2238 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002239 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002240 diag::err_template_arg_too_large)
2241 << Value.toString(10) << Param->getType()
2242 << Arg->getSourceRange();
2243 Diag(Param->getLocation(), diag::note_template_param_here);
2244 return true;
2245 }
2246
2247 if (Value.getBitWidth() != AllowedBits)
2248 Value.extOrTrunc(AllowedBits);
2249 Value.setIsSigned(IntegerType->isSignedIntegerType());
2250 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002251
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002252 // Add the value of this argument to the list of converted
2253 // arguments. We use the bitwidth and signedness of the template
2254 // parameter.
2255 if (Arg->isValueDependent()) {
2256 // The argument is value-dependent. Create a new
2257 // TemplateArgument with the converted expression.
2258 Converted = TemplateArgument(Arg);
2259 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002260 }
2261
John McCall0ad16662009-10-29 08:12:44 +00002262 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002263 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002264 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002265 return false;
2266 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002267
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002268 // Handle pointer-to-function, reference-to-function, and
2269 // pointer-to-member-function all in (roughly) the same way.
2270 if (// -- For a non-type template-parameter of type pointer to
2271 // function, only the function-to-pointer conversion (4.3) is
2272 // applied. If the template-argument represents a set of
2273 // overloaded functions (or a pointer to such), the matching
2274 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002275 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002276 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002277 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002278 // -- For a non-type template-parameter of type reference to
2279 // function, no conversions apply. If the template-argument
2280 // represents a set of overloaded functions, the matching
2281 // function is selected from the set (13.4).
2282 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002283 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002284 // -- For a non-type template-parameter of type pointer to
2285 // member function, no conversions apply. If the
2286 // template-argument represents a set of overloaded member
2287 // functions, the matching member function is selected from
2288 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002289 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002290 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002291 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002292 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002293 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002294 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002295 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002296 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2297 ParamType->isMemberPointerType())) {
2298 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002299 if (ParamType->isMemberPointerType())
2300 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2301 else
2302 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002303 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002304 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002305 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002306 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002307 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002308 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2309 return true;
2310
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002311 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002312 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002313 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002314 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002315 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002316 }
2317 }
2318
Mike Stump11289f42009-09-09 15:08:12 +00002319 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002320 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002321 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002322 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002323 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002324 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002325 Diag(Param->getLocation(), diag::note_template_param_here);
2326 return true;
2327 }
Mike Stump11289f42009-09-09 15:08:12 +00002328
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002329 if (ParamType->isMemberPointerType()) {
2330 NamedDecl *Member = 0;
2331 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2332 return true;
2333
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002334 if (Member)
2335 Member = cast<NamedDecl>(Member->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002336 Converted = TemplateArgument(Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002337 return false;
2338 }
Mike Stump11289f42009-09-09 15:08:12 +00002339
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002340 NamedDecl *Entity = 0;
2341 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2342 return true;
2343
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002344 if (Entity)
2345 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002346 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002347 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002348 }
2349
Chris Lattner696197c2009-02-20 21:37:53 +00002350 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002351 // -- for a non-type template-parameter of type pointer to
2352 // object, qualification conversions (4.4) and the
2353 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002354 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002355 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002356 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002357
Sebastian Redl576fd422009-05-10 18:38:11 +00002358 if (ArgType->isNullPtrType()) {
2359 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002360 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002361 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002362 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002363 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002364 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002365
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002366 if (IsQualificationConversion(ArgType, ParamType)) {
2367 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002368 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002369 }
Mike Stump11289f42009-09-09 15:08:12 +00002370
Douglas Gregor1515f762009-02-11 18:22:40 +00002371 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002372 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002373 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002374 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002375 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002376 Diag(Param->getLocation(), diag::note_template_param_here);
2377 return true;
2378 }
Mike Stump11289f42009-09-09 15:08:12 +00002379
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002380 NamedDecl *Entity = 0;
2381 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2382 return true;
2383
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002384 if (Entity)
2385 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002386 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002387 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002388 }
Mike Stump11289f42009-09-09 15:08:12 +00002389
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002390 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002391 // -- For a non-type template-parameter of type reference to
2392 // object, no conversions apply. The type referred to by the
2393 // reference may be more cv-qualified than the (otherwise
2394 // identical) type of the template-argument. The
2395 // template-parameter is bound directly to the
2396 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002397 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002398 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002399
Douglas Gregor1515f762009-02-11 18:22:40 +00002400 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002401 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002402 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002403 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002404 << Arg->getSourceRange();
2405 Diag(Param->getLocation(), diag::note_template_param_here);
2406 return true;
2407 }
2408
Mike Stump11289f42009-09-09 15:08:12 +00002409 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002410 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2411 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002412
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002413 if ((ParamQuals | ArgQuals) != ParamQuals) {
2414 Diag(Arg->getSourceRange().getBegin(),
2415 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002416 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002417 << Arg->getSourceRange();
2418 Diag(Param->getLocation(), diag::note_template_param_here);
2419 return true;
2420 }
Mike Stump11289f42009-09-09 15:08:12 +00002421
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002422 NamedDecl *Entity = 0;
2423 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2424 return true;
2425
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002426 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002427 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002428 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002429 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002430
2431 // -- For a non-type template-parameter of type pointer to data
2432 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002433 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002434 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2435
Douglas Gregor1515f762009-02-11 18:22:40 +00002436 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002437 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002438 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002439 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002440 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002441 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002442 } else {
2443 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002444 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002445 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002446 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002447 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002448 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002449 }
2450
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002451 NamedDecl *Member = 0;
2452 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2453 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002454
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002455 if (Member)
2456 Member = cast<NamedDecl>(Member->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002457 Converted = TemplateArgument(Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002458 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00002459}
2460
2461/// \brief Check a template argument against its corresponding
2462/// template template parameter.
2463///
2464/// This routine implements the semantics of C++ [temp.arg.template].
2465/// It returns true if an error occurred, and false otherwise.
2466bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002467 const TemplateArgumentLoc &Arg) {
2468 TemplateName Name = Arg.getArgument().getAsTemplate();
2469 TemplateDecl *Template = Name.getAsTemplateDecl();
2470 if (!Template) {
2471 // Any dependent template name is fine.
2472 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2473 return false;
2474 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002475
2476 // C++ [temp.arg.template]p1:
2477 // A template-argument for a template template-parameter shall be
2478 // the name of a class template, expressed as id-expression. Only
2479 // primary class templates are considered when matching the
2480 // template template argument with the corresponding parameter;
2481 // partial specializations are not considered even if their
2482 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002483 //
2484 // Note that we also allow template template parameters here, which
2485 // will happen when we are dealing with, e.g., class template
2486 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002487 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002488 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002489 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002490 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002491 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002492 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002493 << Template;
2494 }
2495
2496 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2497 Param->getTemplateParameters(),
2498 true, true,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002499 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002500}
2501
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002502/// \brief Determine whether the given template parameter lists are
2503/// equivalent.
2504///
Mike Stump11289f42009-09-09 15:08:12 +00002505/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002506/// source code as part of a new template declaration.
2507///
2508/// \param Old The old template parameter list, typically found via
2509/// name lookup of the template declared with this template parameter
2510/// list.
2511///
2512/// \param Complain If true, this routine will produce a diagnostic if
2513/// the template parameter lists are not equivalent.
2514///
Douglas Gregor85e0f662009-02-10 00:24:35 +00002515/// \param IsTemplateTemplateParm If true, this routine is being
2516/// called to compare the template parameter lists of a template
2517/// template parameter.
2518///
2519/// \param TemplateArgLoc If this source location is valid, then we
2520/// are actually checking the template parameter list of a template
2521/// argument (New) against the template parameter list of its
2522/// corresponding template template parameter (Old). We produce
2523/// slightly different diagnostics in this scenario.
2524///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002525/// \returns True if the template parameter lists are equal, false
2526/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002527bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002528Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2529 TemplateParameterList *Old,
2530 bool Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002531 bool IsTemplateTemplateParm,
2532 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002533 if (Old->size() != New->size()) {
2534 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002535 unsigned NextDiag = diag::err_template_param_list_different_arity;
2536 if (TemplateArgLoc.isValid()) {
2537 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2538 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002539 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002540 Diag(New->getTemplateLoc(), NextDiag)
2541 << (New->size() > Old->size())
2542 << IsTemplateTemplateParm
2543 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002544 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2545 << IsTemplateTemplateParm
2546 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2547 }
2548
2549 return false;
2550 }
2551
2552 for (TemplateParameterList::iterator OldParm = Old->begin(),
2553 OldParmEnd = Old->end(), NewParm = New->begin();
2554 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2555 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002556 if (Complain) {
2557 unsigned NextDiag = diag::err_template_param_different_kind;
2558 if (TemplateArgLoc.isValid()) {
2559 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2560 NextDiag = diag::note_template_param_different_kind;
2561 }
2562 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregore62e6a02009-11-11 19:13:48 +00002563 << IsTemplateTemplateParm;
Douglas Gregor23061de2009-06-24 16:50:40 +00002564 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregore62e6a02009-11-11 19:13:48 +00002565 << IsTemplateTemplateParm;
Douglas Gregor85e0f662009-02-10 00:24:35 +00002566 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002567 return false;
2568 }
2569
2570 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2571 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002572 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002573 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002574 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2575 // The types of non-type template parameters must agree.
2576 NonTypeTemplateParmDecl *NewNTTP
2577 = cast<NonTypeTemplateParmDecl>(*NewParm);
2578 if (Context.getCanonicalType(OldNTTP->getType()) !=
2579 Context.getCanonicalType(NewNTTP->getType())) {
2580 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002581 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2582 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002583 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002584 diag::err_template_arg_template_params_mismatch);
2585 NextDiag = diag::note_template_nontype_parm_different_type;
2586 }
2587 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002588 << NewNTTP->getType()
2589 << IsTemplateTemplateParm;
Mike Stump11289f42009-09-09 15:08:12 +00002590 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002591 diag::note_template_nontype_parm_prev_declaration)
2592 << OldNTTP->getType();
2593 }
2594 return false;
2595 }
Douglas Gregore62e6a02009-11-11 19:13:48 +00002596 assert(OldNTTP->getDepth() == NewNTTP->getDepth() &&
2597 "Non-type template parameter depth mismatch");
2598 assert(OldNTTP->getPosition() == NewNTTP->getPosition() &&
2599 "Non-type template parameter position mismatch");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002600 } else {
2601 // The template parameter lists of template template
2602 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002603 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002604 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002605 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002606 = cast<TemplateTemplateParmDecl>(*OldParm);
2607 TemplateTemplateParmDecl *NewTTP
2608 = cast<TemplateTemplateParmDecl>(*NewParm);
2609 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2610 OldTTP->getTemplateParameters(),
2611 Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002612 /*IsTemplateTemplateParm=*/true,
2613 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002614 return false;
Douglas Gregore62e6a02009-11-11 19:13:48 +00002615
2616 assert(OldTTP->getDepth() == NewTTP->getDepth() &&
2617 "Template template parameter depth mismatch");
2618 assert(OldTTP->getPosition() == NewTTP->getPosition() &&
2619 "Template template parameter position mismatch");
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002620 }
2621 }
2622
2623 return true;
2624}
2625
2626/// \brief Check whether a template can be declared within this scope.
2627///
2628/// If the template declaration is valid in this scope, returns
2629/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002630bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002631Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002632 // Find the nearest enclosing declaration scope.
2633 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2634 (S->getFlags() & Scope::TemplateParamScope) != 0)
2635 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002636
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002637 // C++ [temp]p2:
2638 // A template-declaration can appear only as a namespace scope or
2639 // class scope declaration.
2640 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002641 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2642 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002643 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002644 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002645
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002646 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002647 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002648
2649 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2650 return false;
2651
Mike Stump11289f42009-09-09 15:08:12 +00002652 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002653 diag::err_template_outside_namespace_or_class_scope)
2654 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002655}
Douglas Gregor67a65642009-02-17 23:15:12 +00002656
Douglas Gregor54888652009-10-07 00:13:32 +00002657/// \brief Determine what kind of template specialization the given declaration
2658/// is.
2659static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2660 if (!D)
2661 return TSK_Undeclared;
2662
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002663 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2664 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002665 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2666 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002667 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2668 return Var->getTemplateSpecializationKind();
2669
Douglas Gregor54888652009-10-07 00:13:32 +00002670 return TSK_Undeclared;
2671}
2672
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002673/// \brief Check whether a specialization is well-formed in the current
2674/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002675///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002676/// This routine determines whether a template specialization can be declared
2677/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002678///
2679/// \param S the semantic analysis object for which this check is being
2680/// performed.
2681///
2682/// \param Specialized the entity being specialized or instantiated, which
2683/// may be a kind of template (class template, function template, etc.) or
2684/// a member of a class template (member function, static data member,
2685/// member class).
2686///
2687/// \param PrevDecl the previous declaration of this entity, if any.
2688///
2689/// \param Loc the location of the explicit specialization or instantiation of
2690/// this entity.
2691///
2692/// \param IsPartialSpecialization whether this is a partial specialization of
2693/// a class template.
2694///
Douglas Gregor54888652009-10-07 00:13:32 +00002695/// \returns true if there was an error that we cannot recover from, false
2696/// otherwise.
2697static bool CheckTemplateSpecializationScope(Sema &S,
2698 NamedDecl *Specialized,
2699 NamedDecl *PrevDecl,
2700 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002701 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002702 // Keep these "kind" numbers in sync with the %select statements in the
2703 // various diagnostics emitted by this routine.
2704 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002705 bool isTemplateSpecialization = false;
2706 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002707 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002708 isTemplateSpecialization = true;
2709 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002710 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002711 isTemplateSpecialization = true;
2712 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002713 EntityKind = 3;
2714 else if (isa<VarDecl>(Specialized))
2715 EntityKind = 4;
2716 else if (isa<RecordDecl>(Specialized))
2717 EntityKind = 5;
2718 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002719 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2720 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00002721 return true;
2722 }
2723
Douglas Gregorf47b9112009-02-25 22:02:03 +00002724 // C++ [temp.expl.spec]p2:
2725 // An explicit specialization shall be declared in the namespace
2726 // of which the template is a member, or, for member templates, in
2727 // the namespace of which the enclosing class or enclosing class
2728 // template is a member. An explicit specialization of a member
2729 // function, member class or static data member of a class
2730 // template shall be declared in the namespace of which the class
2731 // template is a member. Such a declaration may also be a
2732 // definition. If the declaration is not a definition, the
2733 // specialization may be defined later in the name- space in which
2734 // the explicit specialization was declared, or in a namespace
2735 // that encloses the one in which the explicit specialization was
2736 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002737 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2738 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002739 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002740 return true;
2741 }
Douglas Gregore4b05162009-10-07 17:21:34 +00002742
Douglas Gregor40fb7442009-10-07 17:30:37 +00002743 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2744 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002745 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00002746 return true;
2747 }
2748
Douglas Gregore4b05162009-10-07 17:21:34 +00002749 // C++ [temp.class.spec]p6:
2750 // A class template partial specialization may be declared or redeclared
2751 // in any namespace scope in which its definition may be defined (14.5.1
2752 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002753 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002754 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002755 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002756 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002757 if ((!PrevDecl ||
2758 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2759 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2760 // There is no prior declaration of this entity, so this
2761 // specialization must be in the same context as the template
2762 // itself.
2763 if (!DC->Equals(SpecializedContext)) {
2764 if (isa<TranslationUnitDecl>(SpecializedContext))
2765 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2766 << EntityKind << Specialized;
2767 else if (isa<NamespaceDecl>(SpecializedContext))
2768 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2769 << EntityKind << Specialized
2770 << cast<NamedDecl>(SpecializedContext);
2771
2772 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2773 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002774 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002775 }
Douglas Gregor54888652009-10-07 00:13:32 +00002776
2777 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002778 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00002779 // Note that HandleDeclarator() performs this check for explicit
2780 // specializations of function templates, static data members, and member
2781 // functions, so we skip the check here for those kinds of entities.
2782 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00002783 // Should we refactor that check, so that it occurs later?
2784 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002785 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2786 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00002787 if (isa<TranslationUnitDecl>(SpecializedContext))
2788 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2789 << EntityKind << Specialized;
2790 else if (isa<NamespaceDecl>(SpecializedContext))
2791 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2792 << EntityKind << Specialized
2793 << cast<NamedDecl>(SpecializedContext);
2794
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002795 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002796 }
Douglas Gregor54888652009-10-07 00:13:32 +00002797
2798 // FIXME: check for specialization-after-instantiation errors and such.
2799
Douglas Gregorf47b9112009-02-25 22:02:03 +00002800 return false;
2801}
Douglas Gregor54888652009-10-07 00:13:32 +00002802
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002803/// \brief Check the non-type template arguments of a class template
2804/// partial specialization according to C++ [temp.class.spec]p9.
2805///
Douglas Gregor09a30232009-06-12 22:08:06 +00002806/// \param TemplateParams the template parameters of the primary class
2807/// template.
2808///
2809/// \param TemplateArg the template arguments of the class template
2810/// partial specialization.
2811///
2812/// \param MirrorsPrimaryTemplate will be set true if the class
2813/// template partial specialization arguments are identical to the
2814/// implicit template arguments of the primary template. This is not
2815/// necessarily an error (C++0x), and it is left to the caller to diagnose
2816/// this condition when it is an error.
2817///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002818/// \returns true if there was an error, false otherwise.
2819bool Sema::CheckClassTemplatePartialSpecializationArgs(
2820 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002821 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002822 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002823 // FIXME: the interface to this function will have to change to
2824 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002825 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002826
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002827 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002828
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002829 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002830 // Determine whether the template argument list of the partial
2831 // specialization is identical to the implicit argument list of
2832 // the primary template. The caller may need to diagnostic this as
2833 // an error per C++ [temp.class.spec]p9b3.
2834 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002835 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002836 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2837 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002838 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002839 MirrorsPrimaryTemplate = false;
2840 } else if (TemplateTemplateParmDecl *TTP
2841 = dyn_cast<TemplateTemplateParmDecl>(
2842 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002843 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00002844 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002845 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002846 if (!ArgDecl ||
2847 ArgDecl->getIndex() != TTP->getIndex() ||
2848 ArgDecl->getDepth() != TTP->getDepth())
2849 MirrorsPrimaryTemplate = false;
2850 }
2851 }
2852
Mike Stump11289f42009-09-09 15:08:12 +00002853 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002854 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002855 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002856 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002857 }
2858
Anders Carlsson40c1d492009-06-13 18:20:51 +00002859 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002860 if (!ArgExpr) {
2861 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002862 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002863 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002864
2865 // C++ [temp.class.spec]p8:
2866 // A non-type argument is non-specialized if it is the name of a
2867 // non-type parameter. All other non-type arguments are
2868 // specialized.
2869 //
2870 // Below, we check the two conditions that only apply to
2871 // specialized non-type arguments, so skip any non-specialized
2872 // arguments.
2873 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002874 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002875 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002876 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002877 (Param->getIndex() != NTTP->getIndex() ||
2878 Param->getDepth() != NTTP->getDepth()))
2879 MirrorsPrimaryTemplate = false;
2880
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002881 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002882 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002883
2884 // C++ [temp.class.spec]p9:
2885 // Within the argument list of a class template partial
2886 // specialization, the following restrictions apply:
2887 // -- A partially specialized non-type argument expression
2888 // shall not involve a template parameter of the partial
2889 // specialization except when the argument expression is a
2890 // simple identifier.
2891 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002892 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002893 diag::err_dependent_non_type_arg_in_partial_spec)
2894 << ArgExpr->getSourceRange();
2895 return true;
2896 }
2897
2898 // -- The type of a template parameter corresponding to a
2899 // specialized non-type argument shall not be dependent on a
2900 // parameter of the specialization.
2901 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002902 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002903 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2904 << Param->getType()
2905 << ArgExpr->getSourceRange();
2906 Diag(Param->getLocation(), diag::note_template_param_here);
2907 return true;
2908 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002909
2910 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002911 }
2912
2913 return false;
2914}
2915
Douglas Gregorc08f4892009-03-25 00:13:59 +00002916Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002917Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2918 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002919 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002920 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002921 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002922 SourceLocation TemplateNameLoc,
2923 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002924 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002925 SourceLocation RAngleLoc,
2926 AttributeList *Attr,
2927 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00002928 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00002929
Douglas Gregor67a65642009-02-17 23:15:12 +00002930 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002931 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002932 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002933 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002934
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002935 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00002936 bool isPartialSpecialization = false;
2937
Douglas Gregorf47b9112009-02-25 22:02:03 +00002938 // Check the validity of the template headers that introduce this
2939 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00002940 // FIXME: We probably shouldn't complain about these headers for
2941 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002942 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002943 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2944 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002945 TemplateParameterLists.size(),
2946 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002947 if (TemplateParams && TemplateParams->size() > 0) {
2948 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002949
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002950 // C++ [temp.class.spec]p10:
2951 // The template parameter list of a specialization shall not
2952 // contain default template argument values.
2953 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2954 Decl *Param = TemplateParams->getParam(I);
2955 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2956 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002957 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002958 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00002959 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002960 }
2961 } else if (NonTypeTemplateParmDecl *NTTP
2962 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2963 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002964 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002965 diag::err_default_arg_in_partial_spec)
2966 << DefArg->getSourceRange();
2967 NTTP->setDefaultArgument(0);
2968 DefArg->Destroy(Context);
2969 }
2970 } else {
2971 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002972 if (TTP->hasDefaultArgument()) {
2973 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002974 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002975 << TTP->getDefaultArgument().getSourceRange();
2976 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00002977 }
2978 }
2979 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00002980 } else if (TemplateParams) {
2981 if (TUK == TUK_Friend)
2982 Diag(KWLoc, diag::err_template_spec_friend)
2983 << CodeModificationHint::CreateRemoval(
2984 SourceRange(TemplateParams->getTemplateLoc(),
2985 TemplateParams->getRAngleLoc()))
2986 << SourceRange(LAngleLoc, RAngleLoc);
2987 else
2988 isExplicitSpecialization = true;
2989 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002990 Diag(KWLoc, diag::err_template_spec_needs_header)
2991 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002992 isExplicitSpecialization = true;
2993 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002994
Douglas Gregor67a65642009-02-17 23:15:12 +00002995 // Check that the specialization uses the same tag kind as the
2996 // original template.
2997 TagDecl::TagKind Kind;
2998 switch (TagSpec) {
2999 default: assert(0 && "Unknown tag type!");
3000 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3001 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3002 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3003 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003004 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003005 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003006 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003007 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003008 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003009 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003010 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003011 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003012 diag::note_previous_use);
3013 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3014 }
3015
Douglas Gregorc40290e2009-03-09 23:48:35 +00003016 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00003017 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003018 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003019
Douglas Gregor67a65642009-02-17 23:15:12 +00003020 // Check that the template argument list is well-formed for this
3021 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003022 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3023 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003024 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003025 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003026 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003027 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003028
Mike Stump11289f42009-09-09 15:08:12 +00003029 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003030 ClassTemplate->getTemplateParameters()->size()) &&
3031 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003032
Douglas Gregor2373c592009-05-31 09:31:02 +00003033 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003034 // corresponds to these arguments.
3035 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003036 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003037 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003038 if (CheckClassTemplatePartialSpecializationArgs(
3039 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003040 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003041 return true;
3042
Douglas Gregor09a30232009-06-12 22:08:06 +00003043 if (MirrorsPrimaryTemplate) {
3044 // C++ [temp.class.spec]p9b3:
3045 //
Mike Stump11289f42009-09-09 15:08:12 +00003046 // -- The argument list of the specialization shall not be identical
3047 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003048 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003049 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003050 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003051 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003052 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003053 ClassTemplate->getIdentifier(),
3054 TemplateNameLoc,
3055 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003056 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003057 AS_none);
3058 }
3059
Douglas Gregor2208a292009-09-26 20:57:03 +00003060 // FIXME: Diagnose friend partial specializations
3061
Douglas Gregor2373c592009-05-31 09:31:02 +00003062 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00003063 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003064 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003065 Converted.flatSize(),
3066 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003067 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003068 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003069 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003070 Converted.flatSize(),
3071 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003072 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003073 ClassTemplateSpecializationDecl *PrevDecl = 0;
3074
3075 if (isPartialSpecialization)
3076 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003077 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003078 InsertPos);
3079 else
3080 PrevDecl
3081 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003082
3083 ClassTemplateSpecializationDecl *Specialization = 0;
3084
Douglas Gregorf47b9112009-02-25 22:02:03 +00003085 // Check whether we can declare a class template specialization in
3086 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003087 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003088 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003089 TemplateNameLoc,
3090 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003091 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003092
Douglas Gregor15301382009-07-30 17:40:51 +00003093 // The canonical type
3094 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003095 if (PrevDecl &&
3096 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3097 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003098 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003099 // arguments was referenced but not declared, or we're only
3100 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003101 // declaration node as our own, updating its source location to
3102 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003103 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003104 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003105 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003106 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003107 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003108 // Build the canonical type that describes the converted template
3109 // arguments of the class template partial specialization.
3110 CanonType = Context.getTemplateSpecializationType(
3111 TemplateName(ClassTemplate),
3112 Converted.getFlatArguments(),
3113 Converted.flatSize());
3114
Douglas Gregor2373c592009-05-31 09:31:02 +00003115 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003116 ClassTemplatePartialSpecializationDecl *PrevPartial
3117 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003118 ClassTemplatePartialSpecializationDecl *Partial
3119 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003120 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003121 TemplateNameLoc,
3122 TemplateParams,
3123 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003124 Converted,
John McCall0ad16662009-10-29 08:12:44 +00003125 TemplateArgs.data(),
3126 TemplateArgs.size(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003127 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003128
3129 if (PrevPartial) {
3130 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3131 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3132 } else {
3133 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3134 }
3135 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003136
Douglas Gregor21610382009-10-29 00:04:11 +00003137 // If we are providing an explicit specialization of a member class
3138 // template specialization, make a note of that.
3139 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3140 PrevPartial->setMemberSpecialization();
3141
Douglas Gregor91772d12009-06-13 00:26:55 +00003142 // Check that all of the template parameters of the class template
3143 // partial specialization are deducible from the template
3144 // arguments. If not, this class template partial specialization
3145 // will never be used.
3146 llvm::SmallVector<bool, 8> DeducibleParams;
3147 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003148 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003149 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003150 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003151 unsigned NumNonDeducible = 0;
3152 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3153 if (!DeducibleParams[I])
3154 ++NumNonDeducible;
3155
3156 if (NumNonDeducible) {
3157 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3158 << (NumNonDeducible > 1)
3159 << SourceRange(TemplateNameLoc, RAngleLoc);
3160 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3161 if (!DeducibleParams[I]) {
3162 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3163 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003164 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003165 diag::note_partial_spec_unused_parameter)
3166 << Param->getDeclName();
3167 else
Mike Stump11289f42009-09-09 15:08:12 +00003168 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003169 diag::note_partial_spec_unused_parameter)
3170 << std::string("<anonymous>");
3171 }
3172 }
3173 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003174 } else {
3175 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003176 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003177 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003178 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003179 ClassTemplate->getDeclContext(),
3180 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003181 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003182 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003183 PrevDecl);
3184
3185 if (PrevDecl) {
3186 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3187 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3188 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003189 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003190 InsertPos);
3191 }
Douglas Gregor15301382009-07-30 17:40:51 +00003192
3193 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003194 }
3195
Douglas Gregor06db9f52009-10-12 20:18:28 +00003196 // C++ [temp.expl.spec]p6:
3197 // If a template, a member template or the member of a class template is
3198 // explicitly specialized then that specialization shall be declared
3199 // before the first use of that specialization that would cause an implicit
3200 // instantiation to take place, in every translation unit in which such a
3201 // use occurs; no diagnostic is required.
3202 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3203 SourceRange Range(TemplateNameLoc, RAngleLoc);
3204 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3205 << Context.getTypeDeclType(Specialization) << Range;
3206
3207 Diag(PrevDecl->getPointOfInstantiation(),
3208 diag::note_instantiation_required_here)
3209 << (PrevDecl->getTemplateSpecializationKind()
3210 != TSK_ImplicitInstantiation);
3211 return true;
3212 }
3213
Douglas Gregor2208a292009-09-26 20:57:03 +00003214 // If this is not a friend, note that this is an explicit specialization.
3215 if (TUK != TUK_Friend)
3216 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003217
3218 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003219 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003220 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003221 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003222 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003223 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003224 Diag(Def->getLocation(), diag::note_previous_definition);
3225 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003226 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003227 }
3228 }
3229
Douglas Gregord56a91e2009-02-26 22:19:44 +00003230 // Build the fully-sugared type for this class template
3231 // specialization as the user wrote in the specialization
3232 // itself. This means that we'll pretty-print the type retrieved
3233 // from the specialization's declaration the way that the user
3234 // actually wrote the specialization, rather than formatting the
3235 // name based on the "canonical" representation used to store the
3236 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003237 QualType WrittenTy
3238 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003239 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00003240 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00003241 CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003242 if (TUK != TUK_Friend)
3243 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003244 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003245
Douglas Gregor1e249f82009-02-25 22:18:32 +00003246 // C++ [temp.expl.spec]p9:
3247 // A template explicit specialization is in the scope of the
3248 // namespace in which the template was defined.
3249 //
3250 // We actually implement this paragraph where we set the semantic
3251 // context (in the creation of the ClassTemplateSpecializationDecl),
3252 // but we also maintain the lexical context where the actual
3253 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003254 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003255
Douglas Gregor67a65642009-02-17 23:15:12 +00003256 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003257 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003258 Specialization->startDefinition();
3259
Douglas Gregor2208a292009-09-26 20:57:03 +00003260 if (TUK == TUK_Friend) {
3261 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3262 TemplateNameLoc,
3263 WrittenTy.getTypePtr(),
3264 /*FIXME:*/KWLoc);
3265 Friend->setAccess(AS_public);
3266 CurContext->addDecl(Friend);
3267 } else {
3268 // Add the specialization into its lexical context, so that it can
3269 // be seen when iterating through the list of declarations in that
3270 // context. However, specializations are not found by name lookup.
3271 CurContext->addDecl(Specialization);
3272 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003273 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003274}
Douglas Gregor333489b2009-03-27 23:10:48 +00003275
Mike Stump11289f42009-09-09 15:08:12 +00003276Sema::DeclPtrTy
3277Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003278 MultiTemplateParamsArg TemplateParameterLists,
3279 Declarator &D) {
3280 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3281}
3282
Mike Stump11289f42009-09-09 15:08:12 +00003283Sema::DeclPtrTy
3284Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003285 MultiTemplateParamsArg TemplateParameterLists,
3286 Declarator &D) {
3287 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3288 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3289 "Not a function declarator!");
3290 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003291
Douglas Gregor17a7c122009-06-24 00:54:41 +00003292 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003293 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003294 }
Mike Stump11289f42009-09-09 15:08:12 +00003295
Douglas Gregor17a7c122009-06-24 00:54:41 +00003296 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003297
3298 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003299 move(TemplateParameterLists),
3300 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003301 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003302 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003303 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003304 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003305 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3306 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003307 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003308}
3309
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003310/// \brief Diagnose cases where we have an explicit template specialization
3311/// before/after an explicit template instantiation, producing diagnostics
3312/// for those cases where they are required and determining whether the
3313/// new specialization/instantiation will have any effect.
3314///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003315/// \param NewLoc the location of the new explicit specialization or
3316/// instantiation.
3317///
3318/// \param NewTSK the kind of the new explicit specialization or instantiation.
3319///
3320/// \param PrevDecl the previous declaration of the entity.
3321///
3322/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3323///
3324/// \param PrevPointOfInstantiation if valid, indicates where the previus
3325/// declaration was instantiated (either implicitly or explicitly).
3326///
3327/// \param SuppressNew will be set to true to indicate that the new
3328/// specialization or instantiation has no effect and should be ignored.
3329///
3330/// \returns true if there was an error that should prevent the introduction of
3331/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003332bool
3333Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3334 TemplateSpecializationKind NewTSK,
3335 NamedDecl *PrevDecl,
3336 TemplateSpecializationKind PrevTSK,
3337 SourceLocation PrevPointOfInstantiation,
3338 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003339 SuppressNew = false;
3340
3341 switch (NewTSK) {
3342 case TSK_Undeclared:
3343 case TSK_ImplicitInstantiation:
3344 assert(false && "Don't check implicit instantiations here");
3345 return false;
3346
3347 case TSK_ExplicitSpecialization:
3348 switch (PrevTSK) {
3349 case TSK_Undeclared:
3350 case TSK_ExplicitSpecialization:
3351 // Okay, we're just specializing something that is either already
3352 // explicitly specialized or has merely been mentioned without any
3353 // instantiation.
3354 return false;
3355
3356 case TSK_ImplicitInstantiation:
3357 if (PrevPointOfInstantiation.isInvalid()) {
3358 // The declaration itself has not actually been instantiated, so it is
3359 // still okay to specialize it.
3360 return false;
3361 }
3362 // Fall through
3363
3364 case TSK_ExplicitInstantiationDeclaration:
3365 case TSK_ExplicitInstantiationDefinition:
3366 assert((PrevTSK == TSK_ImplicitInstantiation ||
3367 PrevPointOfInstantiation.isValid()) &&
3368 "Explicit instantiation without point of instantiation?");
3369
3370 // C++ [temp.expl.spec]p6:
3371 // If a template, a member template or the member of a class template
3372 // is explicitly specialized then that specialization shall be declared
3373 // before the first use of that specialization that would cause an
3374 // implicit instantiation to take place, in every translation unit in
3375 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003376 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003377 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003378 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003379 << (PrevTSK != TSK_ImplicitInstantiation);
3380
3381 return true;
3382 }
3383 break;
3384
3385 case TSK_ExplicitInstantiationDeclaration:
3386 switch (PrevTSK) {
3387 case TSK_ExplicitInstantiationDeclaration:
3388 // This explicit instantiation declaration is redundant (that's okay).
3389 SuppressNew = true;
3390 return false;
3391
3392 case TSK_Undeclared:
3393 case TSK_ImplicitInstantiation:
3394 // We're explicitly instantiating something that may have already been
3395 // implicitly instantiated; that's fine.
3396 return false;
3397
3398 case TSK_ExplicitSpecialization:
3399 // C++0x [temp.explicit]p4:
3400 // For a given set of template parameters, if an explicit instantiation
3401 // of a template appears after a declaration of an explicit
3402 // specialization for that template, the explicit instantiation has no
3403 // effect.
3404 return false;
3405
3406 case TSK_ExplicitInstantiationDefinition:
3407 // C++0x [temp.explicit]p10:
3408 // If an entity is the subject of both an explicit instantiation
3409 // declaration and an explicit instantiation definition in the same
3410 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003411 Diag(NewLoc,
3412 diag::err_explicit_instantiation_declaration_after_definition);
3413 Diag(PrevPointOfInstantiation,
3414 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003415 assert(PrevPointOfInstantiation.isValid() &&
3416 "Explicit instantiation without point of instantiation?");
3417 SuppressNew = true;
3418 return false;
3419 }
3420 break;
3421
3422 case TSK_ExplicitInstantiationDefinition:
3423 switch (PrevTSK) {
3424 case TSK_Undeclared:
3425 case TSK_ImplicitInstantiation:
3426 // We're explicitly instantiating something that may have already been
3427 // implicitly instantiated; that's fine.
3428 return false;
3429
3430 case TSK_ExplicitSpecialization:
3431 // C++ DR 259, C++0x [temp.explicit]p4:
3432 // For a given set of template parameters, if an explicit
3433 // instantiation of a template appears after a declaration of
3434 // an explicit specialization for that template, the explicit
3435 // instantiation has no effect.
3436 //
3437 // In C++98/03 mode, we only give an extension warning here, because it
3438 // is not not harmful to try to explicitly instantiate something that
3439 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003440 if (!getLangOptions().CPlusPlus0x) {
3441 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003442 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003443 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003444 diag::note_previous_template_specialization);
3445 }
3446 SuppressNew = true;
3447 return false;
3448
3449 case TSK_ExplicitInstantiationDeclaration:
3450 // We're explicity instantiating a definition for something for which we
3451 // were previously asked to suppress instantiations. That's fine.
3452 return false;
3453
3454 case TSK_ExplicitInstantiationDefinition:
3455 // C++0x [temp.spec]p5:
3456 // For a given template and a given set of template-arguments,
3457 // - an explicit instantiation definition shall appear at most once
3458 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003459 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003460 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003461 Diag(PrevPointOfInstantiation,
3462 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003463 SuppressNew = true;
3464 return false;
3465 }
3466 break;
3467 }
3468
3469 assert(false && "Missing specialization/instantiation case?");
3470
3471 return false;
3472}
3473
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003474/// \brief Perform semantic analysis for the given function template
3475/// specialization.
3476///
3477/// This routine performs all of the semantic analysis required for an
3478/// explicit function template specialization. On successful completion,
3479/// the function declaration \p FD will become a function template
3480/// specialization.
3481///
3482/// \param FD the function declaration, which will be updated to become a
3483/// function template specialization.
3484///
3485/// \param HasExplicitTemplateArgs whether any template arguments were
3486/// explicitly provided.
3487///
3488/// \param LAngleLoc the location of the left angle bracket ('<'), if
3489/// template arguments were explicitly provided.
3490///
3491/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3492/// if any.
3493///
3494/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3495/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3496/// true as in, e.g., \c void sort<>(char*, char*);
3497///
3498/// \param RAngleLoc the location of the right angle bracket ('>'), if
3499/// template arguments were explicitly provided.
3500///
3501/// \param PrevDecl the set of declarations that
3502bool
3503Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3504 bool HasExplicitTemplateArgs,
3505 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00003506 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003507 unsigned NumExplicitTemplateArgs,
3508 SourceLocation RAngleLoc,
3509 NamedDecl *&PrevDecl) {
3510 // The set of function template specializations that could match this
3511 // explicit function template specialization.
3512 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3513 CandidateSet Candidates;
3514
3515 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3516 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3517 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3518 // Only consider templates found within the same semantic lookup scope as
3519 // FD.
3520 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3521 continue;
3522
3523 // C++ [temp.expl.spec]p11:
3524 // A trailing template-argument can be left unspecified in the
3525 // template-id naming an explicit function template specialization
3526 // provided it can be deduced from the function argument type.
3527 // Perform template argument deduction to determine whether we may be
3528 // specializing this template.
3529 // FIXME: It is somewhat wasteful to build
3530 TemplateDeductionInfo Info(Context);
3531 FunctionDecl *Specialization = 0;
3532 if (TemplateDeductionResult TDK
3533 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3534 ExplicitTemplateArgs,
3535 NumExplicitTemplateArgs,
3536 FD->getType(),
3537 Specialization,
3538 Info)) {
3539 // FIXME: Template argument deduction failed; record why it failed, so
3540 // that we can provide nifty diagnostics.
3541 (void)TDK;
3542 continue;
3543 }
3544
3545 // Record this candidate.
3546 Candidates.push_back(Specialization);
3547 }
3548 }
3549
Douglas Gregor5de279c2009-09-26 03:41:46 +00003550 // Find the most specialized function template.
3551 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3552 Candidates.size(),
3553 TPOC_Other,
3554 FD->getLocation(),
3555 PartialDiagnostic(diag::err_function_template_spec_no_match)
3556 << FD->getDeclName(),
3557 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3558 << FD->getDeclName() << HasExplicitTemplateArgs,
3559 PartialDiagnostic(diag::note_function_template_spec_matched));
3560 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003561 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003562
3563 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003564 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003565
Douglas Gregor54888652009-10-07 00:13:32 +00003566 // Check the scope of this explicit specialization.
3567 if (CheckTemplateSpecializationScope(*this,
3568 Specialization->getPrimaryTemplate(),
3569 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003570 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003571 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003572
3573 // C++ [temp.expl.spec]p6:
3574 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003575 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003576 // before the first use of that specialization that would cause an implicit
3577 // instantiation to take place, in every translation unit in which such a
3578 // use occurs; no diagnostic is required.
3579 FunctionTemplateSpecializationInfo *SpecInfo
3580 = Specialization->getTemplateSpecializationInfo();
3581 assert(SpecInfo && "Function template specialization info missing?");
3582 if (SpecInfo->getPointOfInstantiation().isValid()) {
3583 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3584 << FD;
3585 Diag(SpecInfo->getPointOfInstantiation(),
3586 diag::note_instantiation_required_here)
3587 << (Specialization->getTemplateSpecializationKind()
3588 != TSK_ImplicitInstantiation);
3589 return true;
3590 }
Douglas Gregor54888652009-10-07 00:13:32 +00003591
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003592 // Mark the prior declaration as an explicit specialization, so that later
3593 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003594 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003595
3596 // Turn the given function declaration into a function template
3597 // specialization, with the template arguments from the previous
3598 // specialization.
3599 FD->setFunctionTemplateSpecialization(Context,
3600 Specialization->getPrimaryTemplate(),
3601 new (Context) TemplateArgumentList(
3602 *Specialization->getTemplateSpecializationArgs()),
3603 /*InsertPos=*/0,
3604 TSK_ExplicitSpecialization);
3605
3606 // The "previous declaration" for this function template specialization is
3607 // the prior function template specialization.
3608 PrevDecl = Specialization;
3609 return false;
3610}
3611
Douglas Gregor86d142a2009-10-08 07:24:58 +00003612/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003613/// specialization.
3614///
3615/// This routine performs all of the semantic analysis required for an
3616/// explicit member function specialization. On successful completion,
3617/// the function declaration \p FD will become a member function
3618/// specialization.
3619///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003620/// \param Member the member declaration, which will be updated to become a
3621/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003622///
3623/// \param PrevDecl the set of declarations, one of which may be specialized
3624/// by this function specialization.
3625bool
Douglas Gregor86d142a2009-10-08 07:24:58 +00003626Sema::CheckMemberSpecialization(NamedDecl *Member, NamedDecl *&PrevDecl) {
3627 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3628
3629 // Try to find the member we are instantiating.
3630 NamedDecl *Instantiation = 0;
3631 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003632 MemberSpecializationInfo *MSInfo = 0;
3633
Douglas Gregor86d142a2009-10-08 07:24:58 +00003634 if (!PrevDecl) {
3635 // Nowhere to look anyway.
3636 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3637 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3638 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl)) {
3639 if (Context.hasSameType(Function->getType(), Method->getType())) {
3640 Instantiation = Method;
3641 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003642 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003643 break;
3644 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003645 }
3646 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003647 } else if (isa<VarDecl>(Member)) {
3648 if (VarDecl *PrevVar = dyn_cast<VarDecl>(PrevDecl))
3649 if (PrevVar->isStaticDataMember()) {
3650 Instantiation = PrevDecl;
3651 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003652 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003653 }
3654 } else if (isa<RecordDecl>(Member)) {
3655 if (CXXRecordDecl *PrevRecord = dyn_cast<CXXRecordDecl>(PrevDecl)) {
3656 Instantiation = PrevDecl;
3657 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003658 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003659 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003660 }
3661
3662 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003663 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003664 // specializations are always out-of-line, the caller will complain about
3665 // this mismatch later.
3666 return false;
3667 }
3668
Douglas Gregor86d142a2009-10-08 07:24:58 +00003669 // Make sure that this is a specialization of a member.
3670 if (!InstantiatedFrom) {
3671 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3672 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003673 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3674 return true;
3675 }
3676
Douglas Gregor06db9f52009-10-12 20:18:28 +00003677 // C++ [temp.expl.spec]p6:
3678 // If a template, a member template or the member of a class template is
3679 // explicitly specialized then that spe- cialization shall be declared
3680 // before the first use of that specialization that would cause an implicit
3681 // instantiation to take place, in every translation unit in which such a
3682 // use occurs; no diagnostic is required.
3683 assert(MSInfo && "Member specialization info missing?");
3684 if (MSInfo->getPointOfInstantiation().isValid()) {
3685 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3686 << Member;
3687 Diag(MSInfo->getPointOfInstantiation(),
3688 diag::note_instantiation_required_here)
3689 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3690 return true;
3691 }
3692
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003693 // Check the scope of this explicit specialization.
3694 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003695 InstantiatedFrom,
3696 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003697 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003698 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003699
Douglas Gregor86d142a2009-10-08 07:24:58 +00003700 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003701 // the original declaration to note that it is an explicit specialization
3702 // (if it was previously an implicit instantiation). This latter step
3703 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003704 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003705 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3706 if (InstantiationFunction->getTemplateSpecializationKind() ==
3707 TSK_ImplicitInstantiation) {
3708 InstantiationFunction->setTemplateSpecializationKind(
3709 TSK_ExplicitSpecialization);
3710 InstantiationFunction->setLocation(Member->getLocation());
3711 }
3712
Douglas Gregor86d142a2009-10-08 07:24:58 +00003713 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3714 cast<CXXMethodDecl>(InstantiatedFrom),
3715 TSK_ExplicitSpecialization);
3716 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003717 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3718 if (InstantiationVar->getTemplateSpecializationKind() ==
3719 TSK_ImplicitInstantiation) {
3720 InstantiationVar->setTemplateSpecializationKind(
3721 TSK_ExplicitSpecialization);
3722 InstantiationVar->setLocation(Member->getLocation());
3723 }
3724
Douglas Gregor86d142a2009-10-08 07:24:58 +00003725 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3726 cast<VarDecl>(InstantiatedFrom),
3727 TSK_ExplicitSpecialization);
3728 } else {
3729 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003730 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3731 if (InstantiationClass->getTemplateSpecializationKind() ==
3732 TSK_ImplicitInstantiation) {
3733 InstantiationClass->setTemplateSpecializationKind(
3734 TSK_ExplicitSpecialization);
3735 InstantiationClass->setLocation(Member->getLocation());
3736 }
3737
Douglas Gregor86d142a2009-10-08 07:24:58 +00003738 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003739 cast<CXXRecordDecl>(InstantiatedFrom),
3740 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003741 }
3742
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003743 // Save the caller the trouble of having to figure out which declaration
3744 // this specialization matches.
3745 PrevDecl = Instantiation;
3746 return false;
3747}
3748
Douglas Gregore47f5a72009-10-14 23:41:34 +00003749/// \brief Check the scope of an explicit instantiation.
3750static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3751 SourceLocation InstLoc,
3752 bool WasQualifiedName) {
3753 DeclContext *ExpectedContext
3754 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3755 DeclContext *CurContext = S.CurContext->getLookupContext();
3756
3757 // C++0x [temp.explicit]p2:
3758 // An explicit instantiation shall appear in an enclosing namespace of its
3759 // template.
3760 //
3761 // This is DR275, which we do not retroactively apply to C++98/03.
3762 if (S.getLangOptions().CPlusPlus0x &&
3763 !CurContext->Encloses(ExpectedContext)) {
3764 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3765 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3766 << D << NS;
3767 else
3768 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3769 << D;
3770 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3771 return;
3772 }
3773
3774 // C++0x [temp.explicit]p2:
3775 // If the name declared in the explicit instantiation is an unqualified
3776 // name, the explicit instantiation shall appear in the namespace where
3777 // its template is declared or, if that namespace is inline (7.3.1), any
3778 // namespace from its enclosing namespace set.
3779 if (WasQualifiedName)
3780 return;
3781
3782 if (CurContext->Equals(ExpectedContext))
3783 return;
3784
3785 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3786 << D << ExpectedContext;
3787 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3788}
3789
3790/// \brief Determine whether the given scope specifier has a template-id in it.
3791static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3792 if (!SS.isSet())
3793 return false;
3794
3795 // C++0x [temp.explicit]p2:
3796 // If the explicit instantiation is for a member function, a member class
3797 // or a static data member of a class template specialization, the name of
3798 // the class template specialization in the qualified-id for the member
3799 // name shall be a simple-template-id.
3800 //
3801 // C++98 has the same restriction, just worded differently.
3802 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3803 NNS; NNS = NNS->getPrefix())
3804 if (Type *T = NNS->getAsType())
3805 if (isa<TemplateSpecializationType>(T))
3806 return true;
3807
3808 return false;
3809}
3810
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003811// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003812// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003813Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003814Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003815 SourceLocation ExternLoc,
3816 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003817 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003818 SourceLocation KWLoc,
3819 const CXXScopeSpec &SS,
3820 TemplateTy TemplateD,
3821 SourceLocation TemplateNameLoc,
3822 SourceLocation LAngleLoc,
3823 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00003824 SourceLocation RAngleLoc,
3825 AttributeList *Attr) {
3826 // Find the class template we're specializing
3827 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003828 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003829 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3830
3831 // Check that the specialization uses the same tag kind as the
3832 // original template.
3833 TagDecl::TagKind Kind;
3834 switch (TagSpec) {
3835 default: assert(0 && "Unknown tag type!");
3836 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3837 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3838 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3839 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003840 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003841 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003842 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003843 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003844 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003845 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003846 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003847 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003848 diag::note_previous_use);
3849 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3850 }
3851
Douglas Gregore47f5a72009-10-14 23:41:34 +00003852 // C++0x [temp.explicit]p2:
3853 // There are two forms of explicit instantiation: an explicit instantiation
3854 // definition and an explicit instantiation declaration. An explicit
3855 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00003856 TemplateSpecializationKind TSK
3857 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3858 : TSK_ExplicitInstantiationDeclaration;
3859
Douglas Gregora1f49972009-05-13 00:25:59 +00003860 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00003861 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003862 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00003863
3864 // Check that the template argument list is well-formed for this
3865 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003866 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3867 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003868 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003869 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003870 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003871 return true;
3872
Mike Stump11289f42009-09-09 15:08:12 +00003873 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003874 ClassTemplate->getTemplateParameters()->size()) &&
3875 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003876
Douglas Gregora1f49972009-05-13 00:25:59 +00003877 // Find the class template specialization declaration that
3878 // corresponds to these arguments.
3879 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003880 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003881 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003882 Converted.flatSize(),
3883 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003884 void *InsertPos = 0;
3885 ClassTemplateSpecializationDecl *PrevDecl
3886 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3887
Douglas Gregor54888652009-10-07 00:13:32 +00003888 // C++0x [temp.explicit]p2:
3889 // [...] An explicit instantiation shall appear in an enclosing
3890 // namespace of its template. [...]
3891 //
3892 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00003893 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
3894 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00003895
Douglas Gregora1f49972009-05-13 00:25:59 +00003896 ClassTemplateSpecializationDecl *Specialization = 0;
3897
3898 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00003899 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003900 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00003901 PrevDecl,
3902 PrevDecl->getSpecializationKind(),
3903 PrevDecl->getPointOfInstantiation(),
3904 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00003905 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003906
Douglas Gregor12e49d32009-10-15 22:53:21 +00003907 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003908 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00003909
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003910 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3911 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3912 // Since the only prior class template specialization with these
3913 // arguments was referenced but not declared, reuse that
3914 // declaration node as our own, updating its source location to
3915 // reflect our new declaration.
3916 Specialization = PrevDecl;
3917 Specialization->setLocation(TemplateNameLoc);
3918 PrevDecl = 0;
3919 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00003920 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003921
3922 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003923 // Create a new class template specialization declaration node for
3924 // this explicit specialization.
3925 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003926 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003927 ClassTemplate->getDeclContext(),
3928 TemplateNameLoc,
3929 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003930 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003931
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003932 if (PrevDecl) {
3933 // Remove the previous declaration from the folding set, since we want
3934 // to introduce a new declaration.
3935 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3936 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3937 }
3938
3939 // Insert the new specialization.
3940 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003941 }
3942
3943 // Build the fully-sugared type for this explicit instantiation as
3944 // the user wrote in the explicit instantiation itself. This means
3945 // that we'll pretty-print the type retrieved from the
3946 // specialization's declaration the way that the user actually wrote
3947 // the explicit instantiation, rather than formatting the name based
3948 // on the "canonical" representation used to store the template
3949 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003950 QualType WrittenTy
3951 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003952 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003953 TemplateArgs.size(),
3954 Context.getTypeDeclType(Specialization));
3955 Specialization->setTypeAsWritten(WrittenTy);
3956 TemplateArgsIn.release();
3957
3958 // Add the explicit instantiation into its lexical context. However,
3959 // since explicit instantiations are never found by name lookup, we
3960 // just put it into the declaration context directly.
3961 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003962 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003963
3964 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003965 // A definition of a class template or class member template
3966 // shall be in scope at the point of the explicit instantiation of
3967 // the class template or class member template.
3968 //
3969 // This check comes when we actually try to perform the
3970 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00003971 ClassTemplateSpecializationDecl *Def
3972 = cast_or_null<ClassTemplateSpecializationDecl>(
3973 Specialization->getDefinition(Context));
3974 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00003975 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00003976
3977 // Instantiate the members of this class template specialization.
3978 Def = cast_or_null<ClassTemplateSpecializationDecl>(
3979 Specialization->getDefinition(Context));
3980 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00003981 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003982
3983 return DeclPtrTy::make(Specialization);
3984}
3985
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003986// Explicit instantiation of a member class of a class template.
3987Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003988Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003989 SourceLocation ExternLoc,
3990 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003991 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003992 SourceLocation KWLoc,
3993 const CXXScopeSpec &SS,
3994 IdentifierInfo *Name,
3995 SourceLocation NameLoc,
3996 AttributeList *Attr) {
3997
Douglas Gregord6ab8742009-05-28 23:31:59 +00003998 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003999 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004000 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004001 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004002 MultiTemplateParamsArg(*this, 0, 0),
4003 Owned, IsDependent);
4004 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4005
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004006 if (!TagD)
4007 return true;
4008
4009 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4010 if (Tag->isEnum()) {
4011 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4012 << Context.getTypeDeclType(Tag);
4013 return true;
4014 }
4015
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004016 if (Tag->isInvalidDecl())
4017 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004018
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004019 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4020 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4021 if (!Pattern) {
4022 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4023 << Context.getTypeDeclType(Record);
4024 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4025 return true;
4026 }
4027
Douglas Gregore47f5a72009-10-14 23:41:34 +00004028 // C++0x [temp.explicit]p2:
4029 // If the explicit instantiation is for a class or member class, the
4030 // elaborated-type-specifier in the declaration shall include a
4031 // simple-template-id.
4032 //
4033 // C++98 has the same restriction, just worded differently.
4034 if (!ScopeSpecifierHasTemplateId(SS))
4035 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4036 << Record << SS.getRange();
4037
4038 // C++0x [temp.explicit]p2:
4039 // There are two forms of explicit instantiation: an explicit instantiation
4040 // definition and an explicit instantiation declaration. An explicit
4041 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004042 TemplateSpecializationKind TSK
4043 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4044 : TSK_ExplicitInstantiationDeclaration;
4045
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004046 // C++0x [temp.explicit]p2:
4047 // [...] An explicit instantiation shall appear in an enclosing
4048 // namespace of its template. [...]
4049 //
4050 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004051 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004052
4053 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004054 CXXRecordDecl *PrevDecl
4055 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4056 if (!PrevDecl && Record->getDefinition(Context))
4057 PrevDecl = Record;
4058 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004059 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4060 bool SuppressNew = false;
4061 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004062 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004063 PrevDecl,
4064 MSInfo->getTemplateSpecializationKind(),
4065 MSInfo->getPointOfInstantiation(),
4066 SuppressNew))
4067 return true;
4068 if (SuppressNew)
4069 return TagD;
4070 }
4071
Douglas Gregor12e49d32009-10-15 22:53:21 +00004072 CXXRecordDecl *RecordDef
4073 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4074 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004075 // C++ [temp.explicit]p3:
4076 // A definition of a member class of a class template shall be in scope
4077 // at the point of an explicit instantiation of the member class.
4078 CXXRecordDecl *Def
4079 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4080 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004081 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4082 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004083 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4084 << Pattern;
4085 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004086 } else {
4087 if (InstantiateClass(NameLoc, Record, Def,
4088 getTemplateInstantiationArgs(Record),
4089 TSK))
4090 return true;
4091
4092 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4093 if (!RecordDef)
4094 return true;
4095 }
4096 }
4097
4098 // Instantiate all of the members of the class.
4099 InstantiateClassMembers(NameLoc, RecordDef,
4100 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004101
Mike Stump87c57ac2009-05-16 07:39:55 +00004102 // FIXME: We don't have any representation for explicit instantiations of
4103 // member classes. Such a representation is not needed for compilation, but it
4104 // should be available for clients that want to see all of the declarations in
4105 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004106 return TagD;
4107}
4108
Douglas Gregor450f00842009-09-25 18:43:00 +00004109Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4110 SourceLocation ExternLoc,
4111 SourceLocation TemplateLoc,
4112 Declarator &D) {
4113 // Explicit instantiations always require a name.
4114 DeclarationName Name = GetNameForDeclarator(D);
4115 if (!Name) {
4116 if (!D.isInvalidType())
4117 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4118 diag::err_explicit_instantiation_requires_name)
4119 << D.getDeclSpec().getSourceRange()
4120 << D.getSourceRange();
4121
4122 return true;
4123 }
4124
4125 // The scope passed in may not be a decl scope. Zip up the scope tree until
4126 // we find one that is.
4127 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4128 (S->getFlags() & Scope::TemplateParamScope) != 0)
4129 S = S->getParent();
4130
4131 // Determine the type of the declaration.
4132 QualType R = GetTypeForDeclarator(D, S, 0);
4133 if (R.isNull())
4134 return true;
4135
4136 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4137 // Cannot explicitly instantiate a typedef.
4138 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4139 << Name;
4140 return true;
4141 }
4142
Douglas Gregor3c74d412009-10-14 20:14:33 +00004143 // C++0x [temp.explicit]p1:
4144 // [...] An explicit instantiation of a function template shall not use the
4145 // inline or constexpr specifiers.
4146 // Presumably, this also applies to member functions of class templates as
4147 // well.
4148 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4149 Diag(D.getDeclSpec().getInlineSpecLoc(),
4150 diag::err_explicit_instantiation_inline)
4151 << CodeModificationHint::CreateRemoval(
4152 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
4153
4154 // FIXME: check for constexpr specifier.
4155
Douglas Gregore47f5a72009-10-14 23:41:34 +00004156 // C++0x [temp.explicit]p2:
4157 // There are two forms of explicit instantiation: an explicit instantiation
4158 // definition and an explicit instantiation declaration. An explicit
4159 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004160 TemplateSpecializationKind TSK
4161 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4162 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004163
John McCall9f3059a2009-10-09 21:13:30 +00004164 LookupResult Previous;
4165 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
4166 Name, LookupOrdinaryName);
Douglas Gregor450f00842009-09-25 18:43:00 +00004167
4168 if (!R->isFunctionType()) {
4169 // C++ [temp.explicit]p1:
4170 // A [...] static data member of a class template can be explicitly
4171 // instantiated from the member definition associated with its class
4172 // template.
4173 if (Previous.isAmbiguous()) {
4174 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
4175 D.getSourceRange());
4176 }
4177
John McCall9f3059a2009-10-09 21:13:30 +00004178 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4179 Previous.getAsSingleDecl(Context));
Douglas Gregor450f00842009-09-25 18:43:00 +00004180 if (!Prev || !Prev->isStaticDataMember()) {
4181 // We expect to see a data data member here.
4182 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4183 << Name;
4184 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4185 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004186 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004187 return true;
4188 }
4189
4190 if (!Prev->getInstantiatedFromStaticDataMember()) {
4191 // FIXME: Check for explicit specialization?
4192 Diag(D.getIdentifierLoc(),
4193 diag::err_explicit_instantiation_data_member_not_instantiated)
4194 << Prev;
4195 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4196 // FIXME: Can we provide a note showing where this was declared?
4197 return true;
4198 }
4199
Douglas Gregore47f5a72009-10-14 23:41:34 +00004200 // C++0x [temp.explicit]p2:
4201 // If the explicit instantiation is for a member function, a member class
4202 // or a static data member of a class template specialization, the name of
4203 // the class template specialization in the qualified-id for the member
4204 // name shall be a simple-template-id.
4205 //
4206 // C++98 has the same restriction, just worded differently.
4207 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4208 Diag(D.getIdentifierLoc(),
4209 diag::err_explicit_instantiation_without_qualified_id)
4210 << Prev << D.getCXXScopeSpec().getRange();
4211
4212 // Check the scope of this explicit instantiation.
4213 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4214
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004215 // Verify that it is okay to explicitly instantiate here.
4216 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4217 assert(MSInfo && "Missing static data member specialization info?");
4218 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004219 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004220 MSInfo->getTemplateSpecializationKind(),
4221 MSInfo->getPointOfInstantiation(),
4222 SuppressNew))
4223 return true;
4224 if (SuppressNew)
4225 return DeclPtrTy();
4226
Douglas Gregor450f00842009-09-25 18:43:00 +00004227 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004228 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004229 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004230 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4231 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004232
4233 // FIXME: Create an ExplicitInstantiation node?
4234 return DeclPtrTy();
4235 }
4236
Douglas Gregor0e876e02009-09-25 23:53:26 +00004237 // If the declarator is a template-id, translate the parser's template
4238 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004239 bool HasExplicitTemplateArgs = false;
John McCall0ad16662009-10-29 08:12:44 +00004240 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004241 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4242 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Douglas Gregord90fd522009-09-25 21:45:23 +00004243 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4244 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004245 TemplateId->NumArgs);
4246 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregord90fd522009-09-25 21:45:23 +00004247 TemplateArgs);
4248 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004249 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004250 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004251
Douglas Gregor450f00842009-09-25 18:43:00 +00004252 // C++ [temp.explicit]p1:
4253 // A [...] function [...] can be explicitly instantiated from its template.
4254 // A member function [...] of a class template can be explicitly
4255 // instantiated from the member definition associated with its class
4256 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004257 llvm::SmallVector<FunctionDecl *, 8> Matches;
4258 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4259 P != PEnd; ++P) {
4260 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004261 if (!HasExplicitTemplateArgs) {
4262 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4263 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4264 Matches.clear();
4265 Matches.push_back(Method);
4266 break;
4267 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004268 }
4269 }
4270
4271 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4272 if (!FunTmpl)
4273 continue;
4274
4275 TemplateDeductionInfo Info(Context);
4276 FunctionDecl *Specialization = 0;
4277 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00004278 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
4279 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00004280 R, Specialization, Info)) {
4281 // FIXME: Keep track of almost-matches?
4282 (void)TDK;
4283 continue;
4284 }
4285
4286 Matches.push_back(Specialization);
4287 }
4288
4289 // Find the most specialized function template specialization.
4290 FunctionDecl *Specialization
4291 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4292 D.getIdentifierLoc(),
4293 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4294 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4295 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4296
4297 if (!Specialization)
4298 return true;
4299
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004300 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004301 Diag(D.getIdentifierLoc(),
4302 diag::err_explicit_instantiation_member_function_not_instantiated)
4303 << Specialization
4304 << (Specialization->getTemplateSpecializationKind() ==
4305 TSK_ExplicitSpecialization);
4306 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4307 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004308 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004309
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004310 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004311 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4312 PrevDecl = Specialization;
4313
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004314 if (PrevDecl) {
4315 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004316 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004317 PrevDecl,
4318 PrevDecl->getTemplateSpecializationKind(),
4319 PrevDecl->getPointOfInstantiation(),
4320 SuppressNew))
4321 return true;
4322
4323 // FIXME: We may still want to build some representation of this
4324 // explicit specialization.
4325 if (SuppressNew)
4326 return DeclPtrTy();
4327 }
4328
4329 if (TSK == TSK_ExplicitInstantiationDefinition)
4330 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4331 false, /*DefinitionRequired=*/true);
4332
4333 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4334
Douglas Gregore47f5a72009-10-14 23:41:34 +00004335 // C++0x [temp.explicit]p2:
4336 // If the explicit instantiation is for a member function, a member class
4337 // or a static data member of a class template specialization, the name of
4338 // the class template specialization in the qualified-id for the member
4339 // name shall be a simple-template-id.
4340 //
4341 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004342 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004343 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004344 D.getCXXScopeSpec().isSet() &&
4345 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4346 Diag(D.getIdentifierLoc(),
4347 diag::err_explicit_instantiation_without_qualified_id)
4348 << Specialization << D.getCXXScopeSpec().getRange();
4349
4350 CheckExplicitInstantiationScope(*this,
4351 FunTmpl? (NamedDecl *)FunTmpl
4352 : Specialization->getInstantiatedFromMemberFunction(),
4353 D.getIdentifierLoc(),
4354 D.getCXXScopeSpec().isSet());
4355
Douglas Gregor450f00842009-09-25 18:43:00 +00004356 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4357 return DeclPtrTy();
4358}
4359
Douglas Gregor333489b2009-03-27 23:10:48 +00004360Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004361Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4362 const CXXScopeSpec &SS, IdentifierInfo *Name,
4363 SourceLocation TagLoc, SourceLocation NameLoc) {
4364 // This has to hold, because SS is expected to be defined.
4365 assert(Name && "Expected a name in a dependent tag");
4366
4367 NestedNameSpecifier *NNS
4368 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4369 if (!NNS)
4370 return true;
4371
4372 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4373 if (T.isNull())
4374 return true;
4375
4376 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4377 QualType ElabType = Context.getElaboratedType(T, TagKind);
4378
4379 return ElabType.getAsOpaquePtr();
4380}
4381
4382Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004383Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4384 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004385 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004386 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4387 if (!NNS)
4388 return true;
4389
4390 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004391 if (T.isNull())
4392 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004393 return T.getAsOpaquePtr();
4394}
4395
Douglas Gregordce2b622009-04-01 00:28:59 +00004396Sema::TypeResult
4397Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4398 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004399 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004400 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004401 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004402 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004403 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004404 assert(TemplateId && "Expected a template specialization type");
4405
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004406 if (computeDeclContext(SS, false)) {
4407 // If we can compute a declaration context, then the "typename"
4408 // keyword was superfluous. Just build a QualifiedNameType to keep
4409 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004410
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004411 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4412 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4413 }
Mike Stump11289f42009-09-09 15:08:12 +00004414
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004415 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004416}
4417
Douglas Gregor333489b2009-03-27 23:10:48 +00004418/// \brief Build the type that describes a C++ typename specifier,
4419/// e.g., "typename T::type".
4420QualType
4421Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4422 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004423 CXXRecordDecl *CurrentInstantiation = 0;
4424 if (NNS->isDependent()) {
4425 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004426
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004427 // If the nested-name-specifier does not refer to the current
4428 // instantiation, then build a typename type.
4429 if (!CurrentInstantiation)
4430 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004431
Douglas Gregorc707da62009-09-02 13:12:51 +00004432 // The nested-name-specifier refers to the current instantiation, so the
4433 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004434 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004435 // extraneous "typename" keywords, and we retroactively apply this DR to
4436 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004437 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004438
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004439 DeclContext *Ctx = 0;
4440
4441 if (CurrentInstantiation)
4442 Ctx = CurrentInstantiation;
4443 else {
4444 CXXScopeSpec SS;
4445 SS.setScopeRep(NNS);
4446 SS.setRange(Range);
4447 if (RequireCompleteDeclContext(SS))
4448 return QualType();
4449
4450 Ctx = computeDeclContext(SS);
4451 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004452 assert(Ctx && "No declaration context?");
4453
4454 DeclarationName Name(&II);
John McCall9f3059a2009-10-09 21:13:30 +00004455 LookupResult Result;
4456 LookupQualifiedName(Result, Ctx, Name, LookupOrdinaryName, false);
Douglas Gregor333489b2009-03-27 23:10:48 +00004457 unsigned DiagID = 0;
4458 Decl *Referenced = 0;
4459 switch (Result.getKind()) {
4460 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004461 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004462 break;
4463
4464 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004465 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004466 // We found a type. Build a QualifiedNameType, since the
4467 // typename-specifier was just sugar. FIXME: Tell
4468 // QualifiedNameType that it has a "typename" prefix.
4469 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4470 }
4471
4472 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004473 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004474 break;
4475
4476 case LookupResult::FoundOverloaded:
4477 DiagID = diag::err_typename_nested_not_type;
4478 Referenced = *Result.begin();
4479 break;
4480
John McCall6538c932009-10-10 05:48:19 +00004481 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004482 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
4483 return QualType();
4484 }
4485
4486 // If we get here, it's because name lookup did not find a
4487 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004488 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004489 if (Referenced)
4490 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4491 << Name;
4492 return QualType();
4493}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004494
4495namespace {
4496 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00004497 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4498 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004499 SourceLocation Loc;
4500 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004501
Douglas Gregor15acfb92009-08-06 16:20:37 +00004502 public:
Mike Stump11289f42009-09-09 15:08:12 +00004503 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004504 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004505 DeclarationName Entity)
4506 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004507 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004508
4509 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004510 /// transformed.
4511 ///
4512 /// For the purposes of type reconstruction, a type has already been
4513 /// transformed if it is NULL or if it is not dependent.
4514 bool AlreadyTransformed(QualType T) {
4515 return T.isNull() || !T->isDependentType();
4516 }
Mike Stump11289f42009-09-09 15:08:12 +00004517
4518 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004519 /// rebuilt.
4520 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004521
Douglas Gregor15acfb92009-08-06 16:20:37 +00004522 /// \brief Returns the name of the entity whose type is being rebuilt.
4523 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004524
Douglas Gregoref6ab412009-10-27 06:26:26 +00004525 /// \brief Sets the "base" location and entity when that
4526 /// information is known based on another transformation.
4527 void setBase(SourceLocation Loc, DeclarationName Entity) {
4528 this->Loc = Loc;
4529 this->Entity = Entity;
4530 }
4531
Douglas Gregor15acfb92009-08-06 16:20:37 +00004532 /// \brief Transforms an expression by returning the expression itself
4533 /// (an identity function).
4534 ///
4535 /// FIXME: This is completely unsafe; we will need to actually clone the
4536 /// expressions.
4537 Sema::OwningExprResult TransformExpr(Expr *E) {
4538 return getSema().Owned(E);
4539 }
Mike Stump11289f42009-09-09 15:08:12 +00004540
Douglas Gregor15acfb92009-08-06 16:20:37 +00004541 /// \brief Transforms a typename type by determining whether the type now
4542 /// refers to a member of the current instantiation, and then
4543 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004544 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004545 };
4546}
4547
Mike Stump11289f42009-09-09 15:08:12 +00004548QualType
John McCall550e0c22009-10-21 00:40:46 +00004549CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4550 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004551 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004552
Douglas Gregor15acfb92009-08-06 16:20:37 +00004553 NestedNameSpecifier *NNS
4554 = TransformNestedNameSpecifier(T->getQualifier(),
4555 /*FIXME:*/SourceRange(getBaseLocation()));
4556 if (!NNS)
4557 return QualType();
4558
4559 // If the nested-name-specifier did not change, and we cannot compute the
4560 // context corresponding to the nested-name-specifier, then this
4561 // typename type will not change; exit early.
4562 CXXScopeSpec SS;
4563 SS.setRange(SourceRange(getBaseLocation()));
4564 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004565
4566 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004567 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004568 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004569
4570 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004571 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004572 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004573 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004574 = TransformType(QualType(TemplateId, 0));
4575 if (NewTemplateId.isNull())
4576 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004577
Douglas Gregor15acfb92009-08-06 16:20:37 +00004578 if (NNS == T->getQualifier() &&
4579 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004580 Result = QualType(T, 0);
4581 else
4582 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4583 } else
4584 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4585 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004586
John McCall0ad16662009-10-29 08:12:44 +00004587 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4588 NewTL.setNameLoc(TL.getNameLoc());
4589 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004590}
4591
4592/// \brief Rebuilds a type within the context of the current instantiation.
4593///
Mike Stump11289f42009-09-09 15:08:12 +00004594/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004595/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004596/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004597/// partial specialization thereof). This routine will rebuild that type now
4598/// that we have entered the declarator's scope, which may produce different
4599/// canonical types, e.g.,
4600///
4601/// \code
4602/// template<typename T>
4603/// struct X {
4604/// typedef T* pointer;
4605/// pointer data();
4606/// };
4607///
4608/// template<typename T>
4609/// typename X<T>::pointer X<T>::data() { ... }
4610/// \endcode
4611///
4612/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4613/// since we do not know that we can look into X<T> when we parsed the type.
4614/// This function will rebuild the type, performing the lookup of "pointer"
4615/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4616/// as the canonical type of T*, allowing the return types of the out-of-line
4617/// definition and the declaration to match.
4618QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4619 DeclarationName Name) {
4620 if (T.isNull() || !T->isDependentType())
4621 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004622
Douglas Gregor15acfb92009-08-06 16:20:37 +00004623 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4624 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004625}
Douglas Gregorbe999392009-09-15 16:23:51 +00004626
4627/// \brief Produces a formatted string that describes the binding of
4628/// template parameters to template arguments.
4629std::string
4630Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4631 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004632 // FIXME: For variadic templates, we'll need to get the structured list.
4633 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4634 Args.flat_size());
4635}
4636
4637std::string
4638Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4639 const TemplateArgument *Args,
4640 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004641 std::string Result;
4642
Douglas Gregore62e6a02009-11-11 19:13:48 +00004643 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00004644 return Result;
4645
4646 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004647 if (I >= NumArgs)
4648 break;
4649
Douglas Gregorbe999392009-09-15 16:23:51 +00004650 if (I == 0)
4651 Result += "[with ";
4652 else
4653 Result += ", ";
4654
4655 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4656 Result += Id->getName();
4657 } else {
4658 Result += '$';
4659 Result += llvm::utostr(I);
4660 }
4661
4662 Result += " = ";
4663
4664 switch (Args[I].getKind()) {
4665 case TemplateArgument::Null:
4666 Result += "<no value>";
4667 break;
4668
4669 case TemplateArgument::Type: {
4670 std::string TypeStr;
4671 Args[I].getAsType().getAsStringInternal(TypeStr,
4672 Context.PrintingPolicy);
4673 Result += TypeStr;
4674 break;
4675 }
4676
4677 case TemplateArgument::Declaration: {
4678 bool Unnamed = true;
4679 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4680 if (ND->getDeclName()) {
4681 Unnamed = false;
4682 Result += ND->getNameAsString();
4683 }
4684 }
4685
4686 if (Unnamed) {
4687 Result += "<anonymous>";
4688 }
4689 break;
4690 }
4691
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004692 case TemplateArgument::Template: {
4693 std::string Str;
4694 llvm::raw_string_ostream OS(Str);
4695 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4696 Result += OS.str();
4697 break;
4698 }
4699
Douglas Gregorbe999392009-09-15 16:23:51 +00004700 case TemplateArgument::Integral: {
4701 Result += Args[I].getAsIntegral()->toString(10);
4702 break;
4703 }
4704
4705 case TemplateArgument::Expression: {
4706 assert(false && "No expressions in deduced template arguments!");
4707 Result += "<expression>";
4708 break;
4709 }
4710
4711 case TemplateArgument::Pack:
4712 // FIXME: Format template argument packs
4713 Result += "<template argument pack>";
4714 break;
4715 }
4716 }
4717
4718 Result += ']';
4719 return Result;
4720}