blob: 32a6d6c2438b15ec343792ef2c4aef200e210061 [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 Gregor5101c242008-12-05 18:15:24 +0000287/// ActOnTypeParameter - Called when a C++ template type parameter
288/// (e.g., "typename T") has been parsed. Typename specifies whether
289/// the keyword "typename" was used to declare the type parameter
290/// (otherwise, "class" was used), and KeyLoc is the location of the
291/// "class" or "typename" keyword. ParamName is the name of the
292/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000293/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000294/// If the type parameter has a default argument, it will be added
295/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000296Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000297 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000298 SourceLocation KeyLoc,
299 IdentifierInfo *ParamName,
300 SourceLocation ParamNameLoc,
301 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000302 assert(S->isTemplateParamScope() &&
303 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000304 bool Invalid = false;
305
306 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000307 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000308 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000309 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000310 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000311 }
312
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000313 SourceLocation Loc = ParamNameLoc;
314 if (!ParamName)
315 Loc = KeyLoc;
316
Douglas Gregor5101c242008-12-05 18:15:24 +0000317 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000318 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
319 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000320 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000321 if (Invalid)
322 Param->setInvalidDecl();
323
324 if (ParamName) {
325 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000326 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000327 IdResolver.AddDecl(Param);
328 }
329
Chris Lattner83f095c2009-03-28 19:18:32 +0000330 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000331}
332
Douglas Gregordba32632009-02-10 19:49:53 +0000333/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000334/// Default) to the given template type parameter (TypeParam).
335void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000336 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000337 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000338 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000339 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000340 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000341
342 DeclaratorInfo *DefaultDInfo;
343 GetTypeFromParser(DefaultT, &DefaultDInfo);
344
345 assert(DefaultDInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000346
Anders Carlssond3824352009-06-12 22:30:13 +0000347 // C++0x [temp.param]p9:
348 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000349 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000350 if (Parm->isParameterPack()) {
351 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000352 return;
353 }
Mike Stump11289f42009-09-09 15:08:12 +0000354
Douglas Gregordba32632009-02-10 19:49:53 +0000355 // C++ [temp.param]p14:
356 // A template-parameter shall not be used in its own default argument.
357 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000358
Douglas Gregordba32632009-02-10 19:49:53 +0000359 // Check the template argument itself.
John McCall0ad16662009-10-29 08:12:44 +0000360 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000361 Parm->setInvalidDecl();
362 return;
363 }
364
John McCall0ad16662009-10-29 08:12:44 +0000365 Parm->setDefaultArgument(DefaultDInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000366}
367
Douglas Gregor463421d2009-03-03 04:44:36 +0000368/// \brief Check that the type of a non-type template parameter is
369/// well-formed.
370///
371/// \returns the (possibly-promoted) parameter type if valid;
372/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000373QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000374Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
375 // C++ [temp.param]p4:
376 //
377 // A non-type template-parameter shall have one of the following
378 // (optionally cv-qualified) types:
379 //
380 // -- integral or enumeration type,
381 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000382 // -- pointer to object or pointer to function,
383 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000384 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
385 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000386 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000387 T->isReferenceType() ||
388 // -- pointer to member.
389 T->isMemberPointerType() ||
390 // If T is a dependent type, we can't do the check now, so we
391 // assume that it is well-formed.
392 T->isDependentType())
393 return T;
394 // C++ [temp.param]p8:
395 //
396 // A non-type template-parameter of type "array of T" or
397 // "function returning T" is adjusted to be of type "pointer to
398 // T" or "pointer to function returning T", respectively.
399 else if (T->isArrayType())
400 // FIXME: Keep the type prior to promotion?
401 return Context.getArrayDecayedType(T);
402 else if (T->isFunctionType())
403 // FIXME: Keep the type prior to promotion?
404 return Context.getPointerType(T);
405
406 Diag(Loc, diag::err_template_nontype_parm_bad_type)
407 << T;
408
409 return QualType();
410}
411
Douglas Gregor5101c242008-12-05 18:15:24 +0000412/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
413/// template parameter (e.g., "int Size" in "template<int Size>
414/// class Array") has been parsed. S is the current scope and D is
415/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000416Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000417 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000418 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000419 DeclaratorInfo *DInfo = 0;
420 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000421
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000422 assert(S->isTemplateParamScope() &&
423 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000424 bool Invalid = false;
425
426 IdentifierInfo *ParamName = D.getIdentifier();
427 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000428 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000429 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000430 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000431 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000432 }
433
Douglas Gregor463421d2009-03-03 04:44:36 +0000434 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000435 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000436 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000437 Invalid = true;
438 }
Douglas Gregor81338792009-02-10 17:43:50 +0000439
Douglas Gregor5101c242008-12-05 18:15:24 +0000440 NonTypeTemplateParmDecl *Param
441 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000442 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000443 if (Invalid)
444 Param->setInvalidDecl();
445
446 if (D.getIdentifier()) {
447 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000448 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000449 IdResolver.AddDecl(Param);
450 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000451 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000452}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000453
Douglas Gregordba32632009-02-10 19:49:53 +0000454/// \brief Adds a default argument to the given non-type template
455/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000456void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000457 SourceLocation EqualLoc,
458 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000459 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000460 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000461 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000462
Douglas Gregordba32632009-02-10 19:49:53 +0000463 // C++ [temp.param]p14:
464 // A template-parameter shall not be used in its own default argument.
465 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000466
Douglas Gregordba32632009-02-10 19:49:53 +0000467 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000468 TemplateArgument Converted;
469 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
470 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000471 TemplateParm->setInvalidDecl();
472 return;
473 }
474
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000475 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000476}
477
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000478
479/// ActOnTemplateTemplateParameter - Called when a C++ template template
480/// parameter (e.g. T in template <template <typename> class T> class array)
481/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000482Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
483 SourceLocation TmpLoc,
484 TemplateParamsTy *Params,
485 IdentifierInfo *Name,
486 SourceLocation NameLoc,
487 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000488 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000489 assert(S->isTemplateParamScope() &&
490 "Template template parameter not in template parameter scope!");
491
492 // Construct the parameter object.
493 TemplateTemplateParmDecl *Param =
494 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
495 Position, Name,
496 (TemplateParameterList*)Params);
497
498 // Make sure the parameter is valid.
499 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
500 // do anything yet. However, if the template parameter list or (eventual)
501 // default value is ever invalidated, that will propagate here.
502 bool Invalid = false;
503 if (Invalid) {
504 Param->setInvalidDecl();
505 }
506
507 // If the tt-param has a name, then link the identifier into the scope
508 // and lookup mechanisms.
509 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000510 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000511 IdResolver.AddDecl(Param);
512 }
513
Chris Lattner83f095c2009-03-28 19:18:32 +0000514 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000515}
516
Douglas Gregordba32632009-02-10 19:49:53 +0000517/// \brief Adds a default argument to the given template template
518/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000519void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000520 SourceLocation EqualLoc,
521 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000522 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000523 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000524
525 // Since a template-template parameter's default argument is an
526 // id-expression, it must be a DeclRefExpr.
Mike Stump11289f42009-09-09 15:08:12 +0000527 DeclRefExpr *Default
Douglas Gregordba32632009-02-10 19:49:53 +0000528 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
529
530 // C++ [temp.param]p14:
531 // A template-parameter shall not be used in its own default argument.
532 // FIXME: Implement this check! Needs a recursive walk over the types.
533
534 // Check the well-formedness of the template argument.
535 if (!isa<TemplateDecl>(Default->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +0000536 Diag(Default->getSourceRange().getBegin(),
Douglas Gregordba32632009-02-10 19:49:53 +0000537 diag::err_template_arg_must_be_template)
538 << Default->getSourceRange();
539 TemplateParm->setInvalidDecl();
540 return;
Mike Stump11289f42009-09-09 15:08:12 +0000541 }
Douglas Gregordba32632009-02-10 19:49:53 +0000542 if (CheckTemplateArgument(TemplateParm, Default)) {
543 TemplateParm->setInvalidDecl();
544 return;
545 }
546
547 DefaultE.release();
548 TemplateParm->setDefaultArgument(Default);
549}
550
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000551/// ActOnTemplateParameterList - Builds a TemplateParameterList that
552/// contains the template parameters in Params/NumParams.
553Sema::TemplateParamsTy *
554Sema::ActOnTemplateParameterList(unsigned Depth,
555 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000556 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000557 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000558 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000559 SourceLocation RAngleLoc) {
560 if (ExportLoc.isValid())
561 Diag(ExportLoc, diag::note_template_export_unsupported);
562
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000563 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000564 (NamedDecl**)Params, NumParams,
565 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000566}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000567
Douglas Gregorc08f4892009-03-25 00:13:59 +0000568Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000569Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000570 SourceLocation KWLoc, const CXXScopeSpec &SS,
571 IdentifierInfo *Name, SourceLocation NameLoc,
572 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000573 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000574 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000575 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000576 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000577 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000578 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000579
580 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000581 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000582 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000583
John McCall27b5c252009-09-14 21:59:20 +0000584 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
585 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000586
587 // There is no such thing as an unnamed class template.
588 if (!Name) {
589 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000590 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000591 }
592
593 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000594 DeclContext *SemanticContext;
595 LookupResult Previous;
596 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000597 if (RequireCompleteDeclContext(SS))
598 return true;
599
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000600 SemanticContext = computeDeclContext(SS, true);
601 if (!SemanticContext) {
602 // FIXME: Produce a reasonable diagnostic here
603 return true;
604 }
Mike Stump11289f42009-09-09 15:08:12 +0000605
John McCall9f3059a2009-10-09 21:13:30 +0000606 LookupQualifiedName(Previous, SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000607 true);
608 } else {
609 SemanticContext = CurContext;
John McCall9f3059a2009-10-09 21:13:30 +0000610 LookupName(Previous, S, Name, LookupOrdinaryName, true);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000611 }
Mike Stump11289f42009-09-09 15:08:12 +0000612
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000613 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
614 NamedDecl *PrevDecl = 0;
615 if (Previous.begin() != Previous.end())
616 PrevDecl = *Previous.begin();
617
Douglas Gregor9acb6902009-09-26 07:05:09 +0000618 if (PrevDecl && TUK == TUK_Friend) {
619 // C++ [namespace.memdef]p3:
620 // [...] When looking for a prior declaration of a class or a function
621 // declared as a friend, and when the name of the friend class or
622 // function is neither a qualified name nor a template-id, scopes outside
623 // the innermost enclosing namespace scope are not considered.
624 DeclContext *OutermostContext = CurContext;
625 while (!OutermostContext->isFileContext())
626 OutermostContext = OutermostContext->getLookupParent();
627
628 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
629 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
630 SemanticContext = PrevDecl->getDeclContext();
631 } else {
632 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000633 // context we computed is the semantic context for our new
Douglas Gregor9acb6902009-09-26 07:05:09 +0000634 // declaration.
635 PrevDecl = 0;
636 SemanticContext = OutermostContext;
637 }
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000638
639 if (CurContext->isDependentContext()) {
640 // If this is a dependent context, we don't want to link the friend
641 // class template to the template in scope, because that would perform
642 // checking of the template parameter lists that can't be performed
643 // until the outer context is instantiated.
644 PrevDecl = 0;
645 }
Douglas Gregor9acb6902009-09-26 07:05:09 +0000646 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000647 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000648
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000649 // If there is a previous declaration with the same name, check
650 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000651 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000652 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000653
654 // We may have found the injected-class-name of a class template,
655 // class template partial specialization, or class template specialization.
656 // In these cases, grab the template that is being defined or specialized.
657 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
658 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
659 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
660 PrevClassTemplate
661 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
662 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
663 PrevClassTemplate
664 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
665 ->getSpecializedTemplate();
666 }
667 }
668
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000669 if (PrevClassTemplate) {
670 // Ensure that the template parameter lists are compatible.
671 if (!TemplateParameterListsAreEqual(TemplateParams,
672 PrevClassTemplate->getTemplateParameters(),
673 /*Complain=*/true))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000674 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000675
676 // C++ [temp.class]p4:
677 // In a redeclaration, partial specialization, explicit
678 // specialization or explicit instantiation of a class template,
679 // the class-key shall agree in kind with the original class
680 // template declaration (7.1.5.3).
681 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000682 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000683 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000684 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000685 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000686 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000687 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000688 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000689 }
690
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000691 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000692 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000693 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
694 Diag(NameLoc, diag::err_redefinition) << Name;
695 Diag(Def->getLocation(), diag::note_previous_definition);
696 // FIXME: Would it make sense to try to "forget" the previous
697 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000698 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000699 }
700 }
701 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
702 // Maybe we will complain about the shadowed template parameter.
703 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
704 // Just pretend that we didn't see the previous declaration.
705 PrevDecl = 0;
706 } else if (PrevDecl) {
707 // C++ [temp]p5:
708 // A class template shall not have the same name as any other
709 // template, class, function, object, enumeration, enumerator,
710 // namespace, or type in the same scope (3.3), except as specified
711 // in (14.5.4).
712 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
713 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000714 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000715 }
716
Douglas Gregordba32632009-02-10 19:49:53 +0000717 // Check the template parameter list of this declaration, possibly
718 // merging in the template parameter list from the previous class
719 // template declaration.
720 if (CheckTemplateParameterList(TemplateParams,
721 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
722 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000723
Douglas Gregore362cea2009-05-10 22:57:19 +0000724 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000725 // declaration!
726
Mike Stump11289f42009-09-09 15:08:12 +0000727 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000728 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000729 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000730 PrevClassTemplate->getTemplatedDecl() : 0,
731 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000732
733 ClassTemplateDecl *NewTemplate
734 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
735 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000736 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000737 NewClass->setDescribedClassTemplate(NewTemplate);
738
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000739 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000740 QualType T =
741 Context.getTypeDeclType(NewClass,
742 PrevClassTemplate?
743 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000744 assert(T->isDependentType() && "Class template type is not dependent?");
745 (void)T;
746
Douglas Gregorcf915552009-10-13 16:30:37 +0000747 // If we are providing an explicit specialization of a member that is a
748 // class template, make a note of that.
749 if (PrevClassTemplate &&
750 PrevClassTemplate->getInstantiatedFromMemberTemplate())
751 PrevClassTemplate->setMemberSpecialization();
752
Anders Carlsson137108d2009-03-26 01:24:28 +0000753 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000754 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000755 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000756
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000757 // Set the lexical context of these templates
758 NewClass->setLexicalDeclContext(CurContext);
759 NewTemplate->setLexicalDeclContext(CurContext);
760
John McCall9bb74a52009-07-31 02:45:11 +0000761 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000762 NewClass->startDefinition();
763
764 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000765 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000766
John McCall27b5c252009-09-14 21:59:20 +0000767 if (TUK != TUK_Friend)
768 PushOnScopeChains(NewTemplate, S);
769 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000770 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000771 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000772 NewClass->setAccess(PrevClassTemplate->getAccess());
773 }
John McCall27b5c252009-09-14 21:59:20 +0000774
Douglas Gregor3dad8422009-09-26 06:47:28 +0000775 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
776 PrevClassTemplate != NULL);
777
John McCall27b5c252009-09-14 21:59:20 +0000778 // Friend templates are visible in fairly strange ways.
779 if (!CurContext->isDependentContext()) {
780 DeclContext *DC = SemanticContext->getLookupContext();
781 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
782 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
783 PushOnScopeChains(NewTemplate, EnclosingScope,
784 /* AddToContext = */ false);
785 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000786
787 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
788 NewClass->getLocation(),
789 NewTemplate,
790 /*FIXME:*/NewClass->getLocation());
791 Friend->setAccess(AS_public);
792 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000793 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000794
Douglas Gregordba32632009-02-10 19:49:53 +0000795 if (Invalid) {
796 NewTemplate->setInvalidDecl();
797 NewClass->setInvalidDecl();
798 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000799 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000800}
801
Douglas Gregordba32632009-02-10 19:49:53 +0000802/// \brief Checks the validity of a template parameter list, possibly
803/// considering the template parameter list from a previous
804/// declaration.
805///
806/// If an "old" template parameter list is provided, it must be
807/// equivalent (per TemplateParameterListsAreEqual) to the "new"
808/// template parameter list.
809///
810/// \param NewParams Template parameter list for a new template
811/// declaration. This template parameter list will be updated with any
812/// default arguments that are carried through from the previous
813/// template parameter list.
814///
815/// \param OldParams If provided, template parameter list from a
816/// previous declaration of the same template. Default template
817/// arguments will be merged from the old template parameter list to
818/// the new template parameter list.
819///
820/// \returns true if an error occurred, false otherwise.
821bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
822 TemplateParameterList *OldParams) {
823 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000824
Douglas Gregordba32632009-02-10 19:49:53 +0000825 // C++ [temp.param]p10:
826 // The set of default template-arguments available for use with a
827 // template declaration or definition is obtained by merging the
828 // default arguments from the definition (if in scope) and all
829 // declarations in scope in the same way default function
830 // arguments are (8.3.6).
831 bool SawDefaultArgument = false;
832 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000833
Anders Carlsson327865d2009-06-12 23:20:15 +0000834 bool SawParameterPack = false;
835 SourceLocation ParameterPackLoc;
836
Mike Stumpc89c8e32009-02-11 23:03:27 +0000837 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000838 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000839 if (OldParams)
840 OldParam = OldParams->begin();
841
842 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
843 NewParamEnd = NewParams->end();
844 NewParam != NewParamEnd; ++NewParam) {
845 // Variables used to diagnose redundant default arguments
846 bool RedundantDefaultArg = false;
847 SourceLocation OldDefaultLoc;
848 SourceLocation NewDefaultLoc;
849
850 // Variables used to diagnose missing default arguments
851 bool MissingDefaultArg = false;
852
Anders Carlsson327865d2009-06-12 23:20:15 +0000853 // C++0x [temp.param]p11:
854 // If a template parameter of a class template is a template parameter pack,
855 // it must be the last template parameter.
856 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +0000857 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +0000858 diag::err_template_param_pack_must_be_last_template_parameter);
859 Invalid = true;
860 }
861
Douglas Gregordba32632009-02-10 19:49:53 +0000862 // Merge default arguments for template type parameters.
863 if (TemplateTypeParmDecl *NewTypeParm
864 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump11289f42009-09-09 15:08:12 +0000865 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000866 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000867
Anders Carlsson327865d2009-06-12 23:20:15 +0000868 if (NewTypeParm->isParameterPack()) {
869 assert(!NewTypeParm->hasDefaultArgument() &&
870 "Parameter packs can't have a default argument!");
871 SawParameterPack = true;
872 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000873 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +0000874 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +0000875 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
876 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
877 SawDefaultArgument = true;
878 RedundantDefaultArg = true;
879 PreviousDefaultArgLoc = NewDefaultLoc;
880 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
881 // Merge the default argument from the old declaration to the
882 // new declaration.
883 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +0000884 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +0000885 true);
886 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
887 } else if (NewTypeParm->hasDefaultArgument()) {
888 SawDefaultArgument = true;
889 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
890 } else if (SawDefaultArgument)
891 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000892 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000893 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000894 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000895 NonTypeTemplateParmDecl *OldNonTypeParm
896 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000897 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000898 NewNonTypeParm->hasDefaultArgument()) {
899 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
900 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
901 SawDefaultArgument = true;
902 RedundantDefaultArg = true;
903 PreviousDefaultArgLoc = NewDefaultLoc;
904 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
905 // Merge the default argument from the old declaration to the
906 // new declaration.
907 SawDefaultArgument = true;
908 // FIXME: We need to create a new kind of "default argument"
909 // expression that points to a previous template template
910 // parameter.
911 NewNonTypeParm->setDefaultArgument(
912 OldNonTypeParm->getDefaultArgument());
913 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
914 } else if (NewNonTypeParm->hasDefaultArgument()) {
915 SawDefaultArgument = true;
916 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
917 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000918 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000919 } else {
Douglas Gregordba32632009-02-10 19:49:53 +0000920 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000921 TemplateTemplateParmDecl *NewTemplateParm
922 = cast<TemplateTemplateParmDecl>(*NewParam);
923 TemplateTemplateParmDecl *OldTemplateParm
924 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000925 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000926 NewTemplateParm->hasDefaultArgument()) {
927 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
928 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
929 SawDefaultArgument = true;
930 RedundantDefaultArg = true;
931 PreviousDefaultArgLoc = NewDefaultLoc;
932 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
933 // Merge the default argument from the old declaration to the
934 // new declaration.
935 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +0000936 // FIXME: We need to create a new kind of "default argument" expression
937 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +0000938 NewTemplateParm->setDefaultArgument(
939 OldTemplateParm->getDefaultArgument());
940 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
941 } else if (NewTemplateParm->hasDefaultArgument()) {
942 SawDefaultArgument = true;
943 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
944 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000945 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +0000946 }
947
948 if (RedundantDefaultArg) {
949 // C++ [temp.param]p12:
950 // A template-parameter shall not be given default arguments
951 // by two different declarations in the same scope.
952 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
953 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
954 Invalid = true;
955 } else if (MissingDefaultArg) {
956 // C++ [temp.param]p11:
957 // If a template-parameter has a default template-argument,
958 // all subsequent template-parameters shall have a default
959 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +0000960 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +0000961 diag::err_template_param_default_arg_missing);
962 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
963 Invalid = true;
964 }
965
966 // If we have an old template parameter list that we're merging
967 // in, move on to the next parameter.
968 if (OldParams)
969 ++OldParam;
970 }
971
972 return Invalid;
973}
Douglas Gregord32e0282009-02-09 23:23:08 +0000974
Mike Stump11289f42009-09-09 15:08:12 +0000975/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +0000976/// specifier, returning the template parameter list that applies to the
977/// name.
978///
979/// \param DeclStartLoc the start of the declaration that has a scope
980/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +0000981///
Douglas Gregord8d297c2009-07-21 23:53:31 +0000982/// \param SS the scope specifier that will be matched to the given template
983/// parameter lists. This scope specifier precedes a qualified name that is
984/// being declared.
985///
986/// \param ParamLists the template parameter lists, from the outermost to the
987/// innermost template parameter lists.
988///
989/// \param NumParamLists the number of template parameter lists in ParamLists.
990///
Douglas Gregor5c0405d2009-10-07 22:35:40 +0000991/// \param IsExplicitSpecialization will be set true if the entity being
992/// declared is an explicit specialization, false otherwise.
993///
Mike Stump11289f42009-09-09 15:08:12 +0000994/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +0000995/// name that is preceded by the scope specifier @p SS. This template
996/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +0000997/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +0000998/// template specialization), or may be NULL (if we were's declaring isn't
999/// itself a template).
1000TemplateParameterList *
1001Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1002 const CXXScopeSpec &SS,
1003 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001004 unsigned NumParamLists,
1005 bool &IsExplicitSpecialization) {
1006 IsExplicitSpecialization = false;
1007
Douglas Gregord8d297c2009-07-21 23:53:31 +00001008 // Find the template-ids that occur within the nested-name-specifier. These
1009 // template-ids will match up with the template parameter lists.
1010 llvm::SmallVector<const TemplateSpecializationType *, 4>
1011 TemplateIdsInSpecifier;
1012 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1013 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +00001014 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +00001015 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1016 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1017 if (!Template)
1018 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001019
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001020 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001021 ClassTemplateSpecializationDecl *SpecDecl
1022 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1023 // If the nested name specifier refers to an explicit specialization,
1024 // we don't need a template<> header.
Douglas Gregor82e22862009-09-16 00:01:48 +00001025 // FIXME: revisit this approach once we cope with specializations
Douglas Gregor15301382009-07-30 17:40:51 +00001026 // properly.
Douglas Gregord8d297c2009-07-21 23:53:31 +00001027 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
1028 continue;
1029 }
Mike Stump11289f42009-09-09 15:08:12 +00001030
Douglas Gregord8d297c2009-07-21 23:53:31 +00001031 TemplateIdsInSpecifier.push_back(SpecType);
1032 }
1033 }
Mike Stump11289f42009-09-09 15:08:12 +00001034
Douglas Gregord8d297c2009-07-21 23:53:31 +00001035 // Reverse the list of template-ids in the scope specifier, so that we can
1036 // more easily match up the template-ids and the template parameter lists.
1037 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001038
Douglas Gregord8d297c2009-07-21 23:53:31 +00001039 SourceLocation FirstTemplateLoc = DeclStartLoc;
1040 if (NumParamLists)
1041 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001042
Douglas Gregord8d297c2009-07-21 23:53:31 +00001043 // Match the template-ids found in the specifier to the template parameter
1044 // lists.
1045 unsigned Idx = 0;
1046 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1047 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001048 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1049 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001050 if (Idx >= NumParamLists) {
1051 // We have a template-id without a corresponding template parameter
1052 // list.
1053 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001054 // FIXME: the location information here isn't great.
1055 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001056 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001057 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001058 << SS.getRange();
1059 } else {
1060 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1061 << SS.getRange()
1062 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1063 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001064 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001065 }
1066 return 0;
1067 }
Mike Stump11289f42009-09-09 15:08:12 +00001068
Douglas Gregord8d297c2009-07-21 23:53:31 +00001069 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001070 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001071 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001072 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1073
Mike Stump11289f42009-09-09 15:08:12 +00001074 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001075 = dyn_cast<ClassTemplateDecl>(Template)) {
1076 TemplateParameterList *ExpectedTemplateParams = 0;
1077 // Is this template-id naming the primary template?
1078 if (Context.hasSameType(TemplateId,
1079 ClassTemplate->getInjectedClassNameType(Context)))
1080 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1081 // ... or a partial specialization?
1082 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1083 = ClassTemplate->findPartialSpecialization(TemplateId))
1084 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1085
1086 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001087 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001088 ExpectedTemplateParams,
1089 true);
Mike Stump11289f42009-09-09 15:08:12 +00001090 }
Douglas Gregor15301382009-07-30 17:40:51 +00001091 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001092 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001093 diag::err_template_param_list_matches_nontemplate)
1094 << TemplateId
1095 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001096 else
1097 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001098 }
Mike Stump11289f42009-09-09 15:08:12 +00001099
Douglas Gregord8d297c2009-07-21 23:53:31 +00001100 // If there were at least as many template-ids as there were template
1101 // parameter lists, then there are no template parameter lists remaining for
1102 // the declaration itself.
1103 if (Idx >= NumParamLists)
1104 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001105
Douglas Gregord8d297c2009-07-21 23:53:31 +00001106 // If there were too many template parameter lists, complain about that now.
1107 if (Idx != NumParamLists - 1) {
1108 while (Idx < NumParamLists - 1) {
Mike Stump11289f42009-09-09 15:08:12 +00001109 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001110 diag::err_template_spec_extra_headers)
1111 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1112 ParamLists[Idx]->getRAngleLoc());
1113 ++Idx;
1114 }
1115 }
Mike Stump11289f42009-09-09 15:08:12 +00001116
Douglas Gregord8d297c2009-07-21 23:53:31 +00001117 // Return the last template parameter list, which corresponds to the
1118 // entity being declared.
1119 return ParamLists[NumParamLists - 1];
1120}
1121
Douglas Gregorc40290e2009-03-09 23:48:35 +00001122/// \brief Translates template arguments as provided by the parser
1123/// into template arguments used by semantic analysis.
Douglas Gregor0e876e02009-09-25 23:53:26 +00001124void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001125 llvm::SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001126 TemplateArgs.reserve(TemplateArgsIn.size());
1127
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001128 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) {
1129 const ParsedTemplateArgument &Arg = TemplateArgsIn[I];
1130 switch (Arg.getKind()) {
1131 case ParsedTemplateArgument::Type: {
John McCall0ad16662009-10-29 08:12:44 +00001132 DeclaratorInfo *DI;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001133 QualType T = Sema::GetTypeFromParser(Arg.getAsType(), &DI);
1134 if (!DI) DI = Context.getTrivialDeclaratorInfo(T, Arg.getLocation());
John McCall0ad16662009-10-29 08:12:44 +00001135 TemplateArgs.push_back(TemplateArgumentLoc(TemplateArgument(T), DI));
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001136 break;
1137 }
1138
1139 case ParsedTemplateArgument::NonType: {
1140 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00001141 TemplateArgs.push_back(TemplateArgumentLoc(TemplateArgument(E), E));
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001142 break;
1143 }
1144
1145 case ParsedTemplateArgument::Template: {
1146 TemplateName Template
1147 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
1148
1149 // FIXME: This is an egregious hack. We turn a nicely-parsed template name
1150 // into a DeclRefExpr, because that's how we previously parsed template
1151 // template parameters. This will disappear as part of the upcoming
1152 // implementation of template template parameters.
1153 const CXXScopeSpec &SS = Arg.getScopeSpec();
1154 Expr *E = DeclRefExpr::Create(Context,
1155 (NestedNameSpecifier *)SS.getScopeRep(),
1156 SS.getRange(),
1157 Template.getAsTemplateDecl(),
1158 Arg.getLocation(),
1159 Context.DependentTy, false, false);
1160 TemplateArgs.push_back(TemplateArgumentLoc(TemplateArgument(E), E));
1161 }
John McCall0ad16662009-10-29 08:12:44 +00001162 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00001163 }
1164}
1165
Douglas Gregordc572a32009-03-30 22:58:21 +00001166QualType Sema::CheckTemplateIdType(TemplateName Name,
1167 SourceLocation TemplateLoc,
1168 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001169 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregordc572a32009-03-30 22:58:21 +00001170 unsigned NumTemplateArgs,
1171 SourceLocation RAngleLoc) {
1172 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001173 if (!Template) {
1174 // The template name does not resolve to a template, so we just
1175 // build a dependent template-id type.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001176 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001177 NumTemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001178 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001179
Douglas Gregorc40290e2009-03-09 23:48:35 +00001180 // Check that the template argument list is well-formed for this
1181 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001182 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1183 NumTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001184 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001185 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001186 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001187 return QualType();
1188
Mike Stump11289f42009-09-09 15:08:12 +00001189 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001190 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001191 "Converted template argument list is too short!");
1192
1193 QualType CanonType;
1194
Douglas Gregordc572a32009-03-30 22:58:21 +00001195 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorc40290e2009-03-09 23:48:35 +00001196 TemplateArgs,
1197 NumTemplateArgs)) {
1198 // This class template specialization is a dependent
1199 // type. Therefore, its canonical type is another class template
1200 // specialization type that contains all of the converted
1201 // arguments in canonical form. This ensures that, e.g., A<T> and
1202 // A<T, T> have identical types when A is declared as:
1203 //
1204 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001205 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001206 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001207 Converted.getFlatArguments(),
1208 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001209
Douglas Gregora8e02e72009-07-28 23:00:59 +00001210 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001211 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001212 // In the future, we need to teach getTemplateSpecializationType to only
1213 // build the canonical type and return that to us.
1214 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001215 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001216 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001217 // Find the class template specialization declaration that
1218 // corresponds to these arguments.
1219 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001220 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001221 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001222 Converted.flatSize(),
1223 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001224 void *InsertPos = 0;
1225 ClassTemplateSpecializationDecl *Decl
1226 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1227 if (!Decl) {
1228 // This is the first time we have referenced this class template
1229 // specialization. Create the canonical declaration and add it to
1230 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001231 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001232 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001233 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001234 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001235 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001236 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1237 Decl->setLexicalDeclContext(CurContext);
1238 }
1239
1240 CanonType = Context.getTypeDeclType(Decl);
1241 }
Mike Stump11289f42009-09-09 15:08:12 +00001242
Douglas Gregorc40290e2009-03-09 23:48:35 +00001243 // Build the fully-sugared type for this class template
1244 // specialization, which refers back to the class template
1245 // specialization we created or found.
Douglas Gregordc572a32009-03-30 22:58:21 +00001246 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1247 NumTemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001248}
1249
Douglas Gregor67a65642009-02-17 23:15:12 +00001250Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001251Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001252 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001253 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001254 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001255 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001256
Douglas Gregorc40290e2009-03-09 23:48:35 +00001257 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00001258 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001259 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001260
Douglas Gregordc572a32009-03-30 22:58:21 +00001261 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +00001262 TemplateArgs.data(),
1263 TemplateArgs.size(),
Douglas Gregordc572a32009-03-30 22:58:21 +00001264 RAngleLoc);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001265 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001266
1267 if (Result.isNull())
1268 return true;
1269
John McCall0ad16662009-10-29 08:12:44 +00001270 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1271 TemplateSpecializationTypeLoc TL
1272 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1273 TL.setTemplateNameLoc(TemplateLoc);
1274 TL.setLAngleLoc(LAngleLoc);
1275 TL.setRAngleLoc(RAngleLoc);
1276 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1277 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1278
1279 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001280}
John McCall06f6fe8d2009-09-04 01:14:41 +00001281
John McCalld8fe9af2009-09-08 17:47:29 +00001282Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1283 TagUseKind TUK,
1284 DeclSpec::TST TagSpec,
1285 SourceLocation TagLoc) {
1286 if (TypeResult.isInvalid())
1287 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001288
John McCall0ad16662009-10-29 08:12:44 +00001289 // FIXME: preserve source info, ideally without copying the DI.
1290 DeclaratorInfo *DI;
1291 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001292
John McCalld8fe9af2009-09-08 17:47:29 +00001293 // Verify the tag specifier.
1294 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001295
John McCalld8fe9af2009-09-08 17:47:29 +00001296 if (const RecordType *RT = Type->getAs<RecordType>()) {
1297 RecordDecl *D = RT->getDecl();
1298
1299 IdentifierInfo *Id = D->getIdentifier();
1300 assert(Id && "templated class must have an identifier");
1301
1302 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1303 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001304 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001305 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1306 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001307 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001308 }
1309 }
1310
John McCalld8fe9af2009-09-08 17:47:29 +00001311 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1312
1313 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001314}
1315
Douglas Gregord019ff62009-10-22 17:20:55 +00001316Sema::OwningExprResult Sema::BuildTemplateIdExpr(NestedNameSpecifier *Qualifier,
1317 SourceRange QualifierRange,
1318 TemplateName Template,
Douglas Gregora727cb92009-06-30 22:34:41 +00001319 SourceLocation TemplateNameLoc,
1320 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001321 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001322 unsigned NumTemplateArgs,
1323 SourceLocation RAngleLoc) {
1324 // FIXME: Can we do any checking at this point? I guess we could check the
1325 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001326 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001327 // though.
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001328
1329 // Cope with an implicit member access in a C++ non-static member function.
1330 NamedDecl *D = Template.getAsTemplateDecl();
1331 if (!D)
1332 D = Template.getAsOverloadedFunctionDecl();
1333
Douglas Gregord019ff62009-10-22 17:20:55 +00001334 CXXScopeSpec SS;
1335 SS.setRange(QualifierRange);
1336 SS.setScopeRep(Qualifier);
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001337 QualType ThisType, MemberType;
Douglas Gregord019ff62009-10-22 17:20:55 +00001338 if (D && isImplicitMemberReference(&SS, D, TemplateNameLoc,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001339 ThisType, MemberType)) {
1340 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
1341 return Owned(MemberExpr::Create(Context, This, true,
Douglas Gregord019ff62009-10-22 17:20:55 +00001342 Qualifier, QualifierRange,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001343 D, TemplateNameLoc, true,
1344 LAngleLoc, TemplateArgs,
1345 NumTemplateArgs, RAngleLoc,
1346 Context.OverloadTy));
1347 }
1348
Douglas Gregord019ff62009-10-22 17:20:55 +00001349 return Owned(TemplateIdRefExpr::Create(Context, Context.OverloadTy,
1350 Qualifier, QualifierRange,
Douglas Gregora727cb92009-06-30 22:34:41 +00001351 Template, TemplateNameLoc, LAngleLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001352 TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001353 NumTemplateArgs, RAngleLoc));
1354}
1355
Douglas Gregord019ff62009-10-22 17:20:55 +00001356Sema::OwningExprResult Sema::ActOnTemplateIdExpr(const CXXScopeSpec &SS,
1357 TemplateTy TemplateD,
Douglas Gregora727cb92009-06-30 22:34:41 +00001358 SourceLocation TemplateNameLoc,
1359 SourceLocation LAngleLoc,
1360 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora727cb92009-06-30 22:34:41 +00001361 SourceLocation RAngleLoc) {
1362 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001363
Douglas Gregora727cb92009-06-30 22:34:41 +00001364 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00001365 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001366 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001367 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001368
Douglas Gregord019ff62009-10-22 17:20:55 +00001369 return BuildTemplateIdExpr((NestedNameSpecifier *)SS.getScopeRep(),
1370 SS.getRange(),
1371 Template, TemplateNameLoc, LAngleLoc,
Douglas Gregora727cb92009-06-30 22:34:41 +00001372 TemplateArgs.data(), TemplateArgs.size(),
1373 RAngleLoc);
1374}
1375
Douglas Gregorb67535d2009-03-31 00:43:58 +00001376/// \brief Form a dependent template name.
1377///
1378/// This action forms a dependent template name given the template
1379/// name and its (presumably dependent) scope specifier. For
1380/// example, given "MetaFun::template apply", the scope specifier \p
1381/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1382/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001383Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001384Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001385 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001386 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001387 TypeTy *ObjectType) {
Mike Stump11289f42009-09-09 15:08:12 +00001388 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001389 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1390 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001391 // C++0x [temp.names]p5:
1392 // If a name prefixed by the keyword template is not the name of
1393 // a template, the program is ill-formed. [Note: the keyword
1394 // template may not be applied to non-template members of class
1395 // templates. -end note ] [ Note: as is the case with the
1396 // typename prefix, the template prefix is allowed in cases
1397 // where it is not strictly necessary; i.e., when the
1398 // nested-name-specifier or the expression on the left of the ->
1399 // or . is not dependent on a template-parameter, or the use
1400 // does not appear in the scope of a template. -end note]
1401 //
1402 // Note: C++03 was more strict here, because it banned the use of
1403 // the "template" keyword prior to a template-name that was not a
1404 // dependent name. C++ DR468 relaxed this requirement (the
1405 // "template" keyword is now permitted). We follow the C++0x
1406 // rules, even in C++03 mode, retroactively applying the DR.
1407 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001408 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001409 false, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001410 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001411 Diag(Name.getSourceRange().getBegin(),
1412 diag::err_template_kw_refers_to_non_template)
1413 << GetNameFromUnqualifiedId(Name)
1414 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001415 return TemplateTy();
1416 }
1417
1418 return Template;
1419 }
1420
Mike Stump11289f42009-09-09 15:08:12 +00001421 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001422 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001423
1424 switch (Name.getKind()) {
1425 case UnqualifiedId::IK_Identifier:
1426 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1427 Name.Identifier));
1428
Douglas Gregor71395fa2009-11-04 00:56:37 +00001429 case UnqualifiedId::IK_OperatorFunctionId:
1430 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1431 Name.OperatorFunctionId.Operator));
1432
Douglas Gregor3cf81312009-11-03 23:16:33 +00001433 default:
1434 break;
1435 }
1436
1437 Diag(Name.getSourceRange().getBegin(),
1438 diag::err_template_kw_refers_to_non_template)
1439 << GetNameFromUnqualifiedId(Name)
1440 << Name.getSourceRange();
1441 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001442}
1443
Mike Stump11289f42009-09-09 15:08:12 +00001444bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001445 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001446 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001447 const TemplateArgument &Arg = AL.getArgument();
1448
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001449 // Check template type parameter.
1450 if (Arg.getKind() != TemplateArgument::Type) {
1451 // C++ [temp.arg.type]p1:
1452 // A template-argument for a template-parameter which is a
1453 // type shall be a type-id.
1454
1455 // We have a template type parameter but the template argument
1456 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001457 SourceRange SR = AL.getSourceRange();
1458 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001459 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001460
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001461 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001462 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001463
John McCall0ad16662009-10-29 08:12:44 +00001464 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001465 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001466
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001467 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001468 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001469 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001470 return false;
1471}
1472
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001473/// \brief Substitute template arguments into the default template argument for
1474/// the given template type parameter.
1475///
1476/// \param SemaRef the semantic analysis object for which we are performing
1477/// the substitution.
1478///
1479/// \param Template the template that we are synthesizing template arguments
1480/// for.
1481///
1482/// \param TemplateLoc the location of the template name that started the
1483/// template-id we are checking.
1484///
1485/// \param RAngleLoc the location of the right angle bracket ('>') that
1486/// terminates the template-id.
1487///
1488/// \param Param the template template parameter whose default we are
1489/// substituting into.
1490///
1491/// \param Converted the list of template arguments provided for template
1492/// parameters that precede \p Param in the template parameter list.
1493///
1494/// \returns the substituted template argument, or NULL if an error occurred.
1495static DeclaratorInfo *
1496SubstDefaultTemplateArgument(Sema &SemaRef,
1497 TemplateDecl *Template,
1498 SourceLocation TemplateLoc,
1499 SourceLocation RAngleLoc,
1500 TemplateTypeParmDecl *Param,
1501 TemplateArgumentListBuilder &Converted) {
1502 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1503
1504 // If the argument type is dependent, instantiate it now based
1505 // on the previously-computed template arguments.
1506 if (ArgType->getType()->isDependentType()) {
1507 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1508 /*TakeArgs=*/false);
1509
1510 MultiLevelTemplateArgumentList AllTemplateArgs
1511 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1512
1513 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1514 Template, Converted.getFlatArguments(),
1515 Converted.flatSize(),
1516 SourceRange(TemplateLoc, RAngleLoc));
1517
1518 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1519 Param->getDefaultArgumentLoc(),
1520 Param->getDeclName());
1521 }
1522
1523 return ArgType;
1524}
1525
1526/// \brief Substitute template arguments into the default template argument for
1527/// the given non-type template parameter.
1528///
1529/// \param SemaRef the semantic analysis object for which we are performing
1530/// the substitution.
1531///
1532/// \param Template the template that we are synthesizing template arguments
1533/// for.
1534///
1535/// \param TemplateLoc the location of the template name that started the
1536/// template-id we are checking.
1537///
1538/// \param RAngleLoc the location of the right angle bracket ('>') that
1539/// terminates the template-id.
1540///
1541/// \param Param the template template parameter whose default we are
1542/// substituting into.
1543///
1544/// \param Converted the list of template arguments provided for template
1545/// parameters that precede \p Param in the template parameter list.
1546///
1547/// \returns the substituted template argument, or NULL if an error occurred.
1548static Sema::OwningExprResult
1549SubstDefaultTemplateArgument(Sema &SemaRef,
1550 TemplateDecl *Template,
1551 SourceLocation TemplateLoc,
1552 SourceLocation RAngleLoc,
1553 NonTypeTemplateParmDecl *Param,
1554 TemplateArgumentListBuilder &Converted) {
1555 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1556 /*TakeArgs=*/false);
1557
1558 MultiLevelTemplateArgumentList AllTemplateArgs
1559 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1560
1561 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1562 Template, Converted.getFlatArguments(),
1563 Converted.flatSize(),
1564 SourceRange(TemplateLoc, RAngleLoc));
1565
1566 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1567}
1568
Douglas Gregord32e0282009-02-09 23:23:08 +00001569/// \brief Check that the given template argument list is well-formed
1570/// for specializing the given template.
1571bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1572 SourceLocation TemplateLoc,
1573 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001574 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001575 unsigned NumTemplateArgs,
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001576 SourceLocation RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001577 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001578 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001579 TemplateParameterList *Params = Template->getTemplateParameters();
1580 unsigned NumParams = Params->size();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001581 unsigned NumArgs = NumTemplateArgs;
Douglas Gregord32e0282009-02-09 23:23:08 +00001582 bool Invalid = false;
1583
Mike Stump11289f42009-09-09 15:08:12 +00001584 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001585 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001586
Anders Carlsson15201f12009-06-13 02:08:00 +00001587 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001588 (NumArgs < Params->getMinRequiredArguments() &&
1589 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001590 // FIXME: point at either the first arg beyond what we can handle,
1591 // or the '>', depending on whether we have too many or too few
1592 // arguments.
1593 SourceRange Range;
1594 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001595 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001596 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1597 << (NumArgs > NumParams)
1598 << (isa<ClassTemplateDecl>(Template)? 0 :
1599 isa<FunctionTemplateDecl>(Template)? 1 :
1600 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1601 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001602 Diag(Template->getLocation(), diag::note_template_decl_here)
1603 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001604 Invalid = true;
1605 }
Mike Stump11289f42009-09-09 15:08:12 +00001606
1607 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001608 // [...] The type and form of each template-argument specified in
1609 // a template-id shall match the type and form specified for the
1610 // corresponding parameter declared by the template in its
1611 // template-parameter-list.
1612 unsigned ArgIdx = 0;
1613 for (TemplateParameterList::iterator Param = Params->begin(),
1614 ParamEnd = Params->end();
1615 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001616 if (ArgIdx > NumArgs && PartialTemplateArgs)
1617 break;
Mike Stump11289f42009-09-09 15:08:12 +00001618
Douglas Gregord32e0282009-02-09 23:23:08 +00001619 // Decode the template argument
John McCall0ad16662009-10-29 08:12:44 +00001620 TemplateArgumentLoc Arg;
1621
Douglas Gregord32e0282009-02-09 23:23:08 +00001622 if (ArgIdx >= NumArgs) {
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001623 // Retrieve the default template argument from the template
1624 // parameter.
1625 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001626 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001627 // We have an empty argument pack.
1628 Converted.BeginPack();
1629 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001630 break;
1631 }
Mike Stump11289f42009-09-09 15:08:12 +00001632
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001633 if (!TTP->hasDefaultArgument())
1634 break;
1635
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001636 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
1637 Template,
1638 TemplateLoc,
1639 RAngleLoc,
1640 TTP,
1641 Converted);
John McCall0ad16662009-10-29 08:12:44 +00001642 if (!ArgType)
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001643 return true;
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001644
1645 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
1646 ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001647 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001648 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1649 if (!NTTP->hasDefaultArgument())
1650 break;
1651
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001652 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
1653 TemplateLoc,
1654 RAngleLoc,
1655 NTTP,
1656 Converted);
Anders Carlsson40ed3442009-06-11 16:06:49 +00001657 if (E.isInvalid())
1658 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001659
John McCall0ad16662009-10-29 08:12:44 +00001660 Expr *Ex = E.takeAs<Expr>();
1661 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001662 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001663 TemplateTemplateParmDecl *TempParm
1664 = cast<TemplateTemplateParmDecl>(*Param);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001665
1666 if (!TempParm->hasDefaultArgument())
1667 break;
1668
John McCall76d824f2009-08-25 22:02:44 +00001669 // FIXME: Subst default argument
John McCall0d07eb32009-10-29 18:45:58 +00001670 Arg = TemplateArgumentLoc(TemplateArgument(TempParm->getDefaultArgument()),
1671 TempParm->getDefaultArgument());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001672 }
1673 } else {
1674 // Retrieve the template argument produced by the user.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001675 Arg = TemplateArgs[ArgIdx];
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001676 }
1677
Douglas Gregord32e0282009-02-09 23:23:08 +00001678
1679 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001680 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001681 Converted.BeginPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001682 // Check all the remaining arguments (if any).
1683 for (; ArgIdx < NumArgs; ++ArgIdx) {
1684 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1685 Invalid = true;
1686 }
Mike Stump11289f42009-09-09 15:08:12 +00001687
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001688 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001689 } else {
1690 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1691 Invalid = true;
1692 }
Mike Stump11289f42009-09-09 15:08:12 +00001693 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord32e0282009-02-09 23:23:08 +00001694 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1695 // Check non-type template parameters.
Douglas Gregor463421d2009-03-03 04:44:36 +00001696
John McCall76d824f2009-08-25 22:02:44 +00001697 // Do substitution on the type of the non-type template parameter
1698 // with the template arguments we've seen thus far.
Douglas Gregor463421d2009-03-03 04:44:36 +00001699 QualType NTTPType = NTTP->getType();
1700 if (NTTPType->isDependentType()) {
John McCall76d824f2009-08-25 22:02:44 +00001701 // Do substitution on the type of the non-type template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001702 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001703 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001704 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001705 SourceRange(TemplateLoc, RAngleLoc));
1706
Anders Carlssonc8e71132009-06-05 04:47:51 +00001707 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001708 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001709 NTTPType = SubstType(NTTPType,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00001710 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001711 NTTP->getLocation(),
1712 NTTP->getDeclName());
Douglas Gregor463421d2009-03-03 04:44:36 +00001713 // If that worked, check the non-type template parameter type
1714 // for validity.
1715 if (!NTTPType.isNull())
Mike Stump11289f42009-09-09 15:08:12 +00001716 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
Douglas Gregor463421d2009-03-03 04:44:36 +00001717 NTTP->getLocation());
Douglas Gregor463421d2009-03-03 04:44:36 +00001718 if (NTTPType.isNull()) {
1719 Invalid = true;
1720 break;
1721 }
1722 }
1723
John McCall0ad16662009-10-29 08:12:44 +00001724 switch (Arg.getArgument().getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001725 case TemplateArgument::Null:
1726 assert(false && "Should never see a NULL template argument here");
1727 break;
Mike Stump11289f42009-09-09 15:08:12 +00001728
Douglas Gregorc40290e2009-03-09 23:48:35 +00001729 case TemplateArgument::Expression: {
John McCall0ad16662009-10-29 08:12:44 +00001730 Expr *E = Arg.getArgument().getAsExpr();
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001731 TemplateArgument Result;
1732 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregord32e0282009-02-09 23:23:08 +00001733 Invalid = true;
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001734 else
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001735 Converted.Append(Result);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001736 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001737 }
1738
Douglas Gregorc40290e2009-03-09 23:48:35 +00001739 case TemplateArgument::Declaration:
1740 case TemplateArgument::Integral:
1741 // We've already checked this template argument, so just copy
1742 // it to the list of converted arguments.
John McCall0ad16662009-10-29 08:12:44 +00001743 Converted.Append(Arg.getArgument());
Douglas Gregorc40290e2009-03-09 23:48:35 +00001744 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001745
John McCall0ad16662009-10-29 08:12:44 +00001746 case TemplateArgument::Type: {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001747 // We have a non-type template parameter but the template
1748 // argument is a type.
Mike Stump11289f42009-09-09 15:08:12 +00001749
Douglas Gregorc40290e2009-03-09 23:48:35 +00001750 // C++ [temp.arg]p2:
1751 // In a template-argument, an ambiguity between a type-id and
1752 // an expression is resolved to a type-id, regardless of the
1753 // form of the corresponding template-parameter.
1754 //
1755 // We warn specifically about this case, since it can be rather
1756 // confusing for users.
John McCall0ad16662009-10-29 08:12:44 +00001757 QualType T = Arg.getArgument().getAsType();
John McCall0d07eb32009-10-29 18:45:58 +00001758 SourceRange SR = Arg.getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00001759 if (T->isFunctionType())
John McCall0d07eb32009-10-29 18:45:58 +00001760 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig)
1761 << SR << T;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001762 else
John McCall0d07eb32009-10-29 18:45:58 +00001763 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001764 Diag((*Param)->getLocation(), diag::note_template_param_here);
1765 Invalid = true;
Anders Carlssonbc343912009-06-15 17:04:53 +00001766 break;
John McCall0ad16662009-10-29 08:12:44 +00001767 }
Mike Stump11289f42009-09-09 15:08:12 +00001768
Anders Carlssonbc343912009-06-15 17:04:53 +00001769 case TemplateArgument::Pack:
1770 assert(0 && "FIXME: Implement!");
1771 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001772 }
Mike Stump11289f42009-09-09 15:08:12 +00001773 } else {
Douglas Gregord32e0282009-02-09 23:23:08 +00001774 // Check template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001775 TemplateTemplateParmDecl *TempParm
Douglas Gregord32e0282009-02-09 23:23:08 +00001776 = cast<TemplateTemplateParmDecl>(*Param);
Mike Stump11289f42009-09-09 15:08:12 +00001777
John McCall0ad16662009-10-29 08:12:44 +00001778 switch (Arg.getArgument().getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001779 case TemplateArgument::Null:
1780 assert(false && "Should never see a NULL template argument here");
1781 break;
Mike Stump11289f42009-09-09 15:08:12 +00001782
Douglas Gregorc40290e2009-03-09 23:48:35 +00001783 case TemplateArgument::Expression: {
John McCall0ad16662009-10-29 08:12:44 +00001784 Expr *ArgExpr = Arg.getArgument().getAsExpr();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001785 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1786 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1787 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1788 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001789
Douglas Gregorc40290e2009-03-09 23:48:35 +00001790 // Add the converted template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001791 Decl *D
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00001792 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
John McCall0ad16662009-10-29 08:12:44 +00001793 Converted.Append(TemplateArgument(D));
Douglas Gregorc40290e2009-03-09 23:48:35 +00001794 continue;
1795 }
1796 }
1797 // fall through
Mike Stump11289f42009-09-09 15:08:12 +00001798
Douglas Gregorc40290e2009-03-09 23:48:35 +00001799 case TemplateArgument::Type: {
1800 // We have a template template parameter but the template
1801 // argument does not refer to a template.
1802 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1803 Invalid = true;
1804 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001805 }
1806
Douglas Gregorc40290e2009-03-09 23:48:35 +00001807 case TemplateArgument::Declaration:
1808 // We've already checked this template argument, so just copy
1809 // it to the list of converted arguments.
John McCall0ad16662009-10-29 08:12:44 +00001810 Converted.Append(Arg.getArgument());
Douglas Gregorc40290e2009-03-09 23:48:35 +00001811 break;
Mike Stump11289f42009-09-09 15:08:12 +00001812
Douglas Gregorc40290e2009-03-09 23:48:35 +00001813 case TemplateArgument::Integral:
1814 assert(false && "Integral argument with template template parameter");
1815 break;
Mike Stump11289f42009-09-09 15:08:12 +00001816
Anders Carlssonbc343912009-06-15 17:04:53 +00001817 case TemplateArgument::Pack:
1818 assert(0 && "FIXME: Implement!");
1819 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001820 }
Douglas Gregord32e0282009-02-09 23:23:08 +00001821 }
1822 }
1823
1824 return Invalid;
1825}
1826
1827/// \brief Check a template argument against its corresponding
1828/// template type parameter.
1829///
1830/// This routine implements the semantics of C++ [temp.arg.type]. It
1831/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001832bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001833 DeclaratorInfo *ArgInfo) {
1834 assert(ArgInfo && "invalid DeclaratorInfo");
1835 QualType Arg = ArgInfo->getType();
1836
Douglas Gregord32e0282009-02-09 23:23:08 +00001837 // C++ [temp.arg.type]p2:
1838 // A local type, a type with no linkage, an unnamed type or a type
1839 // compounded from any of these types shall not be used as a
1840 // template-argument for a template type-parameter.
1841 //
1842 // FIXME: Perform the recursive and no-linkage type checks.
1843 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001844 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001845 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001846 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001847 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00001848 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
1849 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1850 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
1851 << QualType(Tag, 0) << SR;
1852 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001853 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00001854 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1855 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00001856 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1857 return true;
1858 }
1859
1860 return false;
1861}
1862
Douglas Gregorccb07762009-02-11 19:52:55 +00001863/// \brief Checks whether the given template argument is the address
1864/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001865bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1866 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001867 bool Invalid = false;
1868
1869 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00001870 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00001871 Arg = Cast->getSubExpr();
1872
Sebastian Redl576fd422009-05-10 18:38:11 +00001873 // C++0x allows nullptr, and there's no further checking to be done for that.
1874 if (Arg->getType()->isNullPtrType())
1875 return false;
1876
Douglas Gregorccb07762009-02-11 19:52:55 +00001877 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001878 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001879 // A template-argument for a non-type, non-template
1880 // template-parameter shall be one of: [...]
1881 //
1882 // -- the address of an object or function with external
1883 // linkage, including function templates and function
1884 // template-ids but excluding non-static class members,
1885 // expressed as & id-expression where the & is optional if
1886 // the name refers to a function or array, or if the
1887 // corresponding template-parameter is a reference; or
1888 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001889
Douglas Gregorccb07762009-02-11 19:52:55 +00001890 // Ignore (and complain about) any excess parentheses.
1891 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1892 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001893 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001894 diag::err_template_arg_extra_parens)
1895 << Arg->getSourceRange();
1896 Invalid = true;
1897 }
1898
1899 Arg = Parens->getSubExpr();
1900 }
1901
1902 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1903 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1904 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1905 } else
1906 DRE = dyn_cast<DeclRefExpr>(Arg);
1907
1908 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00001909 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001910 diag::err_template_arg_not_object_or_func_form)
1911 << Arg->getSourceRange();
1912
1913 // Cannot refer to non-static data members
1914 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1915 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1916 << Field << Arg->getSourceRange();
1917
1918 // Cannot refer to non-static member functions
1919 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1920 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00001921 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001922 diag::err_template_arg_method)
1923 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001924
Douglas Gregorccb07762009-02-11 19:52:55 +00001925 // Functions must have external linkage.
1926 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1927 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00001928 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001929 diag::err_template_arg_function_not_extern)
1930 << Func << Arg->getSourceRange();
1931 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1932 << true;
1933 return true;
1934 }
1935
1936 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001937 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00001938 return Invalid;
1939 }
1940
1941 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1942 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00001943 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001944 diag::err_template_arg_object_not_extern)
1945 << Var << Arg->getSourceRange();
1946 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1947 << true;
1948 return true;
1949 }
1950
1951 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001952 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00001953 return Invalid;
1954 }
Mike Stump11289f42009-09-09 15:08:12 +00001955
Douglas Gregorccb07762009-02-11 19:52:55 +00001956 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001957 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001958 diag::err_template_arg_not_object_or_func)
1959 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001960 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001961 diag::note_template_arg_refers_here);
1962 return true;
1963}
1964
1965/// \brief Checks whether the given template argument is a pointer to
1966/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump11289f42009-09-09 15:08:12 +00001967bool
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001968Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001969 bool Invalid = false;
1970
1971 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00001972 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00001973 Arg = Cast->getSubExpr();
1974
Sebastian Redl576fd422009-05-10 18:38:11 +00001975 // C++0x allows nullptr, and there's no further checking to be done for that.
1976 if (Arg->getType()->isNullPtrType())
1977 return false;
1978
Douglas Gregorccb07762009-02-11 19:52:55 +00001979 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001980 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001981 // A template-argument for a non-type, non-template
1982 // template-parameter shall be one of: [...]
1983 //
1984 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00001985 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00001986
1987 // Ignore (and complain about) any excess parentheses.
1988 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1989 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001990 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001991 diag::err_template_arg_extra_parens)
1992 << Arg->getSourceRange();
1993 Invalid = true;
1994 }
1995
1996 Arg = Parens->getSubExpr();
1997 }
1998
1999 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002000 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2001 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2002 if (DRE && !DRE->getQualifier())
2003 DRE = 0;
2004 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002005
2006 if (!DRE)
2007 return Diag(Arg->getSourceRange().getBegin(),
2008 diag::err_template_arg_not_pointer_to_member_form)
2009 << Arg->getSourceRange();
2010
2011 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2012 assert((isa<FieldDecl>(DRE->getDecl()) ||
2013 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2014 "Only non-static member pointers can make it here");
2015
2016 // Okay: this is the address of a non-static member, and therefore
2017 // a member pointer constant.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002018 Member = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00002019 return Invalid;
2020 }
2021
2022 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002023 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002024 diag::err_template_arg_not_pointer_to_member_form)
2025 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002026 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002027 diag::note_template_arg_refers_here);
2028 return true;
2029}
2030
Douglas Gregord32e0282009-02-09 23:23:08 +00002031/// \brief Check a template argument against its corresponding
2032/// non-type template parameter.
2033///
Douglas Gregor463421d2009-03-03 04:44:36 +00002034/// This routine implements the semantics of C++ [temp.arg.nontype].
2035/// It returns true if an error occurred, and false otherwise. \p
2036/// InstantiatedParamType is the type of the non-type template
2037/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002038///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002039/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002040bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002041 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002042 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002043 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2044
Douglas Gregor86560402009-02-10 23:36:10 +00002045 // If either the parameter has a dependent type or the argument is
2046 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002047 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002048 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2049 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002050 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002051 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002052 }
Douglas Gregor86560402009-02-10 23:36:10 +00002053
2054 // C++ [temp.arg.nontype]p5:
2055 // The following conversions are performed on each expression used
2056 // as a non-type template-argument. If a non-type
2057 // template-argument cannot be converted to the type of the
2058 // corresponding template-parameter then the program is
2059 // ill-formed.
2060 //
2061 // -- for a non-type template-parameter of integral or
2062 // enumeration type, integral promotions (4.5) and integral
2063 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002064 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002065 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002066 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002067 // C++ [temp.arg.nontype]p1:
2068 // A template-argument for a non-type, non-template
2069 // template-parameter shall be one of:
2070 //
2071 // -- an integral constant-expression of integral or enumeration
2072 // type; or
2073 // -- the name of a non-type template-parameter; or
2074 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002075 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002076 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002077 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002078 diag::err_template_arg_not_integral_or_enumeral)
2079 << ArgType << Arg->getSourceRange();
2080 Diag(Param->getLocation(), diag::note_template_param_here);
2081 return true;
2082 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002083 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002084 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2085 << ArgType << Arg->getSourceRange();
2086 return true;
2087 }
2088
2089 // FIXME: We need some way to more easily get the unqualified form
2090 // of the types without going all the way to the
2091 // canonical type.
2092 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2093 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2094 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2095 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2096
2097 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002098 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002099 // Okay: no conversion necessary
2100 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2101 !ParamType->isEnumeralType()) {
2102 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002103 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002104 } else {
2105 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002106 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002107 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002108 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002109 Diag(Param->getLocation(), diag::note_template_param_here);
2110 return true;
2111 }
2112
Douglas Gregor52aba872009-03-14 00:20:21 +00002113 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002114 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002115 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002116
2117 if (!Arg->isValueDependent()) {
2118 // Check that an unsigned parameter does not receive a negative
2119 // value.
2120 if (IntegerType->isUnsignedIntegerType()
2121 && (Value.isSigned() && Value.isNegative())) {
2122 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2123 << Value.toString(10) << Param->getType()
2124 << Arg->getSourceRange();
2125 Diag(Param->getLocation(), diag::note_template_param_here);
2126 return true;
2127 }
2128
2129 // Check that we don't overflow the template parameter type.
2130 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2131 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002132 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002133 diag::err_template_arg_too_large)
2134 << Value.toString(10) << Param->getType()
2135 << Arg->getSourceRange();
2136 Diag(Param->getLocation(), diag::note_template_param_here);
2137 return true;
2138 }
2139
2140 if (Value.getBitWidth() != AllowedBits)
2141 Value.extOrTrunc(AllowedBits);
2142 Value.setIsSigned(IntegerType->isSignedIntegerType());
2143 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002144
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002145 // Add the value of this argument to the list of converted
2146 // arguments. We use the bitwidth and signedness of the template
2147 // parameter.
2148 if (Arg->isValueDependent()) {
2149 // The argument is value-dependent. Create a new
2150 // TemplateArgument with the converted expression.
2151 Converted = TemplateArgument(Arg);
2152 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002153 }
2154
John McCall0ad16662009-10-29 08:12:44 +00002155 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002156 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002157 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002158 return false;
2159 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002160
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002161 // Handle pointer-to-function, reference-to-function, and
2162 // pointer-to-member-function all in (roughly) the same way.
2163 if (// -- For a non-type template-parameter of type pointer to
2164 // function, only the function-to-pointer conversion (4.3) is
2165 // applied. If the template-argument represents a set of
2166 // overloaded functions (or a pointer to such), the matching
2167 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002168 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002169 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002170 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002171 // -- For a non-type template-parameter of type reference to
2172 // function, no conversions apply. If the template-argument
2173 // represents a set of overloaded functions, the matching
2174 // function is selected from the set (13.4).
2175 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002176 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002177 // -- For a non-type template-parameter of type pointer to
2178 // member function, no conversions apply. If the
2179 // template-argument represents a set of overloaded member
2180 // functions, the matching member function is selected from
2181 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002182 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002183 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002184 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002185 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002186 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002187 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002188 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002189 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2190 ParamType->isMemberPointerType())) {
2191 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002192 if (ParamType->isMemberPointerType())
2193 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2194 else
2195 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002196 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002197 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002198 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002199 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002200 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002201 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2202 return true;
2203
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002204 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002205 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002206 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002207 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002208 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002209 }
2210 }
2211
Mike Stump11289f42009-09-09 15:08:12 +00002212 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002213 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002214 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002215 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002216 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002217 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002218 Diag(Param->getLocation(), diag::note_template_param_here);
2219 return true;
2220 }
Mike Stump11289f42009-09-09 15:08:12 +00002221
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002222 if (ParamType->isMemberPointerType()) {
2223 NamedDecl *Member = 0;
2224 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2225 return true;
2226
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002227 if (Member)
2228 Member = cast<NamedDecl>(Member->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002229 Converted = TemplateArgument(Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002230 return false;
2231 }
Mike Stump11289f42009-09-09 15:08:12 +00002232
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002233 NamedDecl *Entity = 0;
2234 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2235 return true;
2236
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002237 if (Entity)
2238 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002239 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002240 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002241 }
2242
Chris Lattner696197c2009-02-20 21:37:53 +00002243 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002244 // -- for a non-type template-parameter of type pointer to
2245 // object, qualification conversions (4.4) and the
2246 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002247 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002248 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002249 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002250
Sebastian Redl576fd422009-05-10 18:38:11 +00002251 if (ArgType->isNullPtrType()) {
2252 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002253 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002254 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002255 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002256 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002257 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002258
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002259 if (IsQualificationConversion(ArgType, ParamType)) {
2260 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002261 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002262 }
Mike Stump11289f42009-09-09 15:08:12 +00002263
Douglas Gregor1515f762009-02-11 18:22:40 +00002264 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002265 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002266 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002267 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002268 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002269 Diag(Param->getLocation(), diag::note_template_param_here);
2270 return true;
2271 }
Mike Stump11289f42009-09-09 15:08:12 +00002272
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002273 NamedDecl *Entity = 0;
2274 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2275 return true;
2276
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002277 if (Entity)
2278 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002279 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002280 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002281 }
Mike Stump11289f42009-09-09 15:08:12 +00002282
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002283 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002284 // -- For a non-type template-parameter of type reference to
2285 // object, no conversions apply. The type referred to by the
2286 // reference may be more cv-qualified than the (otherwise
2287 // identical) type of the template-argument. The
2288 // template-parameter is bound directly to the
2289 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002290 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002291 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002292
Douglas Gregor1515f762009-02-11 18:22:40 +00002293 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002294 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002295 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002296 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002297 << Arg->getSourceRange();
2298 Diag(Param->getLocation(), diag::note_template_param_here);
2299 return true;
2300 }
2301
Mike Stump11289f42009-09-09 15:08:12 +00002302 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002303 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2304 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002305
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002306 if ((ParamQuals | ArgQuals) != ParamQuals) {
2307 Diag(Arg->getSourceRange().getBegin(),
2308 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002309 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002310 << Arg->getSourceRange();
2311 Diag(Param->getLocation(), diag::note_template_param_here);
2312 return true;
2313 }
Mike Stump11289f42009-09-09 15:08:12 +00002314
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002315 NamedDecl *Entity = 0;
2316 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2317 return true;
2318
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002319 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002320 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002321 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002322 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002323
2324 // -- For a non-type template-parameter of type pointer to data
2325 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002326 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002327 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2328
Douglas Gregor1515f762009-02-11 18:22:40 +00002329 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002330 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002331 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002332 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002333 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002334 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002335 } else {
2336 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002337 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002338 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002339 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002340 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002341 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002342 }
2343
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002344 NamedDecl *Member = 0;
2345 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2346 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002347
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002348 if (Member)
2349 Member = cast<NamedDecl>(Member->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002350 Converted = TemplateArgument(Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002351 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00002352}
2353
2354/// \brief Check a template argument against its corresponding
2355/// template template parameter.
2356///
2357/// This routine implements the semantics of C++ [temp.arg.template].
2358/// It returns true if an error occurred, and false otherwise.
2359bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2360 DeclRefExpr *Arg) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002361 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2362 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2363
2364 // C++ [temp.arg.template]p1:
2365 // A template-argument for a template template-parameter shall be
2366 // the name of a class template, expressed as id-expression. Only
2367 // primary class templates are considered when matching the
2368 // template template argument with the corresponding parameter;
2369 // partial specializations are not considered even if their
2370 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002371 //
2372 // Note that we also allow template template parameters here, which
2373 // will happen when we are dealing with, e.g., class template
2374 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002375 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002376 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002377 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002378 "Only function templates are possible here");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002379 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2380 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002381 << Template;
2382 }
2383
2384 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2385 Param->getTemplateParameters(),
2386 true, true,
2387 Arg->getSourceRange().getBegin());
Douglas Gregord32e0282009-02-09 23:23:08 +00002388}
2389
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002390/// \brief Determine whether the given template parameter lists are
2391/// equivalent.
2392///
Mike Stump11289f42009-09-09 15:08:12 +00002393/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002394/// source code as part of a new template declaration.
2395///
2396/// \param Old The old template parameter list, typically found via
2397/// name lookup of the template declared with this template parameter
2398/// list.
2399///
2400/// \param Complain If true, this routine will produce a diagnostic if
2401/// the template parameter lists are not equivalent.
2402///
Douglas Gregor85e0f662009-02-10 00:24:35 +00002403/// \param IsTemplateTemplateParm If true, this routine is being
2404/// called to compare the template parameter lists of a template
2405/// template parameter.
2406///
2407/// \param TemplateArgLoc If this source location is valid, then we
2408/// are actually checking the template parameter list of a template
2409/// argument (New) against the template parameter list of its
2410/// corresponding template template parameter (Old). We produce
2411/// slightly different diagnostics in this scenario.
2412///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002413/// \returns True if the template parameter lists are equal, false
2414/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002415bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002416Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2417 TemplateParameterList *Old,
2418 bool Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002419 bool IsTemplateTemplateParm,
2420 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002421 if (Old->size() != New->size()) {
2422 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002423 unsigned NextDiag = diag::err_template_param_list_different_arity;
2424 if (TemplateArgLoc.isValid()) {
2425 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2426 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002427 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002428 Diag(New->getTemplateLoc(), NextDiag)
2429 << (New->size() > Old->size())
2430 << IsTemplateTemplateParm
2431 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002432 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2433 << IsTemplateTemplateParm
2434 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2435 }
2436
2437 return false;
2438 }
2439
2440 for (TemplateParameterList::iterator OldParm = Old->begin(),
2441 OldParmEnd = Old->end(), NewParm = New->begin();
2442 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2443 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002444 if (Complain) {
2445 unsigned NextDiag = diag::err_template_param_different_kind;
2446 if (TemplateArgLoc.isValid()) {
2447 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2448 NextDiag = diag::note_template_param_different_kind;
2449 }
2450 Diag((*NewParm)->getLocation(), NextDiag)
2451 << IsTemplateTemplateParm;
2452 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2453 << IsTemplateTemplateParm;
Douglas Gregor85e0f662009-02-10 00:24:35 +00002454 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002455 return false;
2456 }
2457
2458 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2459 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002460 // know we're at the same index).
2461#if 0
Mike Stump87c57ac2009-05-16 07:39:55 +00002462 // FIXME: Enable this code in debug mode *after* we properly go through
2463 // and "instantiate" the template parameter lists of template template
2464 // parameters. It's only after this instantiation that (1) any dependent
2465 // types within the template parameter list of the template template
2466 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregor85e0f662009-02-10 00:24:35 +00002467 // will match up.
Mike Stump11289f42009-09-09 15:08:12 +00002468 QualType OldParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002469 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
Mike Stump11289f42009-09-09 15:08:12 +00002470 QualType NewParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002471 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
Mike Stump11289f42009-09-09 15:08:12 +00002472 assert(Context.getCanonicalType(OldParmType) ==
2473 Context.getCanonicalType(NewParmType) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002474 "type parameter mismatch?");
2475#endif
Mike Stump11289f42009-09-09 15:08:12 +00002476 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002477 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2478 // The types of non-type template parameters must agree.
2479 NonTypeTemplateParmDecl *NewNTTP
2480 = cast<NonTypeTemplateParmDecl>(*NewParm);
2481 if (Context.getCanonicalType(OldNTTP->getType()) !=
2482 Context.getCanonicalType(NewNTTP->getType())) {
2483 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002484 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2485 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002486 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002487 diag::err_template_arg_template_params_mismatch);
2488 NextDiag = diag::note_template_nontype_parm_different_type;
2489 }
2490 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002491 << NewNTTP->getType()
2492 << IsTemplateTemplateParm;
Mike Stump11289f42009-09-09 15:08:12 +00002493 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002494 diag::note_template_nontype_parm_prev_declaration)
2495 << OldNTTP->getType();
2496 }
2497 return false;
2498 }
2499 } else {
2500 // The template parameter lists of template template
2501 // parameters must agree.
2502 // FIXME: Could we perform a faster "type" comparison here?
Mike Stump11289f42009-09-09 15:08:12 +00002503 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002504 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002505 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002506 = cast<TemplateTemplateParmDecl>(*OldParm);
2507 TemplateTemplateParmDecl *NewTTP
2508 = cast<TemplateTemplateParmDecl>(*NewParm);
2509 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2510 OldTTP->getTemplateParameters(),
2511 Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002512 /*IsTemplateTemplateParm=*/true,
2513 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002514 return false;
2515 }
2516 }
2517
2518 return true;
2519}
2520
2521/// \brief Check whether a template can be declared within this scope.
2522///
2523/// If the template declaration is valid in this scope, returns
2524/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002525bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002526Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002527 // Find the nearest enclosing declaration scope.
2528 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2529 (S->getFlags() & Scope::TemplateParamScope) != 0)
2530 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002531
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002532 // C++ [temp]p2:
2533 // A template-declaration can appear only as a namespace scope or
2534 // class scope declaration.
2535 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002536 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2537 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002538 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002539 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002540
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002541 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002542 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002543
2544 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2545 return false;
2546
Mike Stump11289f42009-09-09 15:08:12 +00002547 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002548 diag::err_template_outside_namespace_or_class_scope)
2549 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002550}
Douglas Gregor67a65642009-02-17 23:15:12 +00002551
Douglas Gregor54888652009-10-07 00:13:32 +00002552/// \brief Determine what kind of template specialization the given declaration
2553/// is.
2554static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2555 if (!D)
2556 return TSK_Undeclared;
2557
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002558 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2559 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002560 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2561 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002562 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2563 return Var->getTemplateSpecializationKind();
2564
Douglas Gregor54888652009-10-07 00:13:32 +00002565 return TSK_Undeclared;
2566}
2567
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002568/// \brief Check whether a specialization is well-formed in the current
2569/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002570///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002571/// This routine determines whether a template specialization can be declared
2572/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002573///
2574/// \param S the semantic analysis object for which this check is being
2575/// performed.
2576///
2577/// \param Specialized the entity being specialized or instantiated, which
2578/// may be a kind of template (class template, function template, etc.) or
2579/// a member of a class template (member function, static data member,
2580/// member class).
2581///
2582/// \param PrevDecl the previous declaration of this entity, if any.
2583///
2584/// \param Loc the location of the explicit specialization or instantiation of
2585/// this entity.
2586///
2587/// \param IsPartialSpecialization whether this is a partial specialization of
2588/// a class template.
2589///
Douglas Gregor54888652009-10-07 00:13:32 +00002590/// \returns true if there was an error that we cannot recover from, false
2591/// otherwise.
2592static bool CheckTemplateSpecializationScope(Sema &S,
2593 NamedDecl *Specialized,
2594 NamedDecl *PrevDecl,
2595 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002596 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002597 // Keep these "kind" numbers in sync with the %select statements in the
2598 // various diagnostics emitted by this routine.
2599 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002600 bool isTemplateSpecialization = false;
2601 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002602 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002603 isTemplateSpecialization = true;
2604 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002605 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002606 isTemplateSpecialization = true;
2607 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002608 EntityKind = 3;
2609 else if (isa<VarDecl>(Specialized))
2610 EntityKind = 4;
2611 else if (isa<RecordDecl>(Specialized))
2612 EntityKind = 5;
2613 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002614 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2615 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00002616 return true;
2617 }
2618
Douglas Gregorf47b9112009-02-25 22:02:03 +00002619 // C++ [temp.expl.spec]p2:
2620 // An explicit specialization shall be declared in the namespace
2621 // of which the template is a member, or, for member templates, in
2622 // the namespace of which the enclosing class or enclosing class
2623 // template is a member. An explicit specialization of a member
2624 // function, member class or static data member of a class
2625 // template shall be declared in the namespace of which the class
2626 // template is a member. Such a declaration may also be a
2627 // definition. If the declaration is not a definition, the
2628 // specialization may be defined later in the name- space in which
2629 // the explicit specialization was declared, or in a namespace
2630 // that encloses the one in which the explicit specialization was
2631 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002632 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2633 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002634 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002635 return true;
2636 }
Douglas Gregore4b05162009-10-07 17:21:34 +00002637
Douglas Gregor40fb7442009-10-07 17:30:37 +00002638 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2639 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002640 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00002641 return true;
2642 }
2643
Douglas Gregore4b05162009-10-07 17:21:34 +00002644 // C++ [temp.class.spec]p6:
2645 // A class template partial specialization may be declared or redeclared
2646 // in any namespace scope in which its definition may be defined (14.5.1
2647 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002648 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002649 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002650 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002651 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002652 if ((!PrevDecl ||
2653 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2654 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2655 // There is no prior declaration of this entity, so this
2656 // specialization must be in the same context as the template
2657 // itself.
2658 if (!DC->Equals(SpecializedContext)) {
2659 if (isa<TranslationUnitDecl>(SpecializedContext))
2660 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2661 << EntityKind << Specialized;
2662 else if (isa<NamespaceDecl>(SpecializedContext))
2663 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2664 << EntityKind << Specialized
2665 << cast<NamedDecl>(SpecializedContext);
2666
2667 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2668 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002669 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002670 }
Douglas Gregor54888652009-10-07 00:13:32 +00002671
2672 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002673 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00002674 // Note that HandleDeclarator() performs this check for explicit
2675 // specializations of function templates, static data members, and member
2676 // functions, so we skip the check here for those kinds of entities.
2677 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00002678 // Should we refactor that check, so that it occurs later?
2679 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002680 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2681 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00002682 if (isa<TranslationUnitDecl>(SpecializedContext))
2683 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2684 << EntityKind << Specialized;
2685 else if (isa<NamespaceDecl>(SpecializedContext))
2686 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2687 << EntityKind << Specialized
2688 << cast<NamedDecl>(SpecializedContext);
2689
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002690 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002691 }
Douglas Gregor54888652009-10-07 00:13:32 +00002692
2693 // FIXME: check for specialization-after-instantiation errors and such.
2694
Douglas Gregorf47b9112009-02-25 22:02:03 +00002695 return false;
2696}
Douglas Gregor54888652009-10-07 00:13:32 +00002697
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002698/// \brief Check the non-type template arguments of a class template
2699/// partial specialization according to C++ [temp.class.spec]p9.
2700///
Douglas Gregor09a30232009-06-12 22:08:06 +00002701/// \param TemplateParams the template parameters of the primary class
2702/// template.
2703///
2704/// \param TemplateArg the template arguments of the class template
2705/// partial specialization.
2706///
2707/// \param MirrorsPrimaryTemplate will be set true if the class
2708/// template partial specialization arguments are identical to the
2709/// implicit template arguments of the primary template. This is not
2710/// necessarily an error (C++0x), and it is left to the caller to diagnose
2711/// this condition when it is an error.
2712///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002713/// \returns true if there was an error, false otherwise.
2714bool Sema::CheckClassTemplatePartialSpecializationArgs(
2715 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002716 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002717 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002718 // FIXME: the interface to this function will have to change to
2719 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002720 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002721
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002722 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002723
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002724 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002725 // Determine whether the template argument list of the partial
2726 // specialization is identical to the implicit argument list of
2727 // the primary template. The caller may need to diagnostic this as
2728 // an error per C++ [temp.class.spec]p9b3.
2729 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002730 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002731 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2732 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002733 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002734 MirrorsPrimaryTemplate = false;
2735 } else if (TemplateTemplateParmDecl *TTP
2736 = dyn_cast<TemplateTemplateParmDecl>(
2737 TemplateParams->getParam(I))) {
2738 // FIXME: We should settle on either Declaration storage or
2739 // Expression storage for template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002740 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor09a30232009-06-12 22:08:06 +00002741 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson40c1d492009-06-13 18:20:51 +00002742 ArgList[I].getAsDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002743 if (!ArgDecl)
Mike Stump11289f42009-09-09 15:08:12 +00002744 if (DeclRefExpr *DRE
Anders Carlsson40c1d492009-06-13 18:20:51 +00002745 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002746 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2747
2748 if (!ArgDecl ||
2749 ArgDecl->getIndex() != TTP->getIndex() ||
2750 ArgDecl->getDepth() != TTP->getDepth())
2751 MirrorsPrimaryTemplate = false;
2752 }
2753 }
2754
Mike Stump11289f42009-09-09 15:08:12 +00002755 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002756 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002757 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002758 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002759 }
2760
Anders Carlsson40c1d492009-06-13 18:20:51 +00002761 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002762 if (!ArgExpr) {
2763 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002764 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002765 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002766
2767 // C++ [temp.class.spec]p8:
2768 // A non-type argument is non-specialized if it is the name of a
2769 // non-type parameter. All other non-type arguments are
2770 // specialized.
2771 //
2772 // Below, we check the two conditions that only apply to
2773 // specialized non-type arguments, so skip any non-specialized
2774 // arguments.
2775 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002776 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002777 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002778 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002779 (Param->getIndex() != NTTP->getIndex() ||
2780 Param->getDepth() != NTTP->getDepth()))
2781 MirrorsPrimaryTemplate = false;
2782
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002783 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002784 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002785
2786 // C++ [temp.class.spec]p9:
2787 // Within the argument list of a class template partial
2788 // specialization, the following restrictions apply:
2789 // -- A partially specialized non-type argument expression
2790 // shall not involve a template parameter of the partial
2791 // specialization except when the argument expression is a
2792 // simple identifier.
2793 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002794 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002795 diag::err_dependent_non_type_arg_in_partial_spec)
2796 << ArgExpr->getSourceRange();
2797 return true;
2798 }
2799
2800 // -- The type of a template parameter corresponding to a
2801 // specialized non-type argument shall not be dependent on a
2802 // parameter of the specialization.
2803 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002804 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002805 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2806 << Param->getType()
2807 << ArgExpr->getSourceRange();
2808 Diag(Param->getLocation(), diag::note_template_param_here);
2809 return true;
2810 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002811
2812 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002813 }
2814
2815 return false;
2816}
2817
Douglas Gregorc08f4892009-03-25 00:13:59 +00002818Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002819Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2820 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002821 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002822 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002823 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002824 SourceLocation TemplateNameLoc,
2825 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002826 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002827 SourceLocation RAngleLoc,
2828 AttributeList *Attr,
2829 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00002830 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00002831
Douglas Gregor67a65642009-02-17 23:15:12 +00002832 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002833 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002834 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002835 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002836
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002837 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00002838 bool isPartialSpecialization = false;
2839
Douglas Gregorf47b9112009-02-25 22:02:03 +00002840 // Check the validity of the template headers that introduce this
2841 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00002842 // FIXME: We probably shouldn't complain about these headers for
2843 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002844 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002845 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2846 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002847 TemplateParameterLists.size(),
2848 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002849 if (TemplateParams && TemplateParams->size() > 0) {
2850 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002851
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002852 // C++ [temp.class.spec]p10:
2853 // The template parameter list of a specialization shall not
2854 // contain default template argument values.
2855 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2856 Decl *Param = TemplateParams->getParam(I);
2857 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2858 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002859 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002860 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00002861 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002862 }
2863 } else if (NonTypeTemplateParmDecl *NTTP
2864 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2865 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002866 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002867 diag::err_default_arg_in_partial_spec)
2868 << DefArg->getSourceRange();
2869 NTTP->setDefaultArgument(0);
2870 DefArg->Destroy(Context);
2871 }
2872 } else {
2873 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2874 if (Expr *DefArg = TTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002875 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002876 diag::err_default_arg_in_partial_spec)
2877 << DefArg->getSourceRange();
2878 TTP->setDefaultArgument(0);
2879 DefArg->Destroy(Context);
Douglas Gregord5222052009-06-12 19:43:02 +00002880 }
2881 }
2882 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00002883 } else if (TemplateParams) {
2884 if (TUK == TUK_Friend)
2885 Diag(KWLoc, diag::err_template_spec_friend)
2886 << CodeModificationHint::CreateRemoval(
2887 SourceRange(TemplateParams->getTemplateLoc(),
2888 TemplateParams->getRAngleLoc()))
2889 << SourceRange(LAngleLoc, RAngleLoc);
2890 else
2891 isExplicitSpecialization = true;
2892 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002893 Diag(KWLoc, diag::err_template_spec_needs_header)
2894 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002895 isExplicitSpecialization = true;
2896 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002897
Douglas Gregor67a65642009-02-17 23:15:12 +00002898 // Check that the specialization uses the same tag kind as the
2899 // original template.
2900 TagDecl::TagKind Kind;
2901 switch (TagSpec) {
2902 default: assert(0 && "Unknown tag type!");
2903 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2904 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2905 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2906 }
Douglas Gregord9034f02009-05-14 16:41:31 +00002907 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00002908 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00002909 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00002910 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00002911 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00002912 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00002913 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00002914 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00002915 diag::note_previous_use);
2916 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2917 }
2918
Douglas Gregorc40290e2009-03-09 23:48:35 +00002919 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00002920 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002921 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002922
Douglas Gregor67a65642009-02-17 23:15:12 +00002923 // Check that the template argument list is well-formed for this
2924 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002925 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2926 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00002927 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002928 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00002929 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002930 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002931
Mike Stump11289f42009-09-09 15:08:12 +00002932 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00002933 ClassTemplate->getTemplateParameters()->size()) &&
2934 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00002935
Douglas Gregor2373c592009-05-31 09:31:02 +00002936 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00002937 // corresponds to these arguments.
2938 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00002939 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002940 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002941 if (CheckClassTemplatePartialSpecializationArgs(
2942 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002943 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002944 return true;
2945
Douglas Gregor09a30232009-06-12 22:08:06 +00002946 if (MirrorsPrimaryTemplate) {
2947 // C++ [temp.class.spec]p9b3:
2948 //
Mike Stump11289f42009-09-09 15:08:12 +00002949 // -- The argument list of the specialization shall not be identical
2950 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00002951 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00002952 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00002953 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00002954 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00002955 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00002956 ClassTemplate->getIdentifier(),
2957 TemplateNameLoc,
2958 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002959 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00002960 AS_none);
2961 }
2962
Douglas Gregor2208a292009-09-26 20:57:03 +00002963 // FIXME: Diagnose friend partial specializations
2964
Douglas Gregor2373c592009-05-31 09:31:02 +00002965 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00002966 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002967 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002968 Converted.flatSize(),
2969 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002970 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002971 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002972 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002973 Converted.flatSize(),
2974 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00002975 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002976 ClassTemplateSpecializationDecl *PrevDecl = 0;
2977
2978 if (isPartialSpecialization)
2979 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00002980 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00002981 InsertPos);
2982 else
2983 PrevDecl
2984 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00002985
2986 ClassTemplateSpecializationDecl *Specialization = 0;
2987
Douglas Gregorf47b9112009-02-25 22:02:03 +00002988 // Check whether we can declare a class template specialization in
2989 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00002990 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00002991 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002992 TemplateNameLoc,
2993 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002994 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002995
Douglas Gregor15301382009-07-30 17:40:51 +00002996 // The canonical type
2997 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00002998 if (PrevDecl &&
2999 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3000 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003001 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003002 // arguments was referenced but not declared, or we're only
3003 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003004 // declaration node as our own, updating its source location to
3005 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003006 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003007 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003008 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003009 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003010 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003011 // Build the canonical type that describes the converted template
3012 // arguments of the class template partial specialization.
3013 CanonType = Context.getTemplateSpecializationType(
3014 TemplateName(ClassTemplate),
3015 Converted.getFlatArguments(),
3016 Converted.flatSize());
3017
Douglas Gregor2373c592009-05-31 09:31:02 +00003018 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003019 ClassTemplatePartialSpecializationDecl *PrevPartial
3020 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003021 ClassTemplatePartialSpecializationDecl *Partial
3022 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003023 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003024 TemplateNameLoc,
3025 TemplateParams,
3026 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003027 Converted,
John McCall0ad16662009-10-29 08:12:44 +00003028 TemplateArgs.data(),
3029 TemplateArgs.size(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003030 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003031
3032 if (PrevPartial) {
3033 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3034 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3035 } else {
3036 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3037 }
3038 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003039
Douglas Gregor21610382009-10-29 00:04:11 +00003040 // If we are providing an explicit specialization of a member class
3041 // template specialization, make a note of that.
3042 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3043 PrevPartial->setMemberSpecialization();
3044
Douglas Gregor91772d12009-06-13 00:26:55 +00003045 // Check that all of the template parameters of the class template
3046 // partial specialization are deducible from the template
3047 // arguments. If not, this class template partial specialization
3048 // will never be used.
3049 llvm::SmallVector<bool, 8> DeducibleParams;
3050 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003051 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003052 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003053 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003054 unsigned NumNonDeducible = 0;
3055 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3056 if (!DeducibleParams[I])
3057 ++NumNonDeducible;
3058
3059 if (NumNonDeducible) {
3060 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3061 << (NumNonDeducible > 1)
3062 << SourceRange(TemplateNameLoc, RAngleLoc);
3063 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3064 if (!DeducibleParams[I]) {
3065 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3066 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003067 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003068 diag::note_partial_spec_unused_parameter)
3069 << Param->getDeclName();
3070 else
Mike Stump11289f42009-09-09 15:08:12 +00003071 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003072 diag::note_partial_spec_unused_parameter)
3073 << std::string("<anonymous>");
3074 }
3075 }
3076 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003077 } else {
3078 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003079 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003080 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003081 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003082 ClassTemplate->getDeclContext(),
3083 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003084 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003085 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003086 PrevDecl);
3087
3088 if (PrevDecl) {
3089 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3090 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3091 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003092 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003093 InsertPos);
3094 }
Douglas Gregor15301382009-07-30 17:40:51 +00003095
3096 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003097 }
3098
Douglas Gregor06db9f52009-10-12 20:18:28 +00003099 // C++ [temp.expl.spec]p6:
3100 // If a template, a member template or the member of a class template is
3101 // explicitly specialized then that specialization shall be declared
3102 // before the first use of that specialization that would cause an implicit
3103 // instantiation to take place, in every translation unit in which such a
3104 // use occurs; no diagnostic is required.
3105 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3106 SourceRange Range(TemplateNameLoc, RAngleLoc);
3107 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3108 << Context.getTypeDeclType(Specialization) << Range;
3109
3110 Diag(PrevDecl->getPointOfInstantiation(),
3111 diag::note_instantiation_required_here)
3112 << (PrevDecl->getTemplateSpecializationKind()
3113 != TSK_ImplicitInstantiation);
3114 return true;
3115 }
3116
Douglas Gregor2208a292009-09-26 20:57:03 +00003117 // If this is not a friend, note that this is an explicit specialization.
3118 if (TUK != TUK_Friend)
3119 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003120
3121 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003122 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003123 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003124 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003125 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003126 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003127 Diag(Def->getLocation(), diag::note_previous_definition);
3128 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003129 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003130 }
3131 }
3132
Douglas Gregord56a91e2009-02-26 22:19:44 +00003133 // Build the fully-sugared type for this class template
3134 // specialization as the user wrote in the specialization
3135 // itself. This means that we'll pretty-print the type retrieved
3136 // from the specialization's declaration the way that the user
3137 // actually wrote the specialization, rather than formatting the
3138 // name based on the "canonical" representation used to store the
3139 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003140 QualType WrittenTy
3141 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003142 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00003143 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00003144 CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003145 if (TUK != TUK_Friend)
3146 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003147 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003148
Douglas Gregor1e249f82009-02-25 22:18:32 +00003149 // C++ [temp.expl.spec]p9:
3150 // A template explicit specialization is in the scope of the
3151 // namespace in which the template was defined.
3152 //
3153 // We actually implement this paragraph where we set the semantic
3154 // context (in the creation of the ClassTemplateSpecializationDecl),
3155 // but we also maintain the lexical context where the actual
3156 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003157 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003158
Douglas Gregor67a65642009-02-17 23:15:12 +00003159 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003160 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003161 Specialization->startDefinition();
3162
Douglas Gregor2208a292009-09-26 20:57:03 +00003163 if (TUK == TUK_Friend) {
3164 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3165 TemplateNameLoc,
3166 WrittenTy.getTypePtr(),
3167 /*FIXME:*/KWLoc);
3168 Friend->setAccess(AS_public);
3169 CurContext->addDecl(Friend);
3170 } else {
3171 // Add the specialization into its lexical context, so that it can
3172 // be seen when iterating through the list of declarations in that
3173 // context. However, specializations are not found by name lookup.
3174 CurContext->addDecl(Specialization);
3175 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003176 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003177}
Douglas Gregor333489b2009-03-27 23:10:48 +00003178
Mike Stump11289f42009-09-09 15:08:12 +00003179Sema::DeclPtrTy
3180Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003181 MultiTemplateParamsArg TemplateParameterLists,
3182 Declarator &D) {
3183 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3184}
3185
Mike Stump11289f42009-09-09 15:08:12 +00003186Sema::DeclPtrTy
3187Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003188 MultiTemplateParamsArg TemplateParameterLists,
3189 Declarator &D) {
3190 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3191 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3192 "Not a function declarator!");
3193 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003194
Douglas Gregor17a7c122009-06-24 00:54:41 +00003195 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003196 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003197 }
Mike Stump11289f42009-09-09 15:08:12 +00003198
Douglas Gregor17a7c122009-06-24 00:54:41 +00003199 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003200
3201 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003202 move(TemplateParameterLists),
3203 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003204 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003205 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003206 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003207 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003208 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3209 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003210 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003211}
3212
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003213/// \brief Diagnose cases where we have an explicit template specialization
3214/// before/after an explicit template instantiation, producing diagnostics
3215/// for those cases where they are required and determining whether the
3216/// new specialization/instantiation will have any effect.
3217///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003218/// \param NewLoc the location of the new explicit specialization or
3219/// instantiation.
3220///
3221/// \param NewTSK the kind of the new explicit specialization or instantiation.
3222///
3223/// \param PrevDecl the previous declaration of the entity.
3224///
3225/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3226///
3227/// \param PrevPointOfInstantiation if valid, indicates where the previus
3228/// declaration was instantiated (either implicitly or explicitly).
3229///
3230/// \param SuppressNew will be set to true to indicate that the new
3231/// specialization or instantiation has no effect and should be ignored.
3232///
3233/// \returns true if there was an error that should prevent the introduction of
3234/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003235bool
3236Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3237 TemplateSpecializationKind NewTSK,
3238 NamedDecl *PrevDecl,
3239 TemplateSpecializationKind PrevTSK,
3240 SourceLocation PrevPointOfInstantiation,
3241 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003242 SuppressNew = false;
3243
3244 switch (NewTSK) {
3245 case TSK_Undeclared:
3246 case TSK_ImplicitInstantiation:
3247 assert(false && "Don't check implicit instantiations here");
3248 return false;
3249
3250 case TSK_ExplicitSpecialization:
3251 switch (PrevTSK) {
3252 case TSK_Undeclared:
3253 case TSK_ExplicitSpecialization:
3254 // Okay, we're just specializing something that is either already
3255 // explicitly specialized or has merely been mentioned without any
3256 // instantiation.
3257 return false;
3258
3259 case TSK_ImplicitInstantiation:
3260 if (PrevPointOfInstantiation.isInvalid()) {
3261 // The declaration itself has not actually been instantiated, so it is
3262 // still okay to specialize it.
3263 return false;
3264 }
3265 // Fall through
3266
3267 case TSK_ExplicitInstantiationDeclaration:
3268 case TSK_ExplicitInstantiationDefinition:
3269 assert((PrevTSK == TSK_ImplicitInstantiation ||
3270 PrevPointOfInstantiation.isValid()) &&
3271 "Explicit instantiation without point of instantiation?");
3272
3273 // C++ [temp.expl.spec]p6:
3274 // If a template, a member template or the member of a class template
3275 // is explicitly specialized then that specialization shall be declared
3276 // before the first use of that specialization that would cause an
3277 // implicit instantiation to take place, in every translation unit in
3278 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003279 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003280 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003281 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003282 << (PrevTSK != TSK_ImplicitInstantiation);
3283
3284 return true;
3285 }
3286 break;
3287
3288 case TSK_ExplicitInstantiationDeclaration:
3289 switch (PrevTSK) {
3290 case TSK_ExplicitInstantiationDeclaration:
3291 // This explicit instantiation declaration is redundant (that's okay).
3292 SuppressNew = true;
3293 return false;
3294
3295 case TSK_Undeclared:
3296 case TSK_ImplicitInstantiation:
3297 // We're explicitly instantiating something that may have already been
3298 // implicitly instantiated; that's fine.
3299 return false;
3300
3301 case TSK_ExplicitSpecialization:
3302 // C++0x [temp.explicit]p4:
3303 // For a given set of template parameters, if an explicit instantiation
3304 // of a template appears after a declaration of an explicit
3305 // specialization for that template, the explicit instantiation has no
3306 // effect.
3307 return false;
3308
3309 case TSK_ExplicitInstantiationDefinition:
3310 // C++0x [temp.explicit]p10:
3311 // If an entity is the subject of both an explicit instantiation
3312 // declaration and an explicit instantiation definition in the same
3313 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003314 Diag(NewLoc,
3315 diag::err_explicit_instantiation_declaration_after_definition);
3316 Diag(PrevPointOfInstantiation,
3317 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003318 assert(PrevPointOfInstantiation.isValid() &&
3319 "Explicit instantiation without point of instantiation?");
3320 SuppressNew = true;
3321 return false;
3322 }
3323 break;
3324
3325 case TSK_ExplicitInstantiationDefinition:
3326 switch (PrevTSK) {
3327 case TSK_Undeclared:
3328 case TSK_ImplicitInstantiation:
3329 // We're explicitly instantiating something that may have already been
3330 // implicitly instantiated; that's fine.
3331 return false;
3332
3333 case TSK_ExplicitSpecialization:
3334 // C++ DR 259, C++0x [temp.explicit]p4:
3335 // For a given set of template parameters, if an explicit
3336 // instantiation of a template appears after a declaration of
3337 // an explicit specialization for that template, the explicit
3338 // instantiation has no effect.
3339 //
3340 // In C++98/03 mode, we only give an extension warning here, because it
3341 // is not not harmful to try to explicitly instantiate something that
3342 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003343 if (!getLangOptions().CPlusPlus0x) {
3344 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003345 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003346 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003347 diag::note_previous_template_specialization);
3348 }
3349 SuppressNew = true;
3350 return false;
3351
3352 case TSK_ExplicitInstantiationDeclaration:
3353 // We're explicity instantiating a definition for something for which we
3354 // were previously asked to suppress instantiations. That's fine.
3355 return false;
3356
3357 case TSK_ExplicitInstantiationDefinition:
3358 // C++0x [temp.spec]p5:
3359 // For a given template and a given set of template-arguments,
3360 // - an explicit instantiation definition shall appear at most once
3361 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003362 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003363 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003364 Diag(PrevPointOfInstantiation,
3365 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003366 SuppressNew = true;
3367 return false;
3368 }
3369 break;
3370 }
3371
3372 assert(false && "Missing specialization/instantiation case?");
3373
3374 return false;
3375}
3376
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003377/// \brief Perform semantic analysis for the given function template
3378/// specialization.
3379///
3380/// This routine performs all of the semantic analysis required for an
3381/// explicit function template specialization. On successful completion,
3382/// the function declaration \p FD will become a function template
3383/// specialization.
3384///
3385/// \param FD the function declaration, which will be updated to become a
3386/// function template specialization.
3387///
3388/// \param HasExplicitTemplateArgs whether any template arguments were
3389/// explicitly provided.
3390///
3391/// \param LAngleLoc the location of the left angle bracket ('<'), if
3392/// template arguments were explicitly provided.
3393///
3394/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3395/// if any.
3396///
3397/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3398/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3399/// true as in, e.g., \c void sort<>(char*, char*);
3400///
3401/// \param RAngleLoc the location of the right angle bracket ('>'), if
3402/// template arguments were explicitly provided.
3403///
3404/// \param PrevDecl the set of declarations that
3405bool
3406Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3407 bool HasExplicitTemplateArgs,
3408 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00003409 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003410 unsigned NumExplicitTemplateArgs,
3411 SourceLocation RAngleLoc,
3412 NamedDecl *&PrevDecl) {
3413 // The set of function template specializations that could match this
3414 // explicit function template specialization.
3415 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3416 CandidateSet Candidates;
3417
3418 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3419 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3420 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3421 // Only consider templates found within the same semantic lookup scope as
3422 // FD.
3423 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3424 continue;
3425
3426 // C++ [temp.expl.spec]p11:
3427 // A trailing template-argument can be left unspecified in the
3428 // template-id naming an explicit function template specialization
3429 // provided it can be deduced from the function argument type.
3430 // Perform template argument deduction to determine whether we may be
3431 // specializing this template.
3432 // FIXME: It is somewhat wasteful to build
3433 TemplateDeductionInfo Info(Context);
3434 FunctionDecl *Specialization = 0;
3435 if (TemplateDeductionResult TDK
3436 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3437 ExplicitTemplateArgs,
3438 NumExplicitTemplateArgs,
3439 FD->getType(),
3440 Specialization,
3441 Info)) {
3442 // FIXME: Template argument deduction failed; record why it failed, so
3443 // that we can provide nifty diagnostics.
3444 (void)TDK;
3445 continue;
3446 }
3447
3448 // Record this candidate.
3449 Candidates.push_back(Specialization);
3450 }
3451 }
3452
Douglas Gregor5de279c2009-09-26 03:41:46 +00003453 // Find the most specialized function template.
3454 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3455 Candidates.size(),
3456 TPOC_Other,
3457 FD->getLocation(),
3458 PartialDiagnostic(diag::err_function_template_spec_no_match)
3459 << FD->getDeclName(),
3460 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3461 << FD->getDeclName() << HasExplicitTemplateArgs,
3462 PartialDiagnostic(diag::note_function_template_spec_matched));
3463 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003464 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003465
3466 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003467 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003468
Douglas Gregor54888652009-10-07 00:13:32 +00003469 // Check the scope of this explicit specialization.
3470 if (CheckTemplateSpecializationScope(*this,
3471 Specialization->getPrimaryTemplate(),
3472 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003473 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003474 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003475
3476 // C++ [temp.expl.spec]p6:
3477 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003478 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003479 // before the first use of that specialization that would cause an implicit
3480 // instantiation to take place, in every translation unit in which such a
3481 // use occurs; no diagnostic is required.
3482 FunctionTemplateSpecializationInfo *SpecInfo
3483 = Specialization->getTemplateSpecializationInfo();
3484 assert(SpecInfo && "Function template specialization info missing?");
3485 if (SpecInfo->getPointOfInstantiation().isValid()) {
3486 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3487 << FD;
3488 Diag(SpecInfo->getPointOfInstantiation(),
3489 diag::note_instantiation_required_here)
3490 << (Specialization->getTemplateSpecializationKind()
3491 != TSK_ImplicitInstantiation);
3492 return true;
3493 }
Douglas Gregor54888652009-10-07 00:13:32 +00003494
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003495 // Mark the prior declaration as an explicit specialization, so that later
3496 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003497 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003498
3499 // Turn the given function declaration into a function template
3500 // specialization, with the template arguments from the previous
3501 // specialization.
3502 FD->setFunctionTemplateSpecialization(Context,
3503 Specialization->getPrimaryTemplate(),
3504 new (Context) TemplateArgumentList(
3505 *Specialization->getTemplateSpecializationArgs()),
3506 /*InsertPos=*/0,
3507 TSK_ExplicitSpecialization);
3508
3509 // The "previous declaration" for this function template specialization is
3510 // the prior function template specialization.
3511 PrevDecl = Specialization;
3512 return false;
3513}
3514
Douglas Gregor86d142a2009-10-08 07:24:58 +00003515/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003516/// specialization.
3517///
3518/// This routine performs all of the semantic analysis required for an
3519/// explicit member function specialization. On successful completion,
3520/// the function declaration \p FD will become a member function
3521/// specialization.
3522///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003523/// \param Member the member declaration, which will be updated to become a
3524/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003525///
3526/// \param PrevDecl the set of declarations, one of which may be specialized
3527/// by this function specialization.
3528bool
Douglas Gregor86d142a2009-10-08 07:24:58 +00003529Sema::CheckMemberSpecialization(NamedDecl *Member, NamedDecl *&PrevDecl) {
3530 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3531
3532 // Try to find the member we are instantiating.
3533 NamedDecl *Instantiation = 0;
3534 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003535 MemberSpecializationInfo *MSInfo = 0;
3536
Douglas Gregor86d142a2009-10-08 07:24:58 +00003537 if (!PrevDecl) {
3538 // Nowhere to look anyway.
3539 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3540 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3541 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl)) {
3542 if (Context.hasSameType(Function->getType(), Method->getType())) {
3543 Instantiation = Method;
3544 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003545 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003546 break;
3547 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003548 }
3549 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003550 } else if (isa<VarDecl>(Member)) {
3551 if (VarDecl *PrevVar = dyn_cast<VarDecl>(PrevDecl))
3552 if (PrevVar->isStaticDataMember()) {
3553 Instantiation = PrevDecl;
3554 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003555 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003556 }
3557 } else if (isa<RecordDecl>(Member)) {
3558 if (CXXRecordDecl *PrevRecord = dyn_cast<CXXRecordDecl>(PrevDecl)) {
3559 Instantiation = PrevDecl;
3560 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003561 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003562 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003563 }
3564
3565 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003566 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003567 // specializations are always out-of-line, the caller will complain about
3568 // this mismatch later.
3569 return false;
3570 }
3571
Douglas Gregor86d142a2009-10-08 07:24:58 +00003572 // Make sure that this is a specialization of a member.
3573 if (!InstantiatedFrom) {
3574 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3575 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003576 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3577 return true;
3578 }
3579
Douglas Gregor06db9f52009-10-12 20:18:28 +00003580 // C++ [temp.expl.spec]p6:
3581 // If a template, a member template or the member of a class template is
3582 // explicitly specialized then that spe- cialization shall be declared
3583 // before the first use of that specialization that would cause an implicit
3584 // instantiation to take place, in every translation unit in which such a
3585 // use occurs; no diagnostic is required.
3586 assert(MSInfo && "Member specialization info missing?");
3587 if (MSInfo->getPointOfInstantiation().isValid()) {
3588 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3589 << Member;
3590 Diag(MSInfo->getPointOfInstantiation(),
3591 diag::note_instantiation_required_here)
3592 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3593 return true;
3594 }
3595
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003596 // Check the scope of this explicit specialization.
3597 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003598 InstantiatedFrom,
3599 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003600 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003601 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003602
Douglas Gregor86d142a2009-10-08 07:24:58 +00003603 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003604 // the original declaration to note that it is an explicit specialization
3605 // (if it was previously an implicit instantiation). This latter step
3606 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003607 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003608 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3609 if (InstantiationFunction->getTemplateSpecializationKind() ==
3610 TSK_ImplicitInstantiation) {
3611 InstantiationFunction->setTemplateSpecializationKind(
3612 TSK_ExplicitSpecialization);
3613 InstantiationFunction->setLocation(Member->getLocation());
3614 }
3615
Douglas Gregor86d142a2009-10-08 07:24:58 +00003616 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3617 cast<CXXMethodDecl>(InstantiatedFrom),
3618 TSK_ExplicitSpecialization);
3619 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003620 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3621 if (InstantiationVar->getTemplateSpecializationKind() ==
3622 TSK_ImplicitInstantiation) {
3623 InstantiationVar->setTemplateSpecializationKind(
3624 TSK_ExplicitSpecialization);
3625 InstantiationVar->setLocation(Member->getLocation());
3626 }
3627
Douglas Gregor86d142a2009-10-08 07:24:58 +00003628 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3629 cast<VarDecl>(InstantiatedFrom),
3630 TSK_ExplicitSpecialization);
3631 } else {
3632 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003633 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3634 if (InstantiationClass->getTemplateSpecializationKind() ==
3635 TSK_ImplicitInstantiation) {
3636 InstantiationClass->setTemplateSpecializationKind(
3637 TSK_ExplicitSpecialization);
3638 InstantiationClass->setLocation(Member->getLocation());
3639 }
3640
Douglas Gregor86d142a2009-10-08 07:24:58 +00003641 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003642 cast<CXXRecordDecl>(InstantiatedFrom),
3643 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003644 }
3645
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003646 // Save the caller the trouble of having to figure out which declaration
3647 // this specialization matches.
3648 PrevDecl = Instantiation;
3649 return false;
3650}
3651
Douglas Gregore47f5a72009-10-14 23:41:34 +00003652/// \brief Check the scope of an explicit instantiation.
3653static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3654 SourceLocation InstLoc,
3655 bool WasQualifiedName) {
3656 DeclContext *ExpectedContext
3657 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3658 DeclContext *CurContext = S.CurContext->getLookupContext();
3659
3660 // C++0x [temp.explicit]p2:
3661 // An explicit instantiation shall appear in an enclosing namespace of its
3662 // template.
3663 //
3664 // This is DR275, which we do not retroactively apply to C++98/03.
3665 if (S.getLangOptions().CPlusPlus0x &&
3666 !CurContext->Encloses(ExpectedContext)) {
3667 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3668 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3669 << D << NS;
3670 else
3671 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3672 << D;
3673 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3674 return;
3675 }
3676
3677 // C++0x [temp.explicit]p2:
3678 // If the name declared in the explicit instantiation is an unqualified
3679 // name, the explicit instantiation shall appear in the namespace where
3680 // its template is declared or, if that namespace is inline (7.3.1), any
3681 // namespace from its enclosing namespace set.
3682 if (WasQualifiedName)
3683 return;
3684
3685 if (CurContext->Equals(ExpectedContext))
3686 return;
3687
3688 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3689 << D << ExpectedContext;
3690 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3691}
3692
3693/// \brief Determine whether the given scope specifier has a template-id in it.
3694static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3695 if (!SS.isSet())
3696 return false;
3697
3698 // C++0x [temp.explicit]p2:
3699 // If the explicit instantiation is for a member function, a member class
3700 // or a static data member of a class template specialization, the name of
3701 // the class template specialization in the qualified-id for the member
3702 // name shall be a simple-template-id.
3703 //
3704 // C++98 has the same restriction, just worded differently.
3705 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3706 NNS; NNS = NNS->getPrefix())
3707 if (Type *T = NNS->getAsType())
3708 if (isa<TemplateSpecializationType>(T))
3709 return true;
3710
3711 return false;
3712}
3713
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003714// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003715// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003716Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003717Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003718 SourceLocation ExternLoc,
3719 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003720 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003721 SourceLocation KWLoc,
3722 const CXXScopeSpec &SS,
3723 TemplateTy TemplateD,
3724 SourceLocation TemplateNameLoc,
3725 SourceLocation LAngleLoc,
3726 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00003727 SourceLocation RAngleLoc,
3728 AttributeList *Attr) {
3729 // Find the class template we're specializing
3730 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003731 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003732 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3733
3734 // Check that the specialization uses the same tag kind as the
3735 // original template.
3736 TagDecl::TagKind Kind;
3737 switch (TagSpec) {
3738 default: assert(0 && "Unknown tag type!");
3739 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3740 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3741 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3742 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003743 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003744 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003745 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003746 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003747 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003748 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003749 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003750 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003751 diag::note_previous_use);
3752 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3753 }
3754
Douglas Gregore47f5a72009-10-14 23:41:34 +00003755 // C++0x [temp.explicit]p2:
3756 // There are two forms of explicit instantiation: an explicit instantiation
3757 // definition and an explicit instantiation declaration. An explicit
3758 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00003759 TemplateSpecializationKind TSK
3760 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3761 : TSK_ExplicitInstantiationDeclaration;
3762
Douglas Gregora1f49972009-05-13 00:25:59 +00003763 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00003764 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003765 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00003766
3767 // Check that the template argument list is well-formed for this
3768 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003769 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3770 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003771 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003772 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003773 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003774 return true;
3775
Mike Stump11289f42009-09-09 15:08:12 +00003776 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003777 ClassTemplate->getTemplateParameters()->size()) &&
3778 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003779
Douglas Gregora1f49972009-05-13 00:25:59 +00003780 // Find the class template specialization declaration that
3781 // corresponds to these arguments.
3782 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003783 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003784 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003785 Converted.flatSize(),
3786 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003787 void *InsertPos = 0;
3788 ClassTemplateSpecializationDecl *PrevDecl
3789 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3790
Douglas Gregor54888652009-10-07 00:13:32 +00003791 // C++0x [temp.explicit]p2:
3792 // [...] An explicit instantiation shall appear in an enclosing
3793 // namespace of its template. [...]
3794 //
3795 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00003796 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
3797 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00003798
Douglas Gregora1f49972009-05-13 00:25:59 +00003799 ClassTemplateSpecializationDecl *Specialization = 0;
3800
3801 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00003802 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003803 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00003804 PrevDecl,
3805 PrevDecl->getSpecializationKind(),
3806 PrevDecl->getPointOfInstantiation(),
3807 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00003808 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003809
Douglas Gregor12e49d32009-10-15 22:53:21 +00003810 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003811 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00003812
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003813 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3814 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3815 // Since the only prior class template specialization with these
3816 // arguments was referenced but not declared, reuse that
3817 // declaration node as our own, updating its source location to
3818 // reflect our new declaration.
3819 Specialization = PrevDecl;
3820 Specialization->setLocation(TemplateNameLoc);
3821 PrevDecl = 0;
3822 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00003823 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003824
3825 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003826 // Create a new class template specialization declaration node for
3827 // this explicit specialization.
3828 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003829 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003830 ClassTemplate->getDeclContext(),
3831 TemplateNameLoc,
3832 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003833 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003834
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003835 if (PrevDecl) {
3836 // Remove the previous declaration from the folding set, since we want
3837 // to introduce a new declaration.
3838 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3839 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3840 }
3841
3842 // Insert the new specialization.
3843 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003844 }
3845
3846 // Build the fully-sugared type for this explicit instantiation as
3847 // the user wrote in the explicit instantiation itself. This means
3848 // that we'll pretty-print the type retrieved from the
3849 // specialization's declaration the way that the user actually wrote
3850 // the explicit instantiation, rather than formatting the name based
3851 // on the "canonical" representation used to store the template
3852 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003853 QualType WrittenTy
3854 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003855 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003856 TemplateArgs.size(),
3857 Context.getTypeDeclType(Specialization));
3858 Specialization->setTypeAsWritten(WrittenTy);
3859 TemplateArgsIn.release();
3860
3861 // Add the explicit instantiation into its lexical context. However,
3862 // since explicit instantiations are never found by name lookup, we
3863 // just put it into the declaration context directly.
3864 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003865 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003866
3867 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003868 // A definition of a class template or class member template
3869 // shall be in scope at the point of the explicit instantiation of
3870 // the class template or class member template.
3871 //
3872 // This check comes when we actually try to perform the
3873 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00003874 ClassTemplateSpecializationDecl *Def
3875 = cast_or_null<ClassTemplateSpecializationDecl>(
3876 Specialization->getDefinition(Context));
3877 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00003878 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00003879
3880 // Instantiate the members of this class template specialization.
3881 Def = cast_or_null<ClassTemplateSpecializationDecl>(
3882 Specialization->getDefinition(Context));
3883 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00003884 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003885
3886 return DeclPtrTy::make(Specialization);
3887}
3888
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003889// Explicit instantiation of a member class of a class template.
3890Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003891Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003892 SourceLocation ExternLoc,
3893 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003894 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003895 SourceLocation KWLoc,
3896 const CXXScopeSpec &SS,
3897 IdentifierInfo *Name,
3898 SourceLocation NameLoc,
3899 AttributeList *Attr) {
3900
Douglas Gregord6ab8742009-05-28 23:31:59 +00003901 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003902 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00003903 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00003904 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00003905 MultiTemplateParamsArg(*this, 0, 0),
3906 Owned, IsDependent);
3907 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3908
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003909 if (!TagD)
3910 return true;
3911
3912 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3913 if (Tag->isEnum()) {
3914 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3915 << Context.getTypeDeclType(Tag);
3916 return true;
3917 }
3918
Douglas Gregorb8006faf2009-05-27 17:30:49 +00003919 if (Tag->isInvalidDecl())
3920 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00003921
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003922 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3923 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3924 if (!Pattern) {
3925 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3926 << Context.getTypeDeclType(Record);
3927 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3928 return true;
3929 }
3930
Douglas Gregore47f5a72009-10-14 23:41:34 +00003931 // C++0x [temp.explicit]p2:
3932 // If the explicit instantiation is for a class or member class, the
3933 // elaborated-type-specifier in the declaration shall include a
3934 // simple-template-id.
3935 //
3936 // C++98 has the same restriction, just worded differently.
3937 if (!ScopeSpecifierHasTemplateId(SS))
3938 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
3939 << Record << SS.getRange();
3940
3941 // C++0x [temp.explicit]p2:
3942 // There are two forms of explicit instantiation: an explicit instantiation
3943 // definition and an explicit instantiation declaration. An explicit
3944 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00003945 TemplateSpecializationKind TSK
3946 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3947 : TSK_ExplicitInstantiationDeclaration;
3948
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003949 // C++0x [temp.explicit]p2:
3950 // [...] An explicit instantiation shall appear in an enclosing
3951 // namespace of its template. [...]
3952 //
3953 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00003954 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003955
3956 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00003957 CXXRecordDecl *PrevDecl
3958 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
3959 if (!PrevDecl && Record->getDefinition(Context))
3960 PrevDecl = Record;
3961 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003962 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
3963 bool SuppressNew = false;
3964 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00003965 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003966 PrevDecl,
3967 MSInfo->getTemplateSpecializationKind(),
3968 MSInfo->getPointOfInstantiation(),
3969 SuppressNew))
3970 return true;
3971 if (SuppressNew)
3972 return TagD;
3973 }
3974
Douglas Gregor12e49d32009-10-15 22:53:21 +00003975 CXXRecordDecl *RecordDef
3976 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
3977 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00003978 // C++ [temp.explicit]p3:
3979 // A definition of a member class of a class template shall be in scope
3980 // at the point of an explicit instantiation of the member class.
3981 CXXRecordDecl *Def
3982 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
3983 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003984 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
3985 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00003986 Diag(Pattern->getLocation(), diag::note_forward_declaration)
3987 << Pattern;
3988 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003989 } else {
3990 if (InstantiateClass(NameLoc, Record, Def,
3991 getTemplateInstantiationArgs(Record),
3992 TSK))
3993 return true;
3994
3995 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
3996 if (!RecordDef)
3997 return true;
3998 }
3999 }
4000
4001 // Instantiate all of the members of the class.
4002 InstantiateClassMembers(NameLoc, RecordDef,
4003 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004004
Mike Stump87c57ac2009-05-16 07:39:55 +00004005 // FIXME: We don't have any representation for explicit instantiations of
4006 // member classes. Such a representation is not needed for compilation, but it
4007 // should be available for clients that want to see all of the declarations in
4008 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004009 return TagD;
4010}
4011
Douglas Gregor450f00842009-09-25 18:43:00 +00004012Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4013 SourceLocation ExternLoc,
4014 SourceLocation TemplateLoc,
4015 Declarator &D) {
4016 // Explicit instantiations always require a name.
4017 DeclarationName Name = GetNameForDeclarator(D);
4018 if (!Name) {
4019 if (!D.isInvalidType())
4020 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4021 diag::err_explicit_instantiation_requires_name)
4022 << D.getDeclSpec().getSourceRange()
4023 << D.getSourceRange();
4024
4025 return true;
4026 }
4027
4028 // The scope passed in may not be a decl scope. Zip up the scope tree until
4029 // we find one that is.
4030 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4031 (S->getFlags() & Scope::TemplateParamScope) != 0)
4032 S = S->getParent();
4033
4034 // Determine the type of the declaration.
4035 QualType R = GetTypeForDeclarator(D, S, 0);
4036 if (R.isNull())
4037 return true;
4038
4039 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4040 // Cannot explicitly instantiate a typedef.
4041 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4042 << Name;
4043 return true;
4044 }
4045
Douglas Gregor3c74d412009-10-14 20:14:33 +00004046 // C++0x [temp.explicit]p1:
4047 // [...] An explicit instantiation of a function template shall not use the
4048 // inline or constexpr specifiers.
4049 // Presumably, this also applies to member functions of class templates as
4050 // well.
4051 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4052 Diag(D.getDeclSpec().getInlineSpecLoc(),
4053 diag::err_explicit_instantiation_inline)
4054 << CodeModificationHint::CreateRemoval(
4055 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
4056
4057 // FIXME: check for constexpr specifier.
4058
Douglas Gregore47f5a72009-10-14 23:41:34 +00004059 // C++0x [temp.explicit]p2:
4060 // There are two forms of explicit instantiation: an explicit instantiation
4061 // definition and an explicit instantiation declaration. An explicit
4062 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004063 TemplateSpecializationKind TSK
4064 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4065 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004066
John McCall9f3059a2009-10-09 21:13:30 +00004067 LookupResult Previous;
4068 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
4069 Name, LookupOrdinaryName);
Douglas Gregor450f00842009-09-25 18:43:00 +00004070
4071 if (!R->isFunctionType()) {
4072 // C++ [temp.explicit]p1:
4073 // A [...] static data member of a class template can be explicitly
4074 // instantiated from the member definition associated with its class
4075 // template.
4076 if (Previous.isAmbiguous()) {
4077 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
4078 D.getSourceRange());
4079 }
4080
John McCall9f3059a2009-10-09 21:13:30 +00004081 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4082 Previous.getAsSingleDecl(Context));
Douglas Gregor450f00842009-09-25 18:43:00 +00004083 if (!Prev || !Prev->isStaticDataMember()) {
4084 // We expect to see a data data member here.
4085 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4086 << Name;
4087 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4088 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004089 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004090 return true;
4091 }
4092
4093 if (!Prev->getInstantiatedFromStaticDataMember()) {
4094 // FIXME: Check for explicit specialization?
4095 Diag(D.getIdentifierLoc(),
4096 diag::err_explicit_instantiation_data_member_not_instantiated)
4097 << Prev;
4098 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4099 // FIXME: Can we provide a note showing where this was declared?
4100 return true;
4101 }
4102
Douglas Gregore47f5a72009-10-14 23:41:34 +00004103 // C++0x [temp.explicit]p2:
4104 // If the explicit instantiation is for a member function, a member class
4105 // or a static data member of a class template specialization, the name of
4106 // the class template specialization in the qualified-id for the member
4107 // name shall be a simple-template-id.
4108 //
4109 // C++98 has the same restriction, just worded differently.
4110 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4111 Diag(D.getIdentifierLoc(),
4112 diag::err_explicit_instantiation_without_qualified_id)
4113 << Prev << D.getCXXScopeSpec().getRange();
4114
4115 // Check the scope of this explicit instantiation.
4116 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4117
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004118 // Verify that it is okay to explicitly instantiate here.
4119 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4120 assert(MSInfo && "Missing static data member specialization info?");
4121 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004122 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004123 MSInfo->getTemplateSpecializationKind(),
4124 MSInfo->getPointOfInstantiation(),
4125 SuppressNew))
4126 return true;
4127 if (SuppressNew)
4128 return DeclPtrTy();
4129
Douglas Gregor450f00842009-09-25 18:43:00 +00004130 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004131 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004132 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004133 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4134 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004135
4136 // FIXME: Create an ExplicitInstantiation node?
4137 return DeclPtrTy();
4138 }
4139
Douglas Gregor0e876e02009-09-25 23:53:26 +00004140 // If the declarator is a template-id, translate the parser's template
4141 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004142 bool HasExplicitTemplateArgs = false;
John McCall0ad16662009-10-29 08:12:44 +00004143 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004144 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4145 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Douglas Gregord90fd522009-09-25 21:45:23 +00004146 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4147 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004148 TemplateId->NumArgs);
4149 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregord90fd522009-09-25 21:45:23 +00004150 TemplateArgs);
4151 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004152 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004153 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004154
Douglas Gregor450f00842009-09-25 18:43:00 +00004155 // C++ [temp.explicit]p1:
4156 // A [...] function [...] can be explicitly instantiated from its template.
4157 // A member function [...] of a class template can be explicitly
4158 // instantiated from the member definition associated with its class
4159 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004160 llvm::SmallVector<FunctionDecl *, 8> Matches;
4161 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4162 P != PEnd; ++P) {
4163 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004164 if (!HasExplicitTemplateArgs) {
4165 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4166 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4167 Matches.clear();
4168 Matches.push_back(Method);
4169 break;
4170 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004171 }
4172 }
4173
4174 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4175 if (!FunTmpl)
4176 continue;
4177
4178 TemplateDeductionInfo Info(Context);
4179 FunctionDecl *Specialization = 0;
4180 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00004181 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
4182 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00004183 R, Specialization, Info)) {
4184 // FIXME: Keep track of almost-matches?
4185 (void)TDK;
4186 continue;
4187 }
4188
4189 Matches.push_back(Specialization);
4190 }
4191
4192 // Find the most specialized function template specialization.
4193 FunctionDecl *Specialization
4194 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4195 D.getIdentifierLoc(),
4196 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4197 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4198 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4199
4200 if (!Specialization)
4201 return true;
4202
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004203 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004204 Diag(D.getIdentifierLoc(),
4205 diag::err_explicit_instantiation_member_function_not_instantiated)
4206 << Specialization
4207 << (Specialization->getTemplateSpecializationKind() ==
4208 TSK_ExplicitSpecialization);
4209 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4210 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004211 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004212
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004213 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004214 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4215 PrevDecl = Specialization;
4216
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004217 if (PrevDecl) {
4218 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004219 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004220 PrevDecl,
4221 PrevDecl->getTemplateSpecializationKind(),
4222 PrevDecl->getPointOfInstantiation(),
4223 SuppressNew))
4224 return true;
4225
4226 // FIXME: We may still want to build some representation of this
4227 // explicit specialization.
4228 if (SuppressNew)
4229 return DeclPtrTy();
4230 }
4231
4232 if (TSK == TSK_ExplicitInstantiationDefinition)
4233 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4234 false, /*DefinitionRequired=*/true);
4235
4236 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4237
Douglas Gregore47f5a72009-10-14 23:41:34 +00004238 // C++0x [temp.explicit]p2:
4239 // If the explicit instantiation is for a member function, a member class
4240 // or a static data member of a class template specialization, the name of
4241 // the class template specialization in the qualified-id for the member
4242 // name shall be a simple-template-id.
4243 //
4244 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004245 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004246 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004247 D.getCXXScopeSpec().isSet() &&
4248 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4249 Diag(D.getIdentifierLoc(),
4250 diag::err_explicit_instantiation_without_qualified_id)
4251 << Specialization << D.getCXXScopeSpec().getRange();
4252
4253 CheckExplicitInstantiationScope(*this,
4254 FunTmpl? (NamedDecl *)FunTmpl
4255 : Specialization->getInstantiatedFromMemberFunction(),
4256 D.getIdentifierLoc(),
4257 D.getCXXScopeSpec().isSet());
4258
Douglas Gregor450f00842009-09-25 18:43:00 +00004259 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4260 return DeclPtrTy();
4261}
4262
Douglas Gregor333489b2009-03-27 23:10:48 +00004263Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004264Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4265 const CXXScopeSpec &SS, IdentifierInfo *Name,
4266 SourceLocation TagLoc, SourceLocation NameLoc) {
4267 // This has to hold, because SS is expected to be defined.
4268 assert(Name && "Expected a name in a dependent tag");
4269
4270 NestedNameSpecifier *NNS
4271 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4272 if (!NNS)
4273 return true;
4274
4275 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4276 if (T.isNull())
4277 return true;
4278
4279 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4280 QualType ElabType = Context.getElaboratedType(T, TagKind);
4281
4282 return ElabType.getAsOpaquePtr();
4283}
4284
4285Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004286Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4287 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004288 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004289 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4290 if (!NNS)
4291 return true;
4292
4293 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004294 if (T.isNull())
4295 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004296 return T.getAsOpaquePtr();
4297}
4298
Douglas Gregordce2b622009-04-01 00:28:59 +00004299Sema::TypeResult
4300Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4301 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004302 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004303 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004304 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004305 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004306 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004307 assert(TemplateId && "Expected a template specialization type");
4308
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004309 if (computeDeclContext(SS, false)) {
4310 // If we can compute a declaration context, then the "typename"
4311 // keyword was superfluous. Just build a QualifiedNameType to keep
4312 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004313
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004314 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4315 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4316 }
Mike Stump11289f42009-09-09 15:08:12 +00004317
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004318 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004319}
4320
Douglas Gregor333489b2009-03-27 23:10:48 +00004321/// \brief Build the type that describes a C++ typename specifier,
4322/// e.g., "typename T::type".
4323QualType
4324Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4325 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004326 CXXRecordDecl *CurrentInstantiation = 0;
4327 if (NNS->isDependent()) {
4328 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004329
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004330 // If the nested-name-specifier does not refer to the current
4331 // instantiation, then build a typename type.
4332 if (!CurrentInstantiation)
4333 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004334
Douglas Gregorc707da62009-09-02 13:12:51 +00004335 // The nested-name-specifier refers to the current instantiation, so the
4336 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004337 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004338 // extraneous "typename" keywords, and we retroactively apply this DR to
4339 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004340 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004341
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004342 DeclContext *Ctx = 0;
4343
4344 if (CurrentInstantiation)
4345 Ctx = CurrentInstantiation;
4346 else {
4347 CXXScopeSpec SS;
4348 SS.setScopeRep(NNS);
4349 SS.setRange(Range);
4350 if (RequireCompleteDeclContext(SS))
4351 return QualType();
4352
4353 Ctx = computeDeclContext(SS);
4354 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004355 assert(Ctx && "No declaration context?");
4356
4357 DeclarationName Name(&II);
John McCall9f3059a2009-10-09 21:13:30 +00004358 LookupResult Result;
4359 LookupQualifiedName(Result, Ctx, Name, LookupOrdinaryName, false);
Douglas Gregor333489b2009-03-27 23:10:48 +00004360 unsigned DiagID = 0;
4361 Decl *Referenced = 0;
4362 switch (Result.getKind()) {
4363 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004364 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004365 break;
4366
4367 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004368 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004369 // We found a type. Build a QualifiedNameType, since the
4370 // typename-specifier was just sugar. FIXME: Tell
4371 // QualifiedNameType that it has a "typename" prefix.
4372 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4373 }
4374
4375 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004376 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004377 break;
4378
4379 case LookupResult::FoundOverloaded:
4380 DiagID = diag::err_typename_nested_not_type;
4381 Referenced = *Result.begin();
4382 break;
4383
John McCall6538c932009-10-10 05:48:19 +00004384 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004385 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
4386 return QualType();
4387 }
4388
4389 // If we get here, it's because name lookup did not find a
4390 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004391 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004392 if (Referenced)
4393 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4394 << Name;
4395 return QualType();
4396}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004397
4398namespace {
4399 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00004400 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4401 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004402 SourceLocation Loc;
4403 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004404
Douglas Gregor15acfb92009-08-06 16:20:37 +00004405 public:
Mike Stump11289f42009-09-09 15:08:12 +00004406 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004407 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004408 DeclarationName Entity)
4409 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004410 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004411
4412 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004413 /// transformed.
4414 ///
4415 /// For the purposes of type reconstruction, a type has already been
4416 /// transformed if it is NULL or if it is not dependent.
4417 bool AlreadyTransformed(QualType T) {
4418 return T.isNull() || !T->isDependentType();
4419 }
Mike Stump11289f42009-09-09 15:08:12 +00004420
4421 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004422 /// rebuilt.
4423 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004424
Douglas Gregor15acfb92009-08-06 16:20:37 +00004425 /// \brief Returns the name of the entity whose type is being rebuilt.
4426 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004427
Douglas Gregoref6ab412009-10-27 06:26:26 +00004428 /// \brief Sets the "base" location and entity when that
4429 /// information is known based on another transformation.
4430 void setBase(SourceLocation Loc, DeclarationName Entity) {
4431 this->Loc = Loc;
4432 this->Entity = Entity;
4433 }
4434
Douglas Gregor15acfb92009-08-06 16:20:37 +00004435 /// \brief Transforms an expression by returning the expression itself
4436 /// (an identity function).
4437 ///
4438 /// FIXME: This is completely unsafe; we will need to actually clone the
4439 /// expressions.
4440 Sema::OwningExprResult TransformExpr(Expr *E) {
4441 return getSema().Owned(E);
4442 }
Mike Stump11289f42009-09-09 15:08:12 +00004443
Douglas Gregor15acfb92009-08-06 16:20:37 +00004444 /// \brief Transforms a typename type by determining whether the type now
4445 /// refers to a member of the current instantiation, and then
4446 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004447 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004448 };
4449}
4450
Mike Stump11289f42009-09-09 15:08:12 +00004451QualType
John McCall550e0c22009-10-21 00:40:46 +00004452CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4453 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004454 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004455
Douglas Gregor15acfb92009-08-06 16:20:37 +00004456 NestedNameSpecifier *NNS
4457 = TransformNestedNameSpecifier(T->getQualifier(),
4458 /*FIXME:*/SourceRange(getBaseLocation()));
4459 if (!NNS)
4460 return QualType();
4461
4462 // If the nested-name-specifier did not change, and we cannot compute the
4463 // context corresponding to the nested-name-specifier, then this
4464 // typename type will not change; exit early.
4465 CXXScopeSpec SS;
4466 SS.setRange(SourceRange(getBaseLocation()));
4467 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004468
4469 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004470 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004471 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004472
4473 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004474 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004475 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004476 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004477 = TransformType(QualType(TemplateId, 0));
4478 if (NewTemplateId.isNull())
4479 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004480
Douglas Gregor15acfb92009-08-06 16:20:37 +00004481 if (NNS == T->getQualifier() &&
4482 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004483 Result = QualType(T, 0);
4484 else
4485 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4486 } else
4487 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4488 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004489
John McCall0ad16662009-10-29 08:12:44 +00004490 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4491 NewTL.setNameLoc(TL.getNameLoc());
4492 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004493}
4494
4495/// \brief Rebuilds a type within the context of the current instantiation.
4496///
Mike Stump11289f42009-09-09 15:08:12 +00004497/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004498/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004499/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004500/// partial specialization thereof). This routine will rebuild that type now
4501/// that we have entered the declarator's scope, which may produce different
4502/// canonical types, e.g.,
4503///
4504/// \code
4505/// template<typename T>
4506/// struct X {
4507/// typedef T* pointer;
4508/// pointer data();
4509/// };
4510///
4511/// template<typename T>
4512/// typename X<T>::pointer X<T>::data() { ... }
4513/// \endcode
4514///
4515/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4516/// since we do not know that we can look into X<T> when we parsed the type.
4517/// This function will rebuild the type, performing the lookup of "pointer"
4518/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4519/// as the canonical type of T*, allowing the return types of the out-of-line
4520/// definition and the declaration to match.
4521QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4522 DeclarationName Name) {
4523 if (T.isNull() || !T->isDependentType())
4524 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004525
Douglas Gregor15acfb92009-08-06 16:20:37 +00004526 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4527 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004528}
Douglas Gregorbe999392009-09-15 16:23:51 +00004529
4530/// \brief Produces a formatted string that describes the binding of
4531/// template parameters to template arguments.
4532std::string
4533Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4534 const TemplateArgumentList &Args) {
4535 std::string Result;
4536
4537 if (!Params || Params->size() == 0)
4538 return Result;
4539
4540 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4541 if (I == 0)
4542 Result += "[with ";
4543 else
4544 Result += ", ";
4545
4546 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4547 Result += Id->getName();
4548 } else {
4549 Result += '$';
4550 Result += llvm::utostr(I);
4551 }
4552
4553 Result += " = ";
4554
4555 switch (Args[I].getKind()) {
4556 case TemplateArgument::Null:
4557 Result += "<no value>";
4558 break;
4559
4560 case TemplateArgument::Type: {
4561 std::string TypeStr;
4562 Args[I].getAsType().getAsStringInternal(TypeStr,
4563 Context.PrintingPolicy);
4564 Result += TypeStr;
4565 break;
4566 }
4567
4568 case TemplateArgument::Declaration: {
4569 bool Unnamed = true;
4570 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4571 if (ND->getDeclName()) {
4572 Unnamed = false;
4573 Result += ND->getNameAsString();
4574 }
4575 }
4576
4577 if (Unnamed) {
4578 Result += "<anonymous>";
4579 }
4580 break;
4581 }
4582
4583 case TemplateArgument::Integral: {
4584 Result += Args[I].getAsIntegral()->toString(10);
4585 break;
4586 }
4587
4588 case TemplateArgument::Expression: {
4589 assert(false && "No expressions in deduced template arguments!");
4590 Result += "<expression>";
4591 break;
4592 }
4593
4594 case TemplateArgument::Pack:
4595 // FIXME: Format template argument packs
4596 Result += "<template argument pack>";
4597 break;
4598 }
4599 }
4600
4601 Result += ']';
4602 return Result;
4603}