blob: c1d828fe45e9fe4d3808af04b389eb62d8a1d547 [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000020#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas 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 return 0;
62}
63
John McCalle66edc12009-11-24 19:00:30 +000064static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
65 LookupResult::Filter filter = R.makeFilter();
66 while (filter.hasNext()) {
67 NamedDecl *Orig = filter.next();
68 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
69 if (!Repl)
70 filter.erase();
71 else if (Repl != Orig)
72 filter.replace(Repl);
73 }
74 filter.done();
75}
76
Douglas Gregorb7bfe792009-09-02 22:59:36 +000077TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor3cf81312009-11-03 23:16:33 +000078 const CXXScopeSpec &SS,
79 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +000080 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +000081 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +000082 TemplateTy &TemplateResult) {
Douglas Gregor3cf81312009-11-03 23:16:33 +000083 DeclarationName TName;
84
85 switch (Name.getKind()) {
86 case UnqualifiedId::IK_Identifier:
87 TName = DeclarationName(Name.Identifier);
88 break;
89
90 case UnqualifiedId::IK_OperatorFunctionId:
91 TName = Context.DeclarationNames.getCXXOperatorName(
92 Name.OperatorFunctionId.Operator);
93 break;
94
Alexis Hunted0530f2009-11-28 08:58:14 +000095 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +000096 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
97 break;
Alexis Hunted0530f2009-11-28 08:58:14 +000098
Douglas Gregor3cf81312009-11-03 23:16:33 +000099 default:
100 return TNK_Non_template;
101 }
Mike Stump11289f42009-09-09 15:08:12 +0000102
John McCalle66edc12009-11-24 19:00:30 +0000103 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000104
John McCalle66edc12009-11-24 19:00:30 +0000105 LookupResult R(*this, TName, SourceLocation(), LookupOrdinaryName);
106 R.suppressDiagnostics();
107 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
108 if (R.empty())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000109 return TNK_Non_template;
110
John McCalld28ae272009-12-02 08:04:21 +0000111 TemplateName Template;
112 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000113
John McCalld28ae272009-12-02 08:04:21 +0000114 unsigned ResultCount = R.end() - R.begin();
115 if (ResultCount > 1) {
116 // We assume that we'll preserve the qualifier from a function
117 // template name in other ways.
118 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
119 TemplateKind = TNK_Function_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000120 } else {
John McCalld28ae272009-12-02 08:04:21 +0000121 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
122
123 if (SS.isSet() && !SS.isInvalid()) {
124 NestedNameSpecifier *Qualifier
125 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
126 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
127 } else {
128 Template = TemplateName(TD);
129 }
130
131 if (isa<FunctionTemplateDecl>(TD))
132 TemplateKind = TNK_Function_template;
133 else {
134 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
135 TemplateKind = TNK_Type_template;
136 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000137 }
Mike Stump11289f42009-09-09 15:08:12 +0000138
John McCalld28ae272009-12-02 08:04:21 +0000139 TemplateResult = TemplateTy::make(Template);
140 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000141}
142
143void Sema::LookupTemplateName(LookupResult &Found,
144 Scope *S, const CXXScopeSpec &SS,
145 QualType ObjectType,
146 bool EnteringContext) {
147 // Determine where to perform name lookup
148 DeclContext *LookupCtx = 0;
149 bool isDependent = false;
150 if (!ObjectType.isNull()) {
151 // This nested-name-specifier occurs in a member access expression, e.g.,
152 // x->B::f, and we are looking into the type of the object.
153 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
154 LookupCtx = computeDeclContext(ObjectType);
155 isDependent = ObjectType->isDependentType();
156 assert((isDependent || !ObjectType->isIncompleteType()) &&
157 "Caller should have completed object type");
158 } else if (SS.isSet()) {
159 // This nested-name-specifier occurs after another nested-name-specifier,
160 // so long into the context associated with the prior nested-name-specifier.
161 LookupCtx = computeDeclContext(SS, EnteringContext);
162 isDependent = isDependentScopeSpecifier(SS);
163
164 // The declaration context must be complete.
165 if (LookupCtx && RequireCompleteDeclContext(SS))
166 return;
167 }
168
169 bool ObjectTypeSearchedInScope = false;
170 if (LookupCtx) {
171 // Perform "qualified" name lookup into the declaration context we
172 // computed, which is either the type of the base of a member access
173 // expression or the declaration context associated with a prior
174 // nested-name-specifier.
175 LookupQualifiedName(Found, LookupCtx);
176
177 if (!ObjectType.isNull() && Found.empty()) {
178 // C++ [basic.lookup.classref]p1:
179 // In a class member access expression (5.2.5), if the . or -> token is
180 // immediately followed by an identifier followed by a <, the
181 // identifier must be looked up to determine whether the < is the
182 // beginning of a template argument list (14.2) or a less-than operator.
183 // The identifier is first looked up in the class of the object
184 // expression. If the identifier is not found, it is then looked up in
185 // the context of the entire postfix-expression and shall name a class
186 // or function template.
187 //
188 // FIXME: When we're instantiating a template, do we actually have to
189 // look in the scope of the template? Seems fishy...
190 if (S) LookupName(Found, S);
191 ObjectTypeSearchedInScope = true;
192 }
193 } else if (isDependent) {
194 // We cannot look into a dependent object type or
195 return;
196 } else {
197 // Perform unqualified name lookup in the current scope.
198 LookupName(Found, S);
199 }
200
201 // FIXME: Cope with ambiguous name-lookup results.
202 assert(!Found.isAmbiguous() &&
203 "Cannot handle template name-lookup ambiguities");
204
205 FilterAcceptableTemplateNames(Context, Found);
206 if (Found.empty())
207 return;
208
209 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
210 // C++ [basic.lookup.classref]p1:
211 // [...] If the lookup in the class of the object expression finds a
212 // template, the name is also looked up in the context of the entire
213 // postfix-expression and [...]
214 //
215 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
216 LookupOrdinaryName);
217 LookupName(FoundOuter, S);
218 FilterAcceptableTemplateNames(Context, FoundOuter);
219 // FIXME: Handle ambiguities in this lookup better
220
221 if (FoundOuter.empty()) {
222 // - if the name is not found, the name found in the class of the
223 // object expression is used, otherwise
224 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
225 // - if the name is found in the context of the entire
226 // postfix-expression and does not name a class template, the name
227 // found in the class of the object expression is used, otherwise
228 } else {
229 // - if the name found is a class template, it must refer to the same
230 // entity as the one found in the class of the object expression,
231 // otherwise the program is ill-formed.
232 if (!Found.isSingleResult() ||
233 Found.getFoundDecl()->getCanonicalDecl()
234 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
235 Diag(Found.getNameLoc(),
236 diag::err_nested_name_member_ref_lookup_ambiguous)
237 << Found.getLookupName();
238 Diag(Found.getRepresentativeDecl()->getLocation(),
239 diag::note_ambig_member_ref_object_type)
240 << ObjectType;
241 Diag(FoundOuter.getFoundDecl()->getLocation(),
242 diag::note_ambig_member_ref_scope);
243
244 // Recover by taking the template that we found in the object
245 // expression's type.
246 }
247 }
248 }
249}
250
John McCallcd4b4772009-12-02 03:53:29 +0000251/// ActOnDependentIdExpression - Handle a dependent id-expression that
252/// was just parsed. This is only possible with an explicit scope
253/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000254Sema::OwningExprResult
255Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
256 DeclarationName Name,
257 SourceLocation NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000258 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000259 const TemplateArgumentListInfo *TemplateArgs) {
260 NestedNameSpecifier *Qualifier
261 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
262
John McCallcd4b4772009-12-02 03:53:29 +0000263 if (!isAddressOfOperand &&
264 isa<CXXMethodDecl>(CurContext) &&
265 cast<CXXMethodDecl>(CurContext)->isInstance()) {
266 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
267
John McCalle66edc12009-11-24 19:00:30 +0000268 // Since the 'this' expression is synthesized, we don't need to
269 // perform the double-lookup check.
270 NamedDecl *FirstQualifierInScope = 0;
271
John McCall2d74de92009-12-01 22:10:20 +0000272 return Owned(CXXDependentScopeMemberExpr::Create(Context,
273 /*This*/ 0, ThisType,
274 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000275 /*Op*/ SourceLocation(),
276 Qualifier, SS.getRange(),
277 FirstQualifierInScope,
278 Name, NameLoc,
279 TemplateArgs));
280 }
281
282 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
283}
284
285Sema::OwningExprResult
286Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
287 DeclarationName Name,
288 SourceLocation NameLoc,
289 const TemplateArgumentListInfo *TemplateArgs) {
290 return Owned(DependentScopeDeclRefExpr::Create(Context,
291 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
292 SS.getRange(),
293 Name, NameLoc,
294 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000295}
296
Douglas Gregor5101c242008-12-05 18:15:24 +0000297/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
298/// that the template parameter 'PrevDecl' is being shadowed by a new
299/// declaration at location Loc. Returns true to indicate that this is
300/// an error, and false otherwise.
301bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000302 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000303
304 // Microsoft Visual C++ permits template parameters to be shadowed.
305 if (getLangOptions().Microsoft)
306 return false;
307
308 // C++ [temp.local]p4:
309 // A template-parameter shall not be redeclared within its
310 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000311 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000312 << cast<NamedDecl>(PrevDecl)->getDeclName();
313 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
314 return true;
315}
316
Douglas Gregor463421d2009-03-03 04:44:36 +0000317/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000318/// the parameter D to reference the templated declaration and return a pointer
319/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000320TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000321 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000322 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000323 return Temp;
324 }
325 return 0;
326}
327
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000328static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
329 const ParsedTemplateArgument &Arg) {
330
331 switch (Arg.getKind()) {
332 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000333 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000334 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
335 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000336 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000337 return TemplateArgumentLoc(TemplateArgument(T), DI);
338 }
339
340 case ParsedTemplateArgument::NonType: {
341 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
342 return TemplateArgumentLoc(TemplateArgument(E), E);
343 }
344
345 case ParsedTemplateArgument::Template: {
346 TemplateName Template
347 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
348 return TemplateArgumentLoc(TemplateArgument(Template),
349 Arg.getScopeSpec().getRange(),
350 Arg.getLocation());
351 }
352 }
353
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000354 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000355 return TemplateArgumentLoc();
356}
357
358/// \brief Translates template arguments as provided by the parser
359/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000360void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
361 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000362 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000363 TemplateArgs.addArgument(translateTemplateArgument(*this,
364 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000365}
366
Douglas Gregor5101c242008-12-05 18:15:24 +0000367/// ActOnTypeParameter - Called when a C++ template type parameter
368/// (e.g., "typename T") has been parsed. Typename specifies whether
369/// the keyword "typename" was used to declare the type parameter
370/// (otherwise, "class" was used), and KeyLoc is the location of the
371/// "class" or "typename" keyword. ParamName is the name of the
372/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000373/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000374/// If the type parameter has a default argument, it will be added
375/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000376Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000377 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000378 SourceLocation KeyLoc,
379 IdentifierInfo *ParamName,
380 SourceLocation ParamNameLoc,
381 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000382 assert(S->isTemplateParamScope() &&
383 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000384 bool Invalid = false;
385
386 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000387 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000388 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000389 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000390 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000391 }
392
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000393 SourceLocation Loc = ParamNameLoc;
394 if (!ParamName)
395 Loc = KeyLoc;
396
Douglas Gregor5101c242008-12-05 18:15:24 +0000397 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000398 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
399 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000400 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000401 if (Invalid)
402 Param->setInvalidDecl();
403
404 if (ParamName) {
405 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000406 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000407 IdResolver.AddDecl(Param);
408 }
409
Chris Lattner83f095c2009-03-28 19:18:32 +0000410 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000411}
412
Douglas Gregordba32632009-02-10 19:49:53 +0000413/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000414/// Default) to the given template type parameter (TypeParam).
415void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000416 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000417 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000418 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000419 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000420 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000421
John McCallbcd03502009-12-07 02:54:59 +0000422 TypeSourceInfo *DefaultTInfo;
423 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall0ad16662009-10-29 08:12:44 +0000424
John McCallbcd03502009-12-07 02:54:59 +0000425 assert(DefaultTInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000426
Anders Carlssond3824352009-06-12 22:30:13 +0000427 // C++0x [temp.param]p9:
428 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000429 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000430 if (Parm->isParameterPack()) {
431 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000432 return;
433 }
Mike Stump11289f42009-09-09 15:08:12 +0000434
Douglas Gregordba32632009-02-10 19:49:53 +0000435 // C++ [temp.param]p14:
436 // A template-parameter shall not be used in its own default argument.
437 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000438
Douglas Gregordba32632009-02-10 19:49:53 +0000439 // Check the template argument itself.
John McCallbcd03502009-12-07 02:54:59 +0000440 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000441 Parm->setInvalidDecl();
442 return;
443 }
444
John McCallbcd03502009-12-07 02:54:59 +0000445 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000446}
447
Douglas Gregor463421d2009-03-03 04:44:36 +0000448/// \brief Check that the type of a non-type template parameter is
449/// well-formed.
450///
451/// \returns the (possibly-promoted) parameter type if valid;
452/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000453QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000454Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
455 // C++ [temp.param]p4:
456 //
457 // A non-type template-parameter shall have one of the following
458 // (optionally cv-qualified) types:
459 //
460 // -- integral or enumeration type,
461 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000462 // -- pointer to object or pointer to function,
463 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000464 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
465 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000466 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000467 T->isReferenceType() ||
468 // -- pointer to member.
469 T->isMemberPointerType() ||
470 // If T is a dependent type, we can't do the check now, so we
471 // assume that it is well-formed.
472 T->isDependentType())
473 return T;
474 // C++ [temp.param]p8:
475 //
476 // A non-type template-parameter of type "array of T" or
477 // "function returning T" is adjusted to be of type "pointer to
478 // T" or "pointer to function returning T", respectively.
479 else if (T->isArrayType())
480 // FIXME: Keep the type prior to promotion?
481 return Context.getArrayDecayedType(T);
482 else if (T->isFunctionType())
483 // FIXME: Keep the type prior to promotion?
484 return Context.getPointerType(T);
485
486 Diag(Loc, diag::err_template_nontype_parm_bad_type)
487 << T;
488
489 return QualType();
490}
491
Douglas Gregor5101c242008-12-05 18:15:24 +0000492/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
493/// template parameter (e.g., "int Size" in "template<int Size>
494/// class Array") has been parsed. S is the current scope and D is
495/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000496Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000497 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000498 unsigned Position) {
John McCallbcd03502009-12-07 02:54:59 +0000499 TypeSourceInfo *TInfo = 0;
500 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000501
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000502 assert(S->isTemplateParamScope() &&
503 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000504 bool Invalid = false;
505
506 IdentifierInfo *ParamName = D.getIdentifier();
507 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000508 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000509 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000510 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000511 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000512 }
513
Douglas Gregor463421d2009-03-03 04:44:36 +0000514 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000515 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000516 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000517 Invalid = true;
518 }
Douglas Gregor81338792009-02-10 17:43:50 +0000519
Douglas Gregor5101c242008-12-05 18:15:24 +0000520 NonTypeTemplateParmDecl *Param
521 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000522 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000523 if (Invalid)
524 Param->setInvalidDecl();
525
526 if (D.getIdentifier()) {
527 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000528 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000529 IdResolver.AddDecl(Param);
530 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000531 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000532}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000533
Douglas Gregordba32632009-02-10 19:49:53 +0000534/// \brief Adds a default argument to the given non-type template
535/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000536void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000537 SourceLocation EqualLoc,
538 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000539 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000540 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000541 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000542
Douglas Gregordba32632009-02-10 19:49:53 +0000543 // C++ [temp.param]p14:
544 // A template-parameter shall not be used in its own default argument.
545 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000546
Douglas Gregordba32632009-02-10 19:49:53 +0000547 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000548 TemplateArgument Converted;
549 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
550 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000551 TemplateParm->setInvalidDecl();
552 return;
553 }
554
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000555 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000556}
557
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000558
559/// ActOnTemplateTemplateParameter - Called when a C++ template template
560/// parameter (e.g. T in template <template <typename> class T> class array)
561/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000562Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
563 SourceLocation TmpLoc,
564 TemplateParamsTy *Params,
565 IdentifierInfo *Name,
566 SourceLocation NameLoc,
567 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000568 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000569 assert(S->isTemplateParamScope() &&
570 "Template template parameter not in template parameter scope!");
571
572 // Construct the parameter object.
573 TemplateTemplateParmDecl *Param =
574 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
575 Position, Name,
576 (TemplateParameterList*)Params);
577
578 // Make sure the parameter is valid.
579 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
580 // do anything yet. However, if the template parameter list or (eventual)
581 // default value is ever invalidated, that will propagate here.
582 bool Invalid = false;
583 if (Invalid) {
584 Param->setInvalidDecl();
585 }
586
587 // If the tt-param has a name, then link the identifier into the scope
588 // and lookup mechanisms.
589 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000590 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000591 IdResolver.AddDecl(Param);
592 }
593
Chris Lattner83f095c2009-03-28 19:18:32 +0000594 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000595}
596
Douglas Gregordba32632009-02-10 19:49:53 +0000597/// \brief Adds a default argument to the given template template
598/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000599void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000600 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000601 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000602 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000603 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000604
Douglas Gregordba32632009-02-10 19:49:53 +0000605 // C++ [temp.param]p14:
606 // A template-parameter shall not be used in its own default argument.
607 // FIXME: Implement this check! Needs a recursive walk over the types.
608
Douglas Gregore62e6a02009-11-11 19:13:48 +0000609 // Check only that we have a template template argument. We don't want to
610 // try to check well-formedness now, because our template template parameter
611 // might have dependent types in its template parameters, which we wouldn't
612 // be able to match now.
613 //
614 // If none of the template template parameter's template arguments mention
615 // other template parameters, we could actually perform more checking here.
616 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000617 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000618 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
619 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
620 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000621 return;
622 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000623
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000624 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000625}
626
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000627/// ActOnTemplateParameterList - Builds a TemplateParameterList that
628/// contains the template parameters in Params/NumParams.
629Sema::TemplateParamsTy *
630Sema::ActOnTemplateParameterList(unsigned Depth,
631 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000632 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000633 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000634 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000635 SourceLocation RAngleLoc) {
636 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000637 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000638
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000639 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000640 (NamedDecl**)Params, NumParams,
641 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000642}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000643
Douglas Gregorc08f4892009-03-25 00:13:59 +0000644Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000645Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000646 SourceLocation KWLoc, const CXXScopeSpec &SS,
647 IdentifierInfo *Name, SourceLocation NameLoc,
648 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000649 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000650 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000651 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000652 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000653 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000654 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000655
656 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000657 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000658 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000659
John McCall27b5c252009-09-14 21:59:20 +0000660 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
661 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000662
663 // There is no such thing as an unnamed class template.
664 if (!Name) {
665 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000666 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000667 }
668
669 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000670 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000671 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000672 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000673 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000674 if (RequireCompleteDeclContext(SS))
675 return true;
676
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000677 SemanticContext = computeDeclContext(SS, true);
678 if (!SemanticContext) {
679 // FIXME: Produce a reasonable diagnostic here
680 return true;
681 }
Mike Stump11289f42009-09-09 15:08:12 +0000682
John McCall27b18f82009-11-17 02:14:36 +0000683 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000684 } else {
685 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000686 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000687 }
Mike Stump11289f42009-09-09 15:08:12 +0000688
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000689 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
690 NamedDecl *PrevDecl = 0;
691 if (Previous.begin() != Previous.end())
692 PrevDecl = *Previous.begin();
693
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000694 // If there is a previous declaration with the same name, check
695 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000696 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000697 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000698
699 // We may have found the injected-class-name of a class template,
700 // class template partial specialization, or class template specialization.
701 // In these cases, grab the template that is being defined or specialized.
702 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
703 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
704 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
705 PrevClassTemplate
706 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
707 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
708 PrevClassTemplate
709 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
710 ->getSpecializedTemplate();
711 }
712 }
713
John McCall90d3bb92009-12-17 23:21:11 +0000714 if (PrevDecl && TUK == TUK_Friend) {
715 // C++ [namespace.memdef]p3:
716 // [...] When looking for a prior declaration of a class or a function
717 // declared as a friend, and when the name of the friend class or
718 // function is neither a qualified name nor a template-id, scopes outside
719 // the innermost enclosing namespace scope are not considered.
720 DeclContext *OutermostContext = CurContext;
721 while (!OutermostContext->isFileContext())
722 OutermostContext = OutermostContext->getLookupParent();
723
724 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
725 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
726 SemanticContext = PrevDecl->getDeclContext();
727 } else {
728 // Declarations in outer scopes don't matter. However, the outermost
729 // context we computed is the semantic context for our new
730 // declaration.
731 PrevDecl = PrevClassTemplate = 0;
732 SemanticContext = OutermostContext;
733 }
734
735 if (CurContext->isDependentContext()) {
736 // If this is a dependent context, we don't want to link the friend
737 // class template to the template in scope, because that would perform
738 // checking of the template parameter lists that can't be performed
739 // until the outer context is instantiated.
740 PrevDecl = PrevClassTemplate = 0;
741 }
742 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
743 PrevDecl = PrevClassTemplate = 0;
744
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000745 if (PrevClassTemplate) {
746 // Ensure that the template parameter lists are compatible.
747 if (!TemplateParameterListsAreEqual(TemplateParams,
748 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000749 /*Complain=*/true,
750 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000751 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000752
753 // C++ [temp.class]p4:
754 // In a redeclaration, partial specialization, explicit
755 // specialization or explicit instantiation of a class template,
756 // the class-key shall agree in kind with the original class
757 // template declaration (7.1.5.3).
758 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000759 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000760 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000761 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000762 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000763 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000764 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000765 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000766 }
767
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000768 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000769 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000770 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
771 Diag(NameLoc, diag::err_redefinition) << Name;
772 Diag(Def->getLocation(), diag::note_previous_definition);
773 // FIXME: Would it make sense to try to "forget" the previous
774 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000775 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000776 }
777 }
778 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
779 // Maybe we will complain about the shadowed template parameter.
780 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
781 // Just pretend that we didn't see the previous declaration.
782 PrevDecl = 0;
783 } else if (PrevDecl) {
784 // C++ [temp]p5:
785 // A class template shall not have the same name as any other
786 // template, class, function, object, enumeration, enumerator,
787 // namespace, or type in the same scope (3.3), except as specified
788 // in (14.5.4).
789 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
790 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000791 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000792 }
793
Douglas Gregordba32632009-02-10 19:49:53 +0000794 // Check the template parameter list of this declaration, possibly
795 // merging in the template parameter list from the previous class
796 // template declaration.
797 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000798 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
799 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000800 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000801
Douglas Gregore362cea2009-05-10 22:57:19 +0000802 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000803 // declaration!
804
Mike Stump11289f42009-09-09 15:08:12 +0000805 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000806 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000807 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000808 PrevClassTemplate->getTemplatedDecl() : 0,
809 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000810
811 ClassTemplateDecl *NewTemplate
812 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
813 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000814 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000815 NewClass->setDescribedClassTemplate(NewTemplate);
816
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000817 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000818 QualType T =
819 Context.getTypeDeclType(NewClass,
820 PrevClassTemplate?
821 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000822 assert(T->isDependentType() && "Class template type is not dependent?");
823 (void)T;
824
Douglas Gregorcf915552009-10-13 16:30:37 +0000825 // If we are providing an explicit specialization of a member that is a
826 // class template, make a note of that.
827 if (PrevClassTemplate &&
828 PrevClassTemplate->getInstantiatedFromMemberTemplate())
829 PrevClassTemplate->setMemberSpecialization();
830
Anders Carlsson137108d2009-03-26 01:24:28 +0000831 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000832 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000833 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000834
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000835 // Set the lexical context of these templates
836 NewClass->setLexicalDeclContext(CurContext);
837 NewTemplate->setLexicalDeclContext(CurContext);
838
John McCall9bb74a52009-07-31 02:45:11 +0000839 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000840 NewClass->startDefinition();
841
842 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000843 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000844
John McCall27b5c252009-09-14 21:59:20 +0000845 if (TUK != TUK_Friend)
846 PushOnScopeChains(NewTemplate, S);
847 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000848 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000849 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000850 NewClass->setAccess(PrevClassTemplate->getAccess());
851 }
John McCall27b5c252009-09-14 21:59:20 +0000852
Douglas Gregor3dad8422009-09-26 06:47:28 +0000853 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
854 PrevClassTemplate != NULL);
855
John McCall27b5c252009-09-14 21:59:20 +0000856 // Friend templates are visible in fairly strange ways.
857 if (!CurContext->isDependentContext()) {
858 DeclContext *DC = SemanticContext->getLookupContext();
859 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
860 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
861 PushOnScopeChains(NewTemplate, EnclosingScope,
862 /* AddToContext = */ false);
863 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000864
865 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
866 NewClass->getLocation(),
867 NewTemplate,
868 /*FIXME:*/NewClass->getLocation());
869 Friend->setAccess(AS_public);
870 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000871 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000872
Douglas Gregordba32632009-02-10 19:49:53 +0000873 if (Invalid) {
874 NewTemplate->setInvalidDecl();
875 NewClass->setInvalidDecl();
876 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000877 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000878}
879
Douglas Gregored5731f2009-11-25 17:50:39 +0000880/// \brief Diagnose the presence of a default template argument on a
881/// template parameter, which is ill-formed in certain contexts.
882///
883/// \returns true if the default template argument should be dropped.
884static bool DiagnoseDefaultTemplateArgument(Sema &S,
885 Sema::TemplateParamListContext TPC,
886 SourceLocation ParamLoc,
887 SourceRange DefArgRange) {
888 switch (TPC) {
889 case Sema::TPC_ClassTemplate:
890 return false;
891
892 case Sema::TPC_FunctionTemplate:
893 // C++ [temp.param]p9:
894 // A default template-argument shall not be specified in a
895 // function template declaration or a function template
896 // definition [...]
897 // (This sentence is not in C++0x, per DR226).
898 if (!S.getLangOptions().CPlusPlus0x)
899 S.Diag(ParamLoc,
900 diag::err_template_parameter_default_in_function_template)
901 << DefArgRange;
902 return false;
903
904 case Sema::TPC_ClassTemplateMember:
905 // C++0x [temp.param]p9:
906 // A default template-argument shall not be specified in the
907 // template-parameter-lists of the definition of a member of a
908 // class template that appears outside of the member's class.
909 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
910 << DefArgRange;
911 return true;
912
913 case Sema::TPC_FriendFunctionTemplate:
914 // C++ [temp.param]p9:
915 // A default template-argument shall not be specified in a
916 // friend template declaration.
917 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
918 << DefArgRange;
919 return true;
920
921 // FIXME: C++0x [temp.param]p9 allows default template-arguments
922 // for friend function templates if there is only a single
923 // declaration (and it is a definition). Strange!
924 }
925
926 return false;
927}
928
Douglas Gregordba32632009-02-10 19:49:53 +0000929/// \brief Checks the validity of a template parameter list, possibly
930/// considering the template parameter list from a previous
931/// declaration.
932///
933/// If an "old" template parameter list is provided, it must be
934/// equivalent (per TemplateParameterListsAreEqual) to the "new"
935/// template parameter list.
936///
937/// \param NewParams Template parameter list for a new template
938/// declaration. This template parameter list will be updated with any
939/// default arguments that are carried through from the previous
940/// template parameter list.
941///
942/// \param OldParams If provided, template parameter list from a
943/// previous declaration of the same template. Default template
944/// arguments will be merged from the old template parameter list to
945/// the new template parameter list.
946///
Douglas Gregored5731f2009-11-25 17:50:39 +0000947/// \param TPC Describes the context in which we are checking the given
948/// template parameter list.
949///
Douglas Gregordba32632009-02-10 19:49:53 +0000950/// \returns true if an error occurred, false otherwise.
951bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000952 TemplateParameterList *OldParams,
953 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +0000954 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000955
Douglas Gregordba32632009-02-10 19:49:53 +0000956 // C++ [temp.param]p10:
957 // The set of default template-arguments available for use with a
958 // template declaration or definition is obtained by merging the
959 // default arguments from the definition (if in scope) and all
960 // declarations in scope in the same way default function
961 // arguments are (8.3.6).
962 bool SawDefaultArgument = false;
963 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000964
Anders Carlsson327865d2009-06-12 23:20:15 +0000965 bool SawParameterPack = false;
966 SourceLocation ParameterPackLoc;
967
Mike Stumpc89c8e32009-02-11 23:03:27 +0000968 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000969 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000970 if (OldParams)
971 OldParam = OldParams->begin();
972
973 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
974 NewParamEnd = NewParams->end();
975 NewParam != NewParamEnd; ++NewParam) {
976 // Variables used to diagnose redundant default arguments
977 bool RedundantDefaultArg = false;
978 SourceLocation OldDefaultLoc;
979 SourceLocation NewDefaultLoc;
980
981 // Variables used to diagnose missing default arguments
982 bool MissingDefaultArg = false;
983
Anders Carlsson327865d2009-06-12 23:20:15 +0000984 // C++0x [temp.param]p11:
985 // If a template parameter of a class template is a template parameter pack,
986 // it must be the last template parameter.
987 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +0000988 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +0000989 diag::err_template_param_pack_must_be_last_template_parameter);
990 Invalid = true;
991 }
992
Douglas Gregordba32632009-02-10 19:49:53 +0000993 if (TemplateTypeParmDecl *NewTypeParm
994 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +0000995 // Check the presence of a default argument here.
996 if (NewTypeParm->hasDefaultArgument() &&
997 DiagnoseDefaultTemplateArgument(*this, TPC,
998 NewTypeParm->getLocation(),
999 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1000 .getFullSourceRange()))
1001 NewTypeParm->removeDefaultArgument();
1002
1003 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001004 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001005 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001006
Anders Carlsson327865d2009-06-12 23:20:15 +00001007 if (NewTypeParm->isParameterPack()) {
1008 assert(!NewTypeParm->hasDefaultArgument() &&
1009 "Parameter packs can't have a default argument!");
1010 SawParameterPack = true;
1011 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001012 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001013 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001014 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1015 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1016 SawDefaultArgument = true;
1017 RedundantDefaultArg = true;
1018 PreviousDefaultArgLoc = NewDefaultLoc;
1019 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1020 // Merge the default argument from the old declaration to the
1021 // new declaration.
1022 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001023 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001024 true);
1025 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1026 } else if (NewTypeParm->hasDefaultArgument()) {
1027 SawDefaultArgument = true;
1028 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1029 } else if (SawDefaultArgument)
1030 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001031 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001032 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001033 // Check the presence of a default argument here.
1034 if (NewNonTypeParm->hasDefaultArgument() &&
1035 DiagnoseDefaultTemplateArgument(*this, TPC,
1036 NewNonTypeParm->getLocation(),
1037 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1038 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1039 NewNonTypeParm->setDefaultArgument(0);
1040 }
1041
Mike Stump12b8ce12009-08-04 21:02:39 +00001042 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001043 NonTypeTemplateParmDecl *OldNonTypeParm
1044 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001045 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001046 NewNonTypeParm->hasDefaultArgument()) {
1047 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1048 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1049 SawDefaultArgument = true;
1050 RedundantDefaultArg = true;
1051 PreviousDefaultArgLoc = NewDefaultLoc;
1052 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1053 // Merge the default argument from the old declaration to the
1054 // new declaration.
1055 SawDefaultArgument = true;
1056 // FIXME: We need to create a new kind of "default argument"
1057 // expression that points to a previous template template
1058 // parameter.
1059 NewNonTypeParm->setDefaultArgument(
1060 OldNonTypeParm->getDefaultArgument());
1061 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1062 } else if (NewNonTypeParm->hasDefaultArgument()) {
1063 SawDefaultArgument = true;
1064 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1065 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001066 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001067 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001068 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001069 TemplateTemplateParmDecl *NewTemplateParm
1070 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001071 if (NewTemplateParm->hasDefaultArgument() &&
1072 DiagnoseDefaultTemplateArgument(*this, TPC,
1073 NewTemplateParm->getLocation(),
1074 NewTemplateParm->getDefaultArgument().getSourceRange()))
1075 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1076
1077 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001078 TemplateTemplateParmDecl *OldTemplateParm
1079 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001080 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001081 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001082 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1083 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001084 SawDefaultArgument = true;
1085 RedundantDefaultArg = true;
1086 PreviousDefaultArgLoc = NewDefaultLoc;
1087 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1088 // Merge the default argument from the old declaration to the
1089 // new declaration.
1090 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001091 // FIXME: We need to create a new kind of "default argument" expression
1092 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001093 NewTemplateParm->setDefaultArgument(
1094 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001095 PreviousDefaultArgLoc
1096 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001097 } else if (NewTemplateParm->hasDefaultArgument()) {
1098 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001099 PreviousDefaultArgLoc
1100 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001101 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001102 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001103 }
1104
1105 if (RedundantDefaultArg) {
1106 // C++ [temp.param]p12:
1107 // A template-parameter shall not be given default arguments
1108 // by two different declarations in the same scope.
1109 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1110 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1111 Invalid = true;
1112 } else if (MissingDefaultArg) {
1113 // C++ [temp.param]p11:
1114 // If a template-parameter has a default template-argument,
1115 // all subsequent template-parameters shall have a default
1116 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001117 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001118 diag::err_template_param_default_arg_missing);
1119 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1120 Invalid = true;
1121 }
1122
1123 // If we have an old template parameter list that we're merging
1124 // in, move on to the next parameter.
1125 if (OldParams)
1126 ++OldParam;
1127 }
1128
1129 return Invalid;
1130}
Douglas Gregord32e0282009-02-09 23:23:08 +00001131
Mike Stump11289f42009-09-09 15:08:12 +00001132/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001133/// specifier, returning the template parameter list that applies to the
1134/// name.
1135///
1136/// \param DeclStartLoc the start of the declaration that has a scope
1137/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001138///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001139/// \param SS the scope specifier that will be matched to the given template
1140/// parameter lists. This scope specifier precedes a qualified name that is
1141/// being declared.
1142///
1143/// \param ParamLists the template parameter lists, from the outermost to the
1144/// innermost template parameter lists.
1145///
1146/// \param NumParamLists the number of template parameter lists in ParamLists.
1147///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001148/// \param IsExplicitSpecialization will be set true if the entity being
1149/// declared is an explicit specialization, false otherwise.
1150///
Mike Stump11289f42009-09-09 15:08:12 +00001151/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001152/// name that is preceded by the scope specifier @p SS. This template
1153/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001154/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001155/// template specialization), or may be NULL (if we were's declaring isn't
1156/// itself a template).
1157TemplateParameterList *
1158Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1159 const CXXScopeSpec &SS,
1160 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001161 unsigned NumParamLists,
1162 bool &IsExplicitSpecialization) {
1163 IsExplicitSpecialization = false;
1164
Douglas Gregord8d297c2009-07-21 23:53:31 +00001165 // Find the template-ids that occur within the nested-name-specifier. These
1166 // template-ids will match up with the template parameter lists.
1167 llvm::SmallVector<const TemplateSpecializationType *, 4>
1168 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001169 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1170 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001171 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1172 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001173 const Type *T = NNS->getAsType();
1174 if (!T) break;
1175
1176 // C++0x [temp.expl.spec]p17:
1177 // A member or a member template may be nested within many
1178 // enclosing class templates. In an explicit specialization for
1179 // such a member, the member declaration shall be preceded by a
1180 // template<> for each enclosing class template that is
1181 // explicitly specialized.
1182 // We interpret this as forbidding typedefs of template
1183 // specializations in the scope specifiers of out-of-line decls.
1184 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) {
1185 const Type *UnderlyingT = TT->LookThroughTypedefs().getTypePtr();
1186 if (isa<TemplateSpecializationType>(UnderlyingT))
1187 // FIXME: better source location information.
1188 Diag(DeclStartLoc, diag::err_typedef_in_def_scope) << QualType(T,0);
1189 T = UnderlyingT;
1190 }
1191
Mike Stump11289f42009-09-09 15:08:12 +00001192 if (const TemplateSpecializationType *SpecType
John McCall90034062009-12-15 02:19:47 +00001193 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001194 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1195 if (!Template)
1196 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001197
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001198 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001199 ClassTemplateSpecializationDecl *SpecDecl
1200 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1201 // If the nested name specifier refers to an explicit specialization,
1202 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001203 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1204 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001205 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001206 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001207 }
Mike Stump11289f42009-09-09 15:08:12 +00001208
Douglas Gregord8d297c2009-07-21 23:53:31 +00001209 TemplateIdsInSpecifier.push_back(SpecType);
1210 }
1211 }
Mike Stump11289f42009-09-09 15:08:12 +00001212
Douglas Gregord8d297c2009-07-21 23:53:31 +00001213 // Reverse the list of template-ids in the scope specifier, so that we can
1214 // more easily match up the template-ids and the template parameter lists.
1215 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001216
Douglas Gregord8d297c2009-07-21 23:53:31 +00001217 SourceLocation FirstTemplateLoc = DeclStartLoc;
1218 if (NumParamLists)
1219 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001220
Douglas Gregord8d297c2009-07-21 23:53:31 +00001221 // Match the template-ids found in the specifier to the template parameter
1222 // lists.
1223 unsigned Idx = 0;
1224 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1225 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001226 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1227 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001228 if (Idx >= NumParamLists) {
1229 // We have a template-id without a corresponding template parameter
1230 // list.
1231 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001232 // FIXME: the location information here isn't great.
1233 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001234 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001235 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001236 << SS.getRange();
1237 } else {
1238 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1239 << SS.getRange()
1240 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1241 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001242 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001243 }
1244 return 0;
1245 }
Mike Stump11289f42009-09-09 15:08:12 +00001246
Douglas Gregord8d297c2009-07-21 23:53:31 +00001247 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001248 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001249 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001250 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1251
Mike Stump11289f42009-09-09 15:08:12 +00001252 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001253 = dyn_cast<ClassTemplateDecl>(Template)) {
1254 TemplateParameterList *ExpectedTemplateParams = 0;
1255 // Is this template-id naming the primary template?
1256 if (Context.hasSameType(TemplateId,
1257 ClassTemplate->getInjectedClassNameType(Context)))
1258 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1259 // ... or a partial specialization?
1260 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1261 = ClassTemplate->findPartialSpecialization(TemplateId))
1262 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1263
1264 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001265 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001266 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001267 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001268 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001269
1270 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001271 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001272 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001273 diag::err_template_param_list_matches_nontemplate)
1274 << TemplateId
1275 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001276 else
1277 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001278 }
Mike Stump11289f42009-09-09 15:08:12 +00001279
Douglas Gregord8d297c2009-07-21 23:53:31 +00001280 // If there were at least as many template-ids as there were template
1281 // parameter lists, then there are no template parameter lists remaining for
1282 // the declaration itself.
1283 if (Idx >= NumParamLists)
1284 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001285
Douglas Gregord8d297c2009-07-21 23:53:31 +00001286 // If there were too many template parameter lists, complain about that now.
1287 if (Idx != NumParamLists - 1) {
1288 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001289 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001290 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001291 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1292 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001293 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1294 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001295
1296 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1297 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1298 diag::note_explicit_template_spec_does_not_need_header)
1299 << ExplicitSpecializationsInSpecifier.back();
1300 ExplicitSpecializationsInSpecifier.pop_back();
1301 }
1302
Douglas Gregord8d297c2009-07-21 23:53:31 +00001303 ++Idx;
1304 }
1305 }
Mike Stump11289f42009-09-09 15:08:12 +00001306
Douglas Gregord8d297c2009-07-21 23:53:31 +00001307 // Return the last template parameter list, which corresponds to the
1308 // entity being declared.
1309 return ParamLists[NumParamLists - 1];
1310}
1311
Douglas Gregordc572a32009-03-30 22:58:21 +00001312QualType Sema::CheckTemplateIdType(TemplateName Name,
1313 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001314 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001315 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001316 if (!Template) {
1317 // The template name does not resolve to a template, so we just
1318 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001319 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001320 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001321
Douglas Gregorc40290e2009-03-09 23:48:35 +00001322 // Check that the template argument list is well-formed for this
1323 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001324 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001325 TemplateArgs.size());
1326 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001327 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001328 return QualType();
1329
Mike Stump11289f42009-09-09 15:08:12 +00001330 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001331 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001332 "Converted template argument list is too short!");
1333
1334 QualType CanonType;
1335
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001336 if (Name.isDependent() ||
1337 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001338 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001339 // This class template specialization is a dependent
1340 // type. Therefore, its canonical type is another class template
1341 // specialization type that contains all of the converted
1342 // arguments in canonical form. This ensures that, e.g., A<T> and
1343 // A<T, T> have identical types when A is declared as:
1344 //
1345 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001346 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001347 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001348 Converted.getFlatArguments(),
1349 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001350
Douglas Gregora8e02e72009-07-28 23:00:59 +00001351 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001352 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001353 // In the future, we need to teach getTemplateSpecializationType to only
1354 // build the canonical type and return that to us.
1355 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001356 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001357 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001358 // Find the class template specialization declaration that
1359 // corresponds to these arguments.
1360 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001361 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001362 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001363 Converted.flatSize(),
1364 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001365 void *InsertPos = 0;
1366 ClassTemplateSpecializationDecl *Decl
1367 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1368 if (!Decl) {
1369 // This is the first time we have referenced this class template
1370 // specialization. Create the canonical declaration and add it to
1371 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001372 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001373 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001374 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001375 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001376 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001377 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1378 Decl->setLexicalDeclContext(CurContext);
1379 }
1380
1381 CanonType = Context.getTypeDeclType(Decl);
1382 }
Mike Stump11289f42009-09-09 15:08:12 +00001383
Douglas Gregorc40290e2009-03-09 23:48:35 +00001384 // Build the fully-sugared type for this class template
1385 // specialization, which refers back to the class template
1386 // specialization we created or found.
John McCall6b51f282009-11-23 01:53:49 +00001387 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001388}
1389
Douglas Gregor67a65642009-02-17 23:15:12 +00001390Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001391Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001392 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001393 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001394 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001395 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001396
Douglas Gregorc40290e2009-03-09 23:48:35 +00001397 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001398 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001399 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001400
John McCall6b51f282009-11-23 01:53:49 +00001401 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001402 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001403
1404 if (Result.isNull())
1405 return true;
1406
John McCallbcd03502009-12-07 02:54:59 +00001407 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001408 TemplateSpecializationTypeLoc TL
1409 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1410 TL.setTemplateNameLoc(TemplateLoc);
1411 TL.setLAngleLoc(LAngleLoc);
1412 TL.setRAngleLoc(RAngleLoc);
1413 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1414 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1415
1416 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001417}
John McCall06f6fe8d2009-09-04 01:14:41 +00001418
John McCalld8fe9af2009-09-08 17:47:29 +00001419Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1420 TagUseKind TUK,
1421 DeclSpec::TST TagSpec,
1422 SourceLocation TagLoc) {
1423 if (TypeResult.isInvalid())
1424 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001425
John McCall0ad16662009-10-29 08:12:44 +00001426 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001427 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001428 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001429
John McCalld8fe9af2009-09-08 17:47:29 +00001430 // Verify the tag specifier.
1431 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001432
John McCalld8fe9af2009-09-08 17:47:29 +00001433 if (const RecordType *RT = Type->getAs<RecordType>()) {
1434 RecordDecl *D = RT->getDecl();
1435
1436 IdentifierInfo *Id = D->getIdentifier();
1437 assert(Id && "templated class must have an identifier");
1438
1439 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1440 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001441 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001442 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1443 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001444 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001445 }
1446 }
1447
John McCalld8fe9af2009-09-08 17:47:29 +00001448 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1449
1450 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001451}
1452
John McCalle66edc12009-11-24 19:00:30 +00001453Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1454 LookupResult &R,
1455 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001456 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001457 // FIXME: Can we do any checking at this point? I guess we could check the
1458 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001459 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001460 // though.
John McCalle66edc12009-11-24 19:00:30 +00001461
1462 // These should be filtered out by our callers.
1463 assert(!R.empty() && "empty lookup results when building templateid");
1464 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1465
1466 NestedNameSpecifier *Qualifier = 0;
1467 SourceRange QualifierRange;
1468 if (SS.isSet()) {
1469 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1470 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001471 }
1472
John McCalle66edc12009-11-24 19:00:30 +00001473 bool Dependent
1474 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1475 &TemplateArgs);
1476 UnresolvedLookupExpr *ULE
1477 = UnresolvedLookupExpr::Create(Context, Dependent,
1478 Qualifier, QualifierRange,
1479 R.getLookupName(), R.getNameLoc(),
1480 RequiresADL, TemplateArgs);
1481 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1482 ULE->addDecl(*I);
1483
1484 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001485}
1486
John McCalle66edc12009-11-24 19:00:30 +00001487// We actually only call this from template instantiation.
1488Sema::OwningExprResult
1489Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1490 DeclarationName Name,
1491 SourceLocation NameLoc,
1492 const TemplateArgumentListInfo &TemplateArgs) {
1493 DeclContext *DC;
1494 if (!(DC = computeDeclContext(SS, false)) ||
1495 DC->isDependentContext() ||
1496 RequireCompleteDeclContext(SS))
1497 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001498
John McCalle66edc12009-11-24 19:00:30 +00001499 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1500 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00001501
John McCalle66edc12009-11-24 19:00:30 +00001502 if (R.isAmbiguous())
1503 return ExprError();
1504
1505 if (R.empty()) {
1506 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1507 << Name << SS.getRange();
1508 return ExprError();
1509 }
1510
1511 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1512 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1513 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1514 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1515 return ExprError();
1516 }
1517
1518 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001519}
1520
Douglas Gregorb67535d2009-03-31 00:43:58 +00001521/// \brief Form a dependent template name.
1522///
1523/// This action forms a dependent template name given the template
1524/// name and its (presumably dependent) scope specifier. For
1525/// example, given "MetaFun::template apply", the scope specifier \p
1526/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1527/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001528Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001529Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001530 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001531 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001532 TypeTy *ObjectType,
1533 bool EnteringContext) {
Mike Stump11289f42009-09-09 15:08:12 +00001534 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001535 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001536 (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001537 // C++0x [temp.names]p5:
1538 // If a name prefixed by the keyword template is not the name of
1539 // a template, the program is ill-formed. [Note: the keyword
1540 // template may not be applied to non-template members of class
1541 // templates. -end note ] [ Note: as is the case with the
1542 // typename prefix, the template prefix is allowed in cases
1543 // where it is not strictly necessary; i.e., when the
1544 // nested-name-specifier or the expression on the left of the ->
1545 // or . is not dependent on a template-parameter, or the use
1546 // does not appear in the scope of a template. -end note]
1547 //
1548 // Note: C++03 was more strict here, because it banned the use of
1549 // the "template" keyword prior to a template-name that was not a
1550 // dependent name. C++ DR468 relaxed this requirement (the
1551 // "template" keyword is now permitted). We follow the C++0x
1552 // rules, even in C++03 mode, retroactively applying the DR.
1553 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001554 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001555 EnteringContext, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001556 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001557 Diag(Name.getSourceRange().getBegin(),
1558 diag::err_template_kw_refers_to_non_template)
1559 << GetNameFromUnqualifiedId(Name)
1560 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001561 return TemplateTy();
1562 }
1563
1564 return Template;
1565 }
1566
Mike Stump11289f42009-09-09 15:08:12 +00001567 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001568 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001569
1570 switch (Name.getKind()) {
1571 case UnqualifiedId::IK_Identifier:
1572 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1573 Name.Identifier));
1574
Douglas Gregor71395fa2009-11-04 00:56:37 +00001575 case UnqualifiedId::IK_OperatorFunctionId:
1576 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1577 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001578
1579 case UnqualifiedId::IK_LiteralOperatorId:
1580 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1581
Douglas Gregor3cf81312009-11-03 23:16:33 +00001582 default:
1583 break;
1584 }
1585
1586 Diag(Name.getSourceRange().getBegin(),
1587 diag::err_template_kw_refers_to_non_template)
1588 << GetNameFromUnqualifiedId(Name)
1589 << Name.getSourceRange();
1590 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001591}
1592
Mike Stump11289f42009-09-09 15:08:12 +00001593bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001594 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001595 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001596 const TemplateArgument &Arg = AL.getArgument();
1597
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001598 // Check template type parameter.
1599 if (Arg.getKind() != TemplateArgument::Type) {
1600 // C++ [temp.arg.type]p1:
1601 // A template-argument for a template-parameter which is a
1602 // type shall be a type-id.
1603
1604 // We have a template type parameter but the template argument
1605 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001606 SourceRange SR = AL.getSourceRange();
1607 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001608 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001609
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001610 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001611 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001612
John McCallbcd03502009-12-07 02:54:59 +00001613 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001614 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001615
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001616 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001617 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001618 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001619 return false;
1620}
1621
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001622/// \brief Substitute template arguments into the default template argument for
1623/// the given template type parameter.
1624///
1625/// \param SemaRef the semantic analysis object for which we are performing
1626/// the substitution.
1627///
1628/// \param Template the template that we are synthesizing template arguments
1629/// for.
1630///
1631/// \param TemplateLoc the location of the template name that started the
1632/// template-id we are checking.
1633///
1634/// \param RAngleLoc the location of the right angle bracket ('>') that
1635/// terminates the template-id.
1636///
1637/// \param Param the template template parameter whose default we are
1638/// substituting into.
1639///
1640/// \param Converted the list of template arguments provided for template
1641/// parameters that precede \p Param in the template parameter list.
1642///
1643/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001644static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001645SubstDefaultTemplateArgument(Sema &SemaRef,
1646 TemplateDecl *Template,
1647 SourceLocation TemplateLoc,
1648 SourceLocation RAngleLoc,
1649 TemplateTypeParmDecl *Param,
1650 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001651 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001652
1653 // If the argument type is dependent, instantiate it now based
1654 // on the previously-computed template arguments.
1655 if (ArgType->getType()->isDependentType()) {
1656 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1657 /*TakeArgs=*/false);
1658
1659 MultiLevelTemplateArgumentList AllTemplateArgs
1660 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1661
1662 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1663 Template, Converted.getFlatArguments(),
1664 Converted.flatSize(),
1665 SourceRange(TemplateLoc, RAngleLoc));
1666
1667 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1668 Param->getDefaultArgumentLoc(),
1669 Param->getDeclName());
1670 }
1671
1672 return ArgType;
1673}
1674
1675/// \brief Substitute template arguments into the default template argument for
1676/// the given non-type template parameter.
1677///
1678/// \param SemaRef the semantic analysis object for which we are performing
1679/// the substitution.
1680///
1681/// \param Template the template that we are synthesizing template arguments
1682/// for.
1683///
1684/// \param TemplateLoc the location of the template name that started the
1685/// template-id we are checking.
1686///
1687/// \param RAngleLoc the location of the right angle bracket ('>') that
1688/// terminates the template-id.
1689///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001690/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001691/// substituting into.
1692///
1693/// \param Converted the list of template arguments provided for template
1694/// parameters that precede \p Param in the template parameter list.
1695///
1696/// \returns the substituted template argument, or NULL if an error occurred.
1697static Sema::OwningExprResult
1698SubstDefaultTemplateArgument(Sema &SemaRef,
1699 TemplateDecl *Template,
1700 SourceLocation TemplateLoc,
1701 SourceLocation RAngleLoc,
1702 NonTypeTemplateParmDecl *Param,
1703 TemplateArgumentListBuilder &Converted) {
1704 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1705 /*TakeArgs=*/false);
1706
1707 MultiLevelTemplateArgumentList AllTemplateArgs
1708 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1709
1710 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1711 Template, Converted.getFlatArguments(),
1712 Converted.flatSize(),
1713 SourceRange(TemplateLoc, RAngleLoc));
1714
1715 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1716}
1717
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001718/// \brief Substitute template arguments into the default template argument for
1719/// the given template template parameter.
1720///
1721/// \param SemaRef the semantic analysis object for which we are performing
1722/// the substitution.
1723///
1724/// \param Template the template that we are synthesizing template arguments
1725/// for.
1726///
1727/// \param TemplateLoc the location of the template name that started the
1728/// template-id we are checking.
1729///
1730/// \param RAngleLoc the location of the right angle bracket ('>') that
1731/// terminates the template-id.
1732///
1733/// \param Param the template template parameter whose default we are
1734/// substituting into.
1735///
1736/// \param Converted the list of template arguments provided for template
1737/// parameters that precede \p Param in the template parameter list.
1738///
1739/// \returns the substituted template argument, or NULL if an error occurred.
1740static TemplateName
1741SubstDefaultTemplateArgument(Sema &SemaRef,
1742 TemplateDecl *Template,
1743 SourceLocation TemplateLoc,
1744 SourceLocation RAngleLoc,
1745 TemplateTemplateParmDecl *Param,
1746 TemplateArgumentListBuilder &Converted) {
1747 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1748 /*TakeArgs=*/false);
1749
1750 MultiLevelTemplateArgumentList AllTemplateArgs
1751 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1752
1753 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1754 Template, Converted.getFlatArguments(),
1755 Converted.flatSize(),
1756 SourceRange(TemplateLoc, RAngleLoc));
1757
1758 return SemaRef.SubstTemplateName(
1759 Param->getDefaultArgument().getArgument().getAsTemplate(),
1760 Param->getDefaultArgument().getTemplateNameLoc(),
1761 AllTemplateArgs);
1762}
1763
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001764/// \brief If the given template parameter has a default template
1765/// argument, substitute into that default template argument and
1766/// return the corresponding template argument.
1767TemplateArgumentLoc
1768Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1769 SourceLocation TemplateLoc,
1770 SourceLocation RAngleLoc,
1771 Decl *Param,
1772 TemplateArgumentListBuilder &Converted) {
1773 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1774 if (!TypeParm->hasDefaultArgument())
1775 return TemplateArgumentLoc();
1776
John McCallbcd03502009-12-07 02:54:59 +00001777 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001778 TemplateLoc,
1779 RAngleLoc,
1780 TypeParm,
1781 Converted);
1782 if (DI)
1783 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1784
1785 return TemplateArgumentLoc();
1786 }
1787
1788 if (NonTypeTemplateParmDecl *NonTypeParm
1789 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1790 if (!NonTypeParm->hasDefaultArgument())
1791 return TemplateArgumentLoc();
1792
1793 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1794 TemplateLoc,
1795 RAngleLoc,
1796 NonTypeParm,
1797 Converted);
1798 if (Arg.isInvalid())
1799 return TemplateArgumentLoc();
1800
1801 Expr *ArgE = Arg.takeAs<Expr>();
1802 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1803 }
1804
1805 TemplateTemplateParmDecl *TempTempParm
1806 = cast<TemplateTemplateParmDecl>(Param);
1807 if (!TempTempParm->hasDefaultArgument())
1808 return TemplateArgumentLoc();
1809
1810 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1811 TemplateLoc,
1812 RAngleLoc,
1813 TempTempParm,
1814 Converted);
1815 if (TName.isNull())
1816 return TemplateArgumentLoc();
1817
1818 return TemplateArgumentLoc(TemplateArgument(TName),
1819 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1820 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1821}
1822
Douglas Gregorda0fb532009-11-11 19:31:23 +00001823/// \brief Check that the given template argument corresponds to the given
1824/// template parameter.
1825bool Sema::CheckTemplateArgument(NamedDecl *Param,
1826 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001827 TemplateDecl *Template,
1828 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001829 SourceLocation RAngleLoc,
1830 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001831 // Check template type parameters.
1832 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001833 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001834
Douglas Gregoreebed722009-11-11 19:41:09 +00001835 // Check non-type template parameters.
1836 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001837 // Do substitution on the type of the non-type template parameter
1838 // with the template arguments we've seen thus far.
1839 QualType NTTPType = NTTP->getType();
1840 if (NTTPType->isDependentType()) {
1841 // Do substitution on the type of the non-type template parameter.
1842 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1843 NTTP, Converted.getFlatArguments(),
1844 Converted.flatSize(),
1845 SourceRange(TemplateLoc, RAngleLoc));
1846
1847 TemplateArgumentList TemplateArgs(Context, Converted,
1848 /*TakeArgs=*/false);
1849 NTTPType = SubstType(NTTPType,
1850 MultiLevelTemplateArgumentList(TemplateArgs),
1851 NTTP->getLocation(),
1852 NTTP->getDeclName());
1853 // If that worked, check the non-type template parameter type
1854 // for validity.
1855 if (!NTTPType.isNull())
1856 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1857 NTTP->getLocation());
1858 if (NTTPType.isNull())
1859 return true;
1860 }
1861
1862 switch (Arg.getArgument().getKind()) {
1863 case TemplateArgument::Null:
1864 assert(false && "Should never see a NULL template argument here");
1865 return true;
1866
1867 case TemplateArgument::Expression: {
1868 Expr *E = Arg.getArgument().getAsExpr();
1869 TemplateArgument Result;
1870 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1871 return true;
1872
1873 Converted.Append(Result);
1874 break;
1875 }
1876
1877 case TemplateArgument::Declaration:
1878 case TemplateArgument::Integral:
1879 // We've already checked this template argument, so just copy
1880 // it to the list of converted arguments.
1881 Converted.Append(Arg.getArgument());
1882 break;
1883
1884 case TemplateArgument::Template:
1885 // We were given a template template argument. It may not be ill-formed;
1886 // see below.
1887 if (DependentTemplateName *DTN
1888 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1889 // We have a template argument such as \c T::template X, which we
1890 // parsed as a template template argument. However, since we now
1891 // know that we need a non-type template argument, convert this
1892 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00001893 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1894 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00001895 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00001896 DTN->getIdentifier(),
1897 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00001898
1899 TemplateArgument Result;
1900 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1901 return true;
1902
1903 Converted.Append(Result);
1904 break;
1905 }
1906
1907 // We have a template argument that actually does refer to a class
1908 // template, template alias, or template template parameter, and
1909 // therefore cannot be a non-type template argument.
1910 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1911 << Arg.getSourceRange();
1912
1913 Diag(Param->getLocation(), diag::note_template_param_here);
1914 return true;
1915
1916 case TemplateArgument::Type: {
1917 // We have a non-type template parameter but the template
1918 // argument is a type.
1919
1920 // C++ [temp.arg]p2:
1921 // In a template-argument, an ambiguity between a type-id and
1922 // an expression is resolved to a type-id, regardless of the
1923 // form of the corresponding template-parameter.
1924 //
1925 // We warn specifically about this case, since it can be rather
1926 // confusing for users.
1927 QualType T = Arg.getArgument().getAsType();
1928 SourceRange SR = Arg.getSourceRange();
1929 if (T->isFunctionType())
1930 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1931 else
1932 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1933 Diag(Param->getLocation(), diag::note_template_param_here);
1934 return true;
1935 }
1936
1937 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001938 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001939 break;
1940 }
1941
1942 return false;
1943 }
1944
1945
1946 // Check template template parameters.
1947 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1948
1949 // Substitute into the template parameter list of the template
1950 // template parameter, since previously-supplied template arguments
1951 // may appear within the template template parameter.
1952 {
1953 // Set up a template instantiation context.
1954 LocalInstantiationScope Scope(*this);
1955 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1956 TempParm, Converted.getFlatArguments(),
1957 Converted.flatSize(),
1958 SourceRange(TemplateLoc, RAngleLoc));
1959
1960 TemplateArgumentList TemplateArgs(Context, Converted,
1961 /*TakeArgs=*/false);
1962 TempParm = cast_or_null<TemplateTemplateParmDecl>(
1963 SubstDecl(TempParm, CurContext,
1964 MultiLevelTemplateArgumentList(TemplateArgs)));
1965 if (!TempParm)
1966 return true;
1967
1968 // FIXME: TempParam is leaked.
1969 }
1970
1971 switch (Arg.getArgument().getKind()) {
1972 case TemplateArgument::Null:
1973 assert(false && "Should never see a NULL template argument here");
1974 return true;
1975
1976 case TemplateArgument::Template:
1977 if (CheckTemplateArgument(TempParm, Arg))
1978 return true;
1979
1980 Converted.Append(Arg.getArgument());
1981 break;
1982
1983 case TemplateArgument::Expression:
1984 case TemplateArgument::Type:
1985 // We have a template template parameter but the template
1986 // argument does not refer to a template.
1987 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1988 return true;
1989
1990 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001991 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00001992 "Declaration argument with template template parameter");
1993 break;
1994 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001995 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00001996 "Integral argument with template template parameter");
1997 break;
1998
1999 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002000 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002001 break;
2002 }
2003
2004 return false;
2005}
2006
Douglas Gregord32e0282009-02-09 23:23:08 +00002007/// \brief Check that the given template argument list is well-formed
2008/// for specializing the given template.
2009bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2010 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002011 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002012 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002013 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002014 TemplateParameterList *Params = Template->getTemplateParameters();
2015 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002016 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002017 bool Invalid = false;
2018
John McCall6b51f282009-11-23 01:53:49 +00002019 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2020
Mike Stump11289f42009-09-09 15:08:12 +00002021 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002022 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002023
Anders Carlsson15201f12009-06-13 02:08:00 +00002024 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002025 (NumArgs < Params->getMinRequiredArguments() &&
2026 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002027 // FIXME: point at either the first arg beyond what we can handle,
2028 // or the '>', depending on whether we have too many or too few
2029 // arguments.
2030 SourceRange Range;
2031 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002032 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002033 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2034 << (NumArgs > NumParams)
2035 << (isa<ClassTemplateDecl>(Template)? 0 :
2036 isa<FunctionTemplateDecl>(Template)? 1 :
2037 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2038 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002039 Diag(Template->getLocation(), diag::note_template_decl_here)
2040 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002041 Invalid = true;
2042 }
Mike Stump11289f42009-09-09 15:08:12 +00002043
2044 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002045 // [...] The type and form of each template-argument specified in
2046 // a template-id shall match the type and form specified for the
2047 // corresponding parameter declared by the template in its
2048 // template-parameter-list.
2049 unsigned ArgIdx = 0;
2050 for (TemplateParameterList::iterator Param = Params->begin(),
2051 ParamEnd = Params->end();
2052 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002053 if (ArgIdx > NumArgs && PartialTemplateArgs)
2054 break;
Mike Stump11289f42009-09-09 15:08:12 +00002055
Douglas Gregoreebed722009-11-11 19:41:09 +00002056 // If we have a template parameter pack, check every remaining template
2057 // argument against that template parameter pack.
2058 if ((*Param)->isTemplateParameterPack()) {
2059 Converted.BeginPack();
2060 for (; ArgIdx < NumArgs; ++ArgIdx) {
2061 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2062 TemplateLoc, RAngleLoc, Converted)) {
2063 Invalid = true;
2064 break;
2065 }
2066 }
2067 Converted.EndPack();
2068 continue;
2069 }
2070
Douglas Gregor84d49a22009-11-11 21:54:23 +00002071 if (ArgIdx < NumArgs) {
2072 // Check the template argument we were given.
2073 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2074 TemplateLoc, RAngleLoc, Converted))
2075 return true;
2076
2077 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002078 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002079
Douglas Gregor84d49a22009-11-11 21:54:23 +00002080 // We have a default template argument that we will use.
2081 TemplateArgumentLoc Arg;
2082
2083 // Retrieve the default template argument from the template
2084 // parameter. For each kind of template parameter, we substitute the
2085 // template arguments provided thus far and any "outer" template arguments
2086 // (when the template parameter was part of a nested template) into
2087 // the default argument.
2088 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2089 if (!TTP->hasDefaultArgument()) {
2090 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2091 break;
2092 }
2093
John McCallbcd03502009-12-07 02:54:59 +00002094 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002095 Template,
2096 TemplateLoc,
2097 RAngleLoc,
2098 TTP,
2099 Converted);
2100 if (!ArgType)
2101 return true;
2102
2103 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2104 ArgType);
2105 } else if (NonTypeTemplateParmDecl *NTTP
2106 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2107 if (!NTTP->hasDefaultArgument()) {
2108 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2109 break;
2110 }
2111
2112 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2113 TemplateLoc,
2114 RAngleLoc,
2115 NTTP,
2116 Converted);
2117 if (E.isInvalid())
2118 return true;
2119
2120 Expr *Ex = E.takeAs<Expr>();
2121 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2122 } else {
2123 TemplateTemplateParmDecl *TempParm
2124 = cast<TemplateTemplateParmDecl>(*Param);
2125
2126 if (!TempParm->hasDefaultArgument()) {
2127 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2128 break;
2129 }
2130
2131 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2132 TemplateLoc,
2133 RAngleLoc,
2134 TempParm,
2135 Converted);
2136 if (Name.isNull())
2137 return true;
2138
2139 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2140 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2141 TempParm->getDefaultArgument().getTemplateNameLoc());
2142 }
2143
2144 // Introduce an instantiation record that describes where we are using
2145 // the default template argument.
2146 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2147 Converted.getFlatArguments(),
2148 Converted.flatSize(),
2149 SourceRange(TemplateLoc, RAngleLoc));
2150
2151 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002152 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002153 RAngleLoc, Converted))
2154 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002155 }
2156
2157 return Invalid;
2158}
2159
2160/// \brief Check a template argument against its corresponding
2161/// template type parameter.
2162///
2163/// This routine implements the semantics of C++ [temp.arg.type]. It
2164/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002165bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002166 TypeSourceInfo *ArgInfo) {
2167 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002168 QualType Arg = ArgInfo->getType();
2169
Douglas Gregord32e0282009-02-09 23:23:08 +00002170 // C++ [temp.arg.type]p2:
2171 // A local type, a type with no linkage, an unnamed type or a type
2172 // compounded from any of these types shall not be used as a
2173 // template-argument for a template type-parameter.
2174 //
2175 // FIXME: Perform the recursive and no-linkage type checks.
2176 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002177 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002178 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002179 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002180 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002181 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2182 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2183 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2184 << QualType(Tag, 0) << SR;
2185 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002186 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002187 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2188 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002189 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2190 return true;
2191 }
2192
2193 return false;
2194}
2195
Douglas Gregorccb07762009-02-11 19:52:55 +00002196/// \brief Checks whether the given template argument is the address
2197/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002198bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2199 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002200 bool Invalid = false;
2201
2202 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002203 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002204 Arg = Cast->getSubExpr();
2205
Sebastian Redl576fd422009-05-10 18:38:11 +00002206 // C++0x allows nullptr, and there's no further checking to be done for that.
2207 if (Arg->getType()->isNullPtrType())
2208 return false;
2209
Douglas Gregorccb07762009-02-11 19:52:55 +00002210 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002211 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002212 // A template-argument for a non-type, non-template
2213 // template-parameter shall be one of: [...]
2214 //
2215 // -- the address of an object or function with external
2216 // linkage, including function templates and function
2217 // template-ids but excluding non-static class members,
2218 // expressed as & id-expression where the & is optional if
2219 // the name refers to a function or array, or if the
2220 // corresponding template-parameter is a reference; or
2221 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002222
Douglas Gregorccb07762009-02-11 19:52:55 +00002223 // Ignore (and complain about) any excess parentheses.
2224 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2225 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002226 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002227 diag::err_template_arg_extra_parens)
2228 << Arg->getSourceRange();
2229 Invalid = true;
2230 }
2231
2232 Arg = Parens->getSubExpr();
2233 }
2234
2235 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2236 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2237 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2238 } else
2239 DRE = dyn_cast<DeclRefExpr>(Arg);
2240
2241 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002242 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002243 diag::err_template_arg_not_object_or_func_form)
2244 << Arg->getSourceRange();
2245
2246 // Cannot refer to non-static data members
2247 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2248 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2249 << Field << Arg->getSourceRange();
2250
2251 // Cannot refer to non-static member functions
2252 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2253 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002254 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002255 diag::err_template_arg_method)
2256 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002257
Douglas Gregorccb07762009-02-11 19:52:55 +00002258 // Functions must have external linkage.
2259 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregorf73b2822009-11-25 22:24:25 +00002260 if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump11289f42009-09-09 15:08:12 +00002261 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002262 diag::err_template_arg_function_not_extern)
2263 << Func << Arg->getSourceRange();
2264 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2265 << true;
2266 return true;
2267 }
2268
2269 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002270 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002271 return Invalid;
2272 }
2273
2274 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregorf73b2822009-11-25 22:24:25 +00002275 if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump11289f42009-09-09 15:08:12 +00002276 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002277 diag::err_template_arg_object_not_extern)
2278 << Var << Arg->getSourceRange();
2279 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2280 << true;
2281 return true;
2282 }
2283
2284 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002285 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002286 return Invalid;
2287 }
Mike Stump11289f42009-09-09 15:08:12 +00002288
Douglas Gregorccb07762009-02-11 19:52:55 +00002289 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002290 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002291 diag::err_template_arg_not_object_or_func)
2292 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002293 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002294 diag::note_template_arg_refers_here);
2295 return true;
2296}
2297
2298/// \brief Checks whether the given template argument is a pointer to
2299/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002300bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2301 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002302 bool Invalid = false;
2303
2304 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002305 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002306 Arg = Cast->getSubExpr();
2307
Sebastian Redl576fd422009-05-10 18:38:11 +00002308 // C++0x allows nullptr, and there's no further checking to be done for that.
2309 if (Arg->getType()->isNullPtrType())
2310 return false;
2311
Douglas Gregorccb07762009-02-11 19:52:55 +00002312 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002313 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002314 // A template-argument for a non-type, non-template
2315 // template-parameter shall be one of: [...]
2316 //
2317 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002318 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002319
2320 // Ignore (and complain about) any excess parentheses.
2321 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2322 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002323 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002324 diag::err_template_arg_extra_parens)
2325 << Arg->getSourceRange();
2326 Invalid = true;
2327 }
2328
2329 Arg = Parens->getSubExpr();
2330 }
2331
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002332 // A pointer-to-member constant written &Class::member.
2333 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002334 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2335 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2336 if (DRE && !DRE->getQualifier())
2337 DRE = 0;
2338 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002339 }
2340 // A constant of pointer-to-member type.
2341 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2342 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2343 if (VD->getType()->isMemberPointerType()) {
2344 if (isa<NonTypeTemplateParmDecl>(VD) ||
2345 (isa<VarDecl>(VD) &&
2346 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2347 if (Arg->isTypeDependent() || Arg->isValueDependent())
2348 Converted = TemplateArgument(Arg->Retain());
2349 else
2350 Converted = TemplateArgument(VD->getCanonicalDecl());
2351 return Invalid;
2352 }
2353 }
2354 }
2355
2356 DRE = 0;
2357 }
2358
Douglas Gregorccb07762009-02-11 19:52:55 +00002359 if (!DRE)
2360 return Diag(Arg->getSourceRange().getBegin(),
2361 diag::err_template_arg_not_pointer_to_member_form)
2362 << Arg->getSourceRange();
2363
2364 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2365 assert((isa<FieldDecl>(DRE->getDecl()) ||
2366 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2367 "Only non-static member pointers can make it here");
2368
2369 // Okay: this is the address of a non-static member, and therefore
2370 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002371 if (Arg->isTypeDependent() || Arg->isValueDependent())
2372 Converted = TemplateArgument(Arg->Retain());
2373 else
2374 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002375 return Invalid;
2376 }
2377
2378 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002379 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002380 diag::err_template_arg_not_pointer_to_member_form)
2381 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002382 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002383 diag::note_template_arg_refers_here);
2384 return true;
2385}
2386
Douglas Gregord32e0282009-02-09 23:23:08 +00002387/// \brief Check a template argument against its corresponding
2388/// non-type template parameter.
2389///
Douglas Gregor463421d2009-03-03 04:44:36 +00002390/// This routine implements the semantics of C++ [temp.arg.nontype].
2391/// It returns true if an error occurred, and false otherwise. \p
2392/// InstantiatedParamType is the type of the non-type template
2393/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002394///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002395/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002396bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002397 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002398 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002399 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2400
Douglas Gregor86560402009-02-10 23:36:10 +00002401 // If either the parameter has a dependent type or the argument is
2402 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002403 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002404 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2405 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002406 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002407 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002408 }
Douglas Gregor86560402009-02-10 23:36:10 +00002409
2410 // C++ [temp.arg.nontype]p5:
2411 // The following conversions are performed on each expression used
2412 // as a non-type template-argument. If a non-type
2413 // template-argument cannot be converted to the type of the
2414 // corresponding template-parameter then the program is
2415 // ill-formed.
2416 //
2417 // -- for a non-type template-parameter of integral or
2418 // enumeration type, integral promotions (4.5) and integral
2419 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002420 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002421 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002422 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002423 // C++ [temp.arg.nontype]p1:
2424 // A template-argument for a non-type, non-template
2425 // template-parameter shall be one of:
2426 //
2427 // -- an integral constant-expression of integral or enumeration
2428 // type; or
2429 // -- the name of a non-type template-parameter; or
2430 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002431 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002432 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002433 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002434 diag::err_template_arg_not_integral_or_enumeral)
2435 << ArgType << Arg->getSourceRange();
2436 Diag(Param->getLocation(), diag::note_template_param_here);
2437 return true;
2438 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002439 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002440 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2441 << ArgType << Arg->getSourceRange();
2442 return true;
2443 }
2444
2445 // FIXME: We need some way to more easily get the unqualified form
2446 // of the types without going all the way to the
2447 // canonical type.
2448 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2449 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2450 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2451 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2452
2453 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002454 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002455 // Okay: no conversion necessary
2456 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2457 !ParamType->isEnumeralType()) {
2458 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002459 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002460 } else {
2461 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002462 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002463 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002464 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002465 Diag(Param->getLocation(), diag::note_template_param_here);
2466 return true;
2467 }
2468
Douglas Gregor52aba872009-03-14 00:20:21 +00002469 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002470 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002471 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002472
2473 if (!Arg->isValueDependent()) {
2474 // Check that an unsigned parameter does not receive a negative
2475 // value.
2476 if (IntegerType->isUnsignedIntegerType()
2477 && (Value.isSigned() && Value.isNegative())) {
2478 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2479 << Value.toString(10) << Param->getType()
2480 << Arg->getSourceRange();
2481 Diag(Param->getLocation(), diag::note_template_param_here);
2482 return true;
2483 }
2484
2485 // Check that we don't overflow the template parameter type.
2486 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2487 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002488 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002489 diag::err_template_arg_too_large)
2490 << Value.toString(10) << Param->getType()
2491 << Arg->getSourceRange();
2492 Diag(Param->getLocation(), diag::note_template_param_here);
2493 return true;
2494 }
2495
2496 if (Value.getBitWidth() != AllowedBits)
2497 Value.extOrTrunc(AllowedBits);
2498 Value.setIsSigned(IntegerType->isSignedIntegerType());
2499 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002500
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002501 // Add the value of this argument to the list of converted
2502 // arguments. We use the bitwidth and signedness of the template
2503 // parameter.
2504 if (Arg->isValueDependent()) {
2505 // The argument is value-dependent. Create a new
2506 // TemplateArgument with the converted expression.
2507 Converted = TemplateArgument(Arg);
2508 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002509 }
2510
John McCall0ad16662009-10-29 08:12:44 +00002511 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002512 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002513 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002514 return false;
2515 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002516
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002517 // Handle pointer-to-function, reference-to-function, and
2518 // pointer-to-member-function all in (roughly) the same way.
2519 if (// -- For a non-type template-parameter of type pointer to
2520 // function, only the function-to-pointer conversion (4.3) is
2521 // applied. If the template-argument represents a set of
2522 // overloaded functions (or a pointer to such), the matching
2523 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002524 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002525 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002526 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002527 // -- For a non-type template-parameter of type reference to
2528 // function, no conversions apply. If the template-argument
2529 // represents a set of overloaded functions, the matching
2530 // function is selected from the set (13.4).
2531 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002532 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002533 // -- For a non-type template-parameter of type pointer to
2534 // member function, no conversions apply. If the
2535 // template-argument represents a set of overloaded member
2536 // functions, the matching member function is selected from
2537 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002538 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002539 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002540 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002541 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002542 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002543 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002544 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002545 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2546 ParamType->isMemberPointerType())) {
2547 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002548 if (ParamType->isMemberPointerType())
2549 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2550 else
2551 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002552 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002553 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002554 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002555 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002556 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002557 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2558 return true;
2559
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002560 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002561 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002562 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002563 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002564 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002565 }
2566 }
2567
Mike Stump11289f42009-09-09 15:08:12 +00002568 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002569 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002570 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002571 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002572 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002573 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002574 Diag(Param->getLocation(), diag::note_template_param_here);
2575 return true;
2576 }
Mike Stump11289f42009-09-09 15:08:12 +00002577
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002578 if (ParamType->isMemberPointerType())
2579 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002580
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002581 NamedDecl *Entity = 0;
2582 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2583 return true;
2584
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002585 if (Entity)
2586 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002587 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002588 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002589 }
2590
Chris Lattner696197c2009-02-20 21:37:53 +00002591 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002592 // -- for a non-type template-parameter of type pointer to
2593 // object, qualification conversions (4.4) and the
2594 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002595 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002596 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002597 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002598
Sebastian Redl576fd422009-05-10 18:38:11 +00002599 if (ArgType->isNullPtrType()) {
2600 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002601 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002602 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002603 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002604 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002605 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002606
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002607 if (IsQualificationConversion(ArgType, ParamType)) {
2608 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002609 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002610 }
Mike Stump11289f42009-09-09 15:08:12 +00002611
Douglas Gregor1515f762009-02-11 18:22:40 +00002612 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002613 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002614 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002615 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002616 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002617 Diag(Param->getLocation(), diag::note_template_param_here);
2618 return true;
2619 }
Mike Stump11289f42009-09-09 15:08:12 +00002620
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002621 NamedDecl *Entity = 0;
2622 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2623 return true;
2624
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002625 if (Entity)
2626 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002627 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002628 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002629 }
Mike Stump11289f42009-09-09 15:08:12 +00002630
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002631 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002632 // -- For a non-type template-parameter of type reference to
2633 // object, no conversions apply. The type referred to by the
2634 // reference may be more cv-qualified than the (otherwise
2635 // identical) type of the template-argument. The
2636 // template-parameter is bound directly to the
2637 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002638 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002639 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002640
Douglas Gregor1515f762009-02-11 18:22:40 +00002641 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002642 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002643 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002644 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002645 << Arg->getSourceRange();
2646 Diag(Param->getLocation(), diag::note_template_param_here);
2647 return true;
2648 }
2649
Mike Stump11289f42009-09-09 15:08:12 +00002650 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002651 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2652 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002653
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002654 if ((ParamQuals | ArgQuals) != ParamQuals) {
2655 Diag(Arg->getSourceRange().getBegin(),
2656 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002657 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002658 << Arg->getSourceRange();
2659 Diag(Param->getLocation(), diag::note_template_param_here);
2660 return true;
2661 }
Mike Stump11289f42009-09-09 15:08:12 +00002662
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002663 NamedDecl *Entity = 0;
2664 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2665 return true;
2666
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002667 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002668 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002669 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002670 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002671
2672 // -- For a non-type template-parameter of type pointer to data
2673 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002674 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002675 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2676
Douglas Gregor1515f762009-02-11 18:22:40 +00002677 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002678 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002679 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002680 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002681 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002682 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002683 } else {
2684 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002685 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002686 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002687 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002688 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002689 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002690 }
2691
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002692 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002693}
2694
2695/// \brief Check a template argument against its corresponding
2696/// template template parameter.
2697///
2698/// This routine implements the semantics of C++ [temp.arg.template].
2699/// It returns true if an error occurred, and false otherwise.
2700bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002701 const TemplateArgumentLoc &Arg) {
2702 TemplateName Name = Arg.getArgument().getAsTemplate();
2703 TemplateDecl *Template = Name.getAsTemplateDecl();
2704 if (!Template) {
2705 // Any dependent template name is fine.
2706 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2707 return false;
2708 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002709
2710 // C++ [temp.arg.template]p1:
2711 // A template-argument for a template template-parameter shall be
2712 // the name of a class template, expressed as id-expression. Only
2713 // primary class templates are considered when matching the
2714 // template template argument with the corresponding parameter;
2715 // partial specializations are not considered even if their
2716 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002717 //
2718 // Note that we also allow template template parameters here, which
2719 // will happen when we are dealing with, e.g., class template
2720 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002721 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002722 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002723 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002724 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002725 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002726 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002727 << Template;
2728 }
2729
2730 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2731 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002732 true,
2733 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002734 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002735}
2736
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002737/// \brief Determine whether the given template parameter lists are
2738/// equivalent.
2739///
Mike Stump11289f42009-09-09 15:08:12 +00002740/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002741/// source code as part of a new template declaration.
2742///
2743/// \param Old The old template parameter list, typically found via
2744/// name lookup of the template declared with this template parameter
2745/// list.
2746///
2747/// \param Complain If true, this routine will produce a diagnostic if
2748/// the template parameter lists are not equivalent.
2749///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002750/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00002751///
2752/// \param TemplateArgLoc If this source location is valid, then we
2753/// are actually checking the template parameter list of a template
2754/// argument (New) against the template parameter list of its
2755/// corresponding template template parameter (Old). We produce
2756/// slightly different diagnostics in this scenario.
2757///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002758/// \returns True if the template parameter lists are equal, false
2759/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002760bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002761Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2762 TemplateParameterList *Old,
2763 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002764 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002765 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002766 if (Old->size() != New->size()) {
2767 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002768 unsigned NextDiag = diag::err_template_param_list_different_arity;
2769 if (TemplateArgLoc.isValid()) {
2770 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2771 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002772 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002773 Diag(New->getTemplateLoc(), NextDiag)
2774 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002775 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002776 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002777 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002778 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002779 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2780 }
2781
2782 return false;
2783 }
2784
2785 for (TemplateParameterList::iterator OldParm = Old->begin(),
2786 OldParmEnd = Old->end(), NewParm = New->begin();
2787 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2788 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002789 if (Complain) {
2790 unsigned NextDiag = diag::err_template_param_different_kind;
2791 if (TemplateArgLoc.isValid()) {
2792 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2793 NextDiag = diag::note_template_param_different_kind;
2794 }
2795 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002796 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00002797 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002798 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00002799 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002800 return false;
2801 }
2802
2803 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2804 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002805 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002806 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002807 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2808 // The types of non-type template parameters must agree.
2809 NonTypeTemplateParmDecl *NewNTTP
2810 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002811
2812 // If we are matching a template template argument to a template
2813 // template parameter and one of the non-type template parameter types
2814 // is dependent, then we must wait until template instantiation time
2815 // to actually compare the arguments.
2816 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2817 (OldNTTP->getType()->isDependentType() ||
2818 NewNTTP->getType()->isDependentType()))
2819 continue;
2820
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002821 if (Context.getCanonicalType(OldNTTP->getType()) !=
2822 Context.getCanonicalType(NewNTTP->getType())) {
2823 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002824 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2825 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002826 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002827 diag::err_template_arg_template_params_mismatch);
2828 NextDiag = diag::note_template_nontype_parm_different_type;
2829 }
2830 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002831 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002832 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00002833 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002834 diag::note_template_nontype_parm_prev_declaration)
2835 << OldNTTP->getType();
2836 }
2837 return false;
2838 }
2839 } else {
2840 // The template parameter lists of template template
2841 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002842 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002843 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002844 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002845 = cast<TemplateTemplateParmDecl>(*OldParm);
2846 TemplateTemplateParmDecl *NewTTP
2847 = cast<TemplateTemplateParmDecl>(*NewParm);
2848 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2849 OldTTP->getTemplateParameters(),
2850 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002851 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00002852 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002853 return false;
2854 }
2855 }
2856
2857 return true;
2858}
2859
2860/// \brief Check whether a template can be declared within this scope.
2861///
2862/// If the template declaration is valid in this scope, returns
2863/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002864bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002865Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002866 // Find the nearest enclosing declaration scope.
2867 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2868 (S->getFlags() & Scope::TemplateParamScope) != 0)
2869 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002870
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002871 // C++ [temp]p2:
2872 // A template-declaration can appear only as a namespace scope or
2873 // class scope declaration.
2874 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002875 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2876 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002877 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002878 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002879
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002880 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002881 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002882
2883 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2884 return false;
2885
Mike Stump11289f42009-09-09 15:08:12 +00002886 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002887 diag::err_template_outside_namespace_or_class_scope)
2888 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002889}
Douglas Gregor67a65642009-02-17 23:15:12 +00002890
Douglas Gregor54888652009-10-07 00:13:32 +00002891/// \brief Determine what kind of template specialization the given declaration
2892/// is.
2893static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2894 if (!D)
2895 return TSK_Undeclared;
2896
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002897 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2898 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002899 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2900 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002901 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2902 return Var->getTemplateSpecializationKind();
2903
Douglas Gregor54888652009-10-07 00:13:32 +00002904 return TSK_Undeclared;
2905}
2906
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002907/// \brief Check whether a specialization is well-formed in the current
2908/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002909///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002910/// This routine determines whether a template specialization can be declared
2911/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002912///
2913/// \param S the semantic analysis object for which this check is being
2914/// performed.
2915///
2916/// \param Specialized the entity being specialized or instantiated, which
2917/// may be a kind of template (class template, function template, etc.) or
2918/// a member of a class template (member function, static data member,
2919/// member class).
2920///
2921/// \param PrevDecl the previous declaration of this entity, if any.
2922///
2923/// \param Loc the location of the explicit specialization or instantiation of
2924/// this entity.
2925///
2926/// \param IsPartialSpecialization whether this is a partial specialization of
2927/// a class template.
2928///
Douglas Gregor54888652009-10-07 00:13:32 +00002929/// \returns true if there was an error that we cannot recover from, false
2930/// otherwise.
2931static bool CheckTemplateSpecializationScope(Sema &S,
2932 NamedDecl *Specialized,
2933 NamedDecl *PrevDecl,
2934 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002935 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002936 // Keep these "kind" numbers in sync with the %select statements in the
2937 // various diagnostics emitted by this routine.
2938 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002939 bool isTemplateSpecialization = false;
2940 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002941 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002942 isTemplateSpecialization = true;
2943 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002944 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002945 isTemplateSpecialization = true;
2946 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002947 EntityKind = 3;
2948 else if (isa<VarDecl>(Specialized))
2949 EntityKind = 4;
2950 else if (isa<RecordDecl>(Specialized))
2951 EntityKind = 5;
2952 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002953 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2954 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00002955 return true;
2956 }
2957
Douglas Gregorf47b9112009-02-25 22:02:03 +00002958 // C++ [temp.expl.spec]p2:
2959 // An explicit specialization shall be declared in the namespace
2960 // of which the template is a member, or, for member templates, in
2961 // the namespace of which the enclosing class or enclosing class
2962 // template is a member. An explicit specialization of a member
2963 // function, member class or static data member of a class
2964 // template shall be declared in the namespace of which the class
2965 // template is a member. Such a declaration may also be a
2966 // definition. If the declaration is not a definition, the
2967 // specialization may be defined later in the name- space in which
2968 // the explicit specialization was declared, or in a namespace
2969 // that encloses the one in which the explicit specialization was
2970 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002971 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2972 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002973 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002974 return true;
2975 }
Douglas Gregore4b05162009-10-07 17:21:34 +00002976
Douglas Gregor40fb7442009-10-07 17:30:37 +00002977 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2978 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002979 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00002980 return true;
2981 }
2982
Douglas Gregore4b05162009-10-07 17:21:34 +00002983 // C++ [temp.class.spec]p6:
2984 // A class template partial specialization may be declared or redeclared
2985 // in any namespace scope in which its definition may be defined (14.5.1
2986 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002987 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002988 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002989 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002990 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002991 if ((!PrevDecl ||
2992 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2993 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2994 // There is no prior declaration of this entity, so this
2995 // specialization must be in the same context as the template
2996 // itself.
2997 if (!DC->Equals(SpecializedContext)) {
2998 if (isa<TranslationUnitDecl>(SpecializedContext))
2999 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3000 << EntityKind << Specialized;
3001 else if (isa<NamespaceDecl>(SpecializedContext))
3002 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3003 << EntityKind << Specialized
3004 << cast<NamedDecl>(SpecializedContext);
3005
3006 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3007 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003008 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003009 }
Douglas Gregor54888652009-10-07 00:13:32 +00003010
3011 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003012 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003013 // Note that HandleDeclarator() performs this check for explicit
3014 // specializations of function templates, static data members, and member
3015 // functions, so we skip the check here for those kinds of entities.
3016 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003017 // Should we refactor that check, so that it occurs later?
3018 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003019 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3020 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003021 if (isa<TranslationUnitDecl>(SpecializedContext))
3022 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3023 << EntityKind << Specialized;
3024 else if (isa<NamespaceDecl>(SpecializedContext))
3025 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3026 << EntityKind << Specialized
3027 << cast<NamedDecl>(SpecializedContext);
3028
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003029 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003030 }
Douglas Gregor54888652009-10-07 00:13:32 +00003031
3032 // FIXME: check for specialization-after-instantiation errors and such.
3033
Douglas Gregorf47b9112009-02-25 22:02:03 +00003034 return false;
3035}
Douglas Gregor54888652009-10-07 00:13:32 +00003036
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003037/// \brief Check the non-type template arguments of a class template
3038/// partial specialization according to C++ [temp.class.spec]p9.
3039///
Douglas Gregor09a30232009-06-12 22:08:06 +00003040/// \param TemplateParams the template parameters of the primary class
3041/// template.
3042///
3043/// \param TemplateArg the template arguments of the class template
3044/// partial specialization.
3045///
3046/// \param MirrorsPrimaryTemplate will be set true if the class
3047/// template partial specialization arguments are identical to the
3048/// implicit template arguments of the primary template. This is not
3049/// necessarily an error (C++0x), and it is left to the caller to diagnose
3050/// this condition when it is an error.
3051///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003052/// \returns true if there was an error, false otherwise.
3053bool Sema::CheckClassTemplatePartialSpecializationArgs(
3054 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003055 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003056 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003057 // FIXME: the interface to this function will have to change to
3058 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003059 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003060
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003061 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003062
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003063 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003064 // Determine whether the template argument list of the partial
3065 // specialization is identical to the implicit argument list of
3066 // the primary template. The caller may need to diagnostic this as
3067 // an error per C++ [temp.class.spec]p9b3.
3068 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003069 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003070 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3071 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003072 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003073 MirrorsPrimaryTemplate = false;
3074 } else if (TemplateTemplateParmDecl *TTP
3075 = dyn_cast<TemplateTemplateParmDecl>(
3076 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003077 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003078 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003079 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003080 if (!ArgDecl ||
3081 ArgDecl->getIndex() != TTP->getIndex() ||
3082 ArgDecl->getDepth() != TTP->getDepth())
3083 MirrorsPrimaryTemplate = false;
3084 }
3085 }
3086
Mike Stump11289f42009-09-09 15:08:12 +00003087 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003088 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003089 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003090 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003091 }
3092
Anders Carlsson40c1d492009-06-13 18:20:51 +00003093 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003094 if (!ArgExpr) {
3095 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003096 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003097 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003098
3099 // C++ [temp.class.spec]p8:
3100 // A non-type argument is non-specialized if it is the name of a
3101 // non-type parameter. All other non-type arguments are
3102 // specialized.
3103 //
3104 // Below, we check the two conditions that only apply to
3105 // specialized non-type arguments, so skip any non-specialized
3106 // arguments.
3107 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003108 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003109 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003110 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003111 (Param->getIndex() != NTTP->getIndex() ||
3112 Param->getDepth() != NTTP->getDepth()))
3113 MirrorsPrimaryTemplate = false;
3114
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003115 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003116 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003117
3118 // C++ [temp.class.spec]p9:
3119 // Within the argument list of a class template partial
3120 // specialization, the following restrictions apply:
3121 // -- A partially specialized non-type argument expression
3122 // shall not involve a template parameter of the partial
3123 // specialization except when the argument expression is a
3124 // simple identifier.
3125 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003126 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003127 diag::err_dependent_non_type_arg_in_partial_spec)
3128 << ArgExpr->getSourceRange();
3129 return true;
3130 }
3131
3132 // -- The type of a template parameter corresponding to a
3133 // specialized non-type argument shall not be dependent on a
3134 // parameter of the specialization.
3135 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003136 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003137 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3138 << Param->getType()
3139 << ArgExpr->getSourceRange();
3140 Diag(Param->getLocation(), diag::note_template_param_here);
3141 return true;
3142 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003143
3144 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003145 }
3146
3147 return false;
3148}
3149
Douglas Gregorc08f4892009-03-25 00:13:59 +00003150Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003151Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3152 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003153 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00003154 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003155 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003156 SourceLocation TemplateNameLoc,
3157 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003158 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003159 SourceLocation RAngleLoc,
3160 AttributeList *Attr,
3161 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003162 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003163
Douglas Gregor67a65642009-02-17 23:15:12 +00003164 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003165 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003166 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003167 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3168
3169 if (!ClassTemplate) {
3170 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3171 << (Name.getAsTemplateDecl() &&
3172 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3173 return true;
3174 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003175
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003176 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003177 bool isPartialSpecialization = false;
3178
Douglas Gregorf47b9112009-02-25 22:02:03 +00003179 // Check the validity of the template headers that introduce this
3180 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003181 // FIXME: We probably shouldn't complain about these headers for
3182 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003183 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003184 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3185 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003186 TemplateParameterLists.size(),
3187 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003188 if (TemplateParams && TemplateParams->size() > 0) {
3189 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003190
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003191 // C++ [temp.class.spec]p10:
3192 // The template parameter list of a specialization shall not
3193 // contain default template argument values.
3194 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3195 Decl *Param = TemplateParams->getParam(I);
3196 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3197 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003198 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003199 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003200 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003201 }
3202 } else if (NonTypeTemplateParmDecl *NTTP
3203 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3204 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003205 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003206 diag::err_default_arg_in_partial_spec)
3207 << DefArg->getSourceRange();
3208 NTTP->setDefaultArgument(0);
3209 DefArg->Destroy(Context);
3210 }
3211 } else {
3212 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003213 if (TTP->hasDefaultArgument()) {
3214 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003215 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003216 << TTP->getDefaultArgument().getSourceRange();
3217 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003218 }
3219 }
3220 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003221 } else if (TemplateParams) {
3222 if (TUK == TUK_Friend)
3223 Diag(KWLoc, diag::err_template_spec_friend)
3224 << CodeModificationHint::CreateRemoval(
3225 SourceRange(TemplateParams->getTemplateLoc(),
3226 TemplateParams->getRAngleLoc()))
3227 << SourceRange(LAngleLoc, RAngleLoc);
3228 else
3229 isExplicitSpecialization = true;
3230 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003231 Diag(KWLoc, diag::err_template_spec_needs_header)
3232 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003233 isExplicitSpecialization = true;
3234 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003235
Douglas Gregor67a65642009-02-17 23:15:12 +00003236 // Check that the specialization uses the same tag kind as the
3237 // original template.
3238 TagDecl::TagKind Kind;
3239 switch (TagSpec) {
3240 default: assert(0 && "Unknown tag type!");
3241 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3242 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3243 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3244 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003245 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003246 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003247 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003248 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003249 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003250 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003251 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003252 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003253 diag::note_previous_use);
3254 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3255 }
3256
Douglas Gregorc40290e2009-03-09 23:48:35 +00003257 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003258 TemplateArgumentListInfo TemplateArgs;
3259 TemplateArgs.setLAngleLoc(LAngleLoc);
3260 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003261 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003262
Douglas Gregor67a65642009-02-17 23:15:12 +00003263 // Check that the template argument list is well-formed for this
3264 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003265 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3266 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003267 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3268 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003269 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003270
Mike Stump11289f42009-09-09 15:08:12 +00003271 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003272 ClassTemplate->getTemplateParameters()->size()) &&
3273 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003274
Douglas Gregor2373c592009-05-31 09:31:02 +00003275 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003276 // corresponds to these arguments.
3277 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003278 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003279 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003280 if (CheckClassTemplatePartialSpecializationArgs(
3281 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003282 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003283 return true;
3284
Douglas Gregor09a30232009-06-12 22:08:06 +00003285 if (MirrorsPrimaryTemplate) {
3286 // C++ [temp.class.spec]p9b3:
3287 //
Mike Stump11289f42009-09-09 15:08:12 +00003288 // -- The argument list of the specialization shall not be identical
3289 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003290 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003291 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003292 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003293 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003294 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003295 ClassTemplate->getIdentifier(),
3296 TemplateNameLoc,
3297 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003298 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003299 AS_none);
3300 }
3301
Douglas Gregor2208a292009-09-26 20:57:03 +00003302 // FIXME: Diagnose friend partial specializations
3303
Douglas Gregor2373c592009-05-31 09:31:02 +00003304 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00003305 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003306 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003307 Converted.flatSize(),
3308 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003309 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003310 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003311 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003312 Converted.flatSize(),
3313 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003314 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003315 ClassTemplateSpecializationDecl *PrevDecl = 0;
3316
3317 if (isPartialSpecialization)
3318 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003319 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003320 InsertPos);
3321 else
3322 PrevDecl
3323 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003324
3325 ClassTemplateSpecializationDecl *Specialization = 0;
3326
Douglas Gregorf47b9112009-02-25 22:02:03 +00003327 // Check whether we can declare a class template specialization in
3328 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003329 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003330 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003331 TemplateNameLoc,
3332 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003333 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003334
Douglas Gregor15301382009-07-30 17:40:51 +00003335 // The canonical type
3336 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003337 if (PrevDecl &&
3338 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3339 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003340 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003341 // arguments was referenced but not declared, or we're only
3342 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003343 // declaration node as our own, updating its source location to
3344 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003345 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003346 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003347 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003348 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003349 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003350 // Build the canonical type that describes the converted template
3351 // arguments of the class template partial specialization.
3352 CanonType = Context.getTemplateSpecializationType(
3353 TemplateName(ClassTemplate),
3354 Converted.getFlatArguments(),
3355 Converted.flatSize());
3356
Douglas Gregor2373c592009-05-31 09:31:02 +00003357 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003358 ClassTemplatePartialSpecializationDecl *PrevPartial
3359 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003360 ClassTemplatePartialSpecializationDecl *Partial
3361 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003362 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003363 TemplateNameLoc,
3364 TemplateParams,
3365 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003366 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003367 TemplateArgs,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003368 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003369
3370 if (PrevPartial) {
3371 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3372 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3373 } else {
3374 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3375 }
3376 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003377
Douglas Gregor21610382009-10-29 00:04:11 +00003378 // If we are providing an explicit specialization of a member class
3379 // template specialization, make a note of that.
3380 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3381 PrevPartial->setMemberSpecialization();
3382
Douglas Gregor91772d12009-06-13 00:26:55 +00003383 // Check that all of the template parameters of the class template
3384 // partial specialization are deducible from the template
3385 // arguments. If not, this class template partial specialization
3386 // will never be used.
3387 llvm::SmallVector<bool, 8> DeducibleParams;
3388 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003389 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003390 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003391 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003392 unsigned NumNonDeducible = 0;
3393 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3394 if (!DeducibleParams[I])
3395 ++NumNonDeducible;
3396
3397 if (NumNonDeducible) {
3398 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3399 << (NumNonDeducible > 1)
3400 << SourceRange(TemplateNameLoc, RAngleLoc);
3401 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3402 if (!DeducibleParams[I]) {
3403 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3404 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003405 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003406 diag::note_partial_spec_unused_parameter)
3407 << Param->getDeclName();
3408 else
Mike Stump11289f42009-09-09 15:08:12 +00003409 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003410 diag::note_partial_spec_unused_parameter)
3411 << std::string("<anonymous>");
3412 }
3413 }
3414 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003415 } else {
3416 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003417 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003418 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003419 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003420 ClassTemplate->getDeclContext(),
3421 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003422 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003423 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003424 PrevDecl);
3425
3426 if (PrevDecl) {
3427 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3428 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3429 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003430 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003431 InsertPos);
3432 }
Douglas Gregor15301382009-07-30 17:40:51 +00003433
3434 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003435 }
3436
Douglas Gregor06db9f52009-10-12 20:18:28 +00003437 // C++ [temp.expl.spec]p6:
3438 // If a template, a member template or the member of a class template is
3439 // explicitly specialized then that specialization shall be declared
3440 // before the first use of that specialization that would cause an implicit
3441 // instantiation to take place, in every translation unit in which such a
3442 // use occurs; no diagnostic is required.
3443 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3444 SourceRange Range(TemplateNameLoc, RAngleLoc);
3445 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3446 << Context.getTypeDeclType(Specialization) << Range;
3447
3448 Diag(PrevDecl->getPointOfInstantiation(),
3449 diag::note_instantiation_required_here)
3450 << (PrevDecl->getTemplateSpecializationKind()
3451 != TSK_ImplicitInstantiation);
3452 return true;
3453 }
3454
Douglas Gregor2208a292009-09-26 20:57:03 +00003455 // If this is not a friend, note that this is an explicit specialization.
3456 if (TUK != TUK_Friend)
3457 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003458
3459 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003460 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003461 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003462 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003463 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003464 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003465 Diag(Def->getLocation(), diag::note_previous_definition);
3466 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003467 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003468 }
3469 }
3470
Douglas Gregord56a91e2009-02-26 22:19:44 +00003471 // Build the fully-sugared type for this class template
3472 // specialization as the user wrote in the specialization
3473 // itself. This means that we'll pretty-print the type retrieved
3474 // from the specialization's declaration the way that the user
3475 // actually wrote the specialization, rather than formatting the
3476 // name based on the "canonical" representation used to store the
3477 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003478 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00003479 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003480 if (TUK != TUK_Friend)
3481 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003482 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003483
Douglas Gregor1e249f82009-02-25 22:18:32 +00003484 // C++ [temp.expl.spec]p9:
3485 // A template explicit specialization is in the scope of the
3486 // namespace in which the template was defined.
3487 //
3488 // We actually implement this paragraph where we set the semantic
3489 // context (in the creation of the ClassTemplateSpecializationDecl),
3490 // but we also maintain the lexical context where the actual
3491 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003492 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003493
Douglas Gregor67a65642009-02-17 23:15:12 +00003494 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003495 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003496 Specialization->startDefinition();
3497
Douglas Gregor2208a292009-09-26 20:57:03 +00003498 if (TUK == TUK_Friend) {
3499 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3500 TemplateNameLoc,
3501 WrittenTy.getTypePtr(),
3502 /*FIXME:*/KWLoc);
3503 Friend->setAccess(AS_public);
3504 CurContext->addDecl(Friend);
3505 } else {
3506 // Add the specialization into its lexical context, so that it can
3507 // be seen when iterating through the list of declarations in that
3508 // context. However, specializations are not found by name lookup.
3509 CurContext->addDecl(Specialization);
3510 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003511 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003512}
Douglas Gregor333489b2009-03-27 23:10:48 +00003513
Mike Stump11289f42009-09-09 15:08:12 +00003514Sema::DeclPtrTy
3515Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003516 MultiTemplateParamsArg TemplateParameterLists,
3517 Declarator &D) {
3518 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3519}
3520
Mike Stump11289f42009-09-09 15:08:12 +00003521Sema::DeclPtrTy
3522Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003523 MultiTemplateParamsArg TemplateParameterLists,
3524 Declarator &D) {
3525 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3526 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3527 "Not a function declarator!");
3528 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003529
Douglas Gregor17a7c122009-06-24 00:54:41 +00003530 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003531 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003532 }
Mike Stump11289f42009-09-09 15:08:12 +00003533
Douglas Gregor17a7c122009-06-24 00:54:41 +00003534 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003535
3536 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003537 move(TemplateParameterLists),
3538 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003539 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003540 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003541 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003542 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003543 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3544 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003545 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003546}
3547
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003548/// \brief Diagnose cases where we have an explicit template specialization
3549/// before/after an explicit template instantiation, producing diagnostics
3550/// for those cases where they are required and determining whether the
3551/// new specialization/instantiation will have any effect.
3552///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003553/// \param NewLoc the location of the new explicit specialization or
3554/// instantiation.
3555///
3556/// \param NewTSK the kind of the new explicit specialization or instantiation.
3557///
3558/// \param PrevDecl the previous declaration of the entity.
3559///
3560/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3561///
3562/// \param PrevPointOfInstantiation if valid, indicates where the previus
3563/// declaration was instantiated (either implicitly or explicitly).
3564///
3565/// \param SuppressNew will be set to true to indicate that the new
3566/// specialization or instantiation has no effect and should be ignored.
3567///
3568/// \returns true if there was an error that should prevent the introduction of
3569/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003570bool
3571Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3572 TemplateSpecializationKind NewTSK,
3573 NamedDecl *PrevDecl,
3574 TemplateSpecializationKind PrevTSK,
3575 SourceLocation PrevPointOfInstantiation,
3576 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003577 SuppressNew = false;
3578
3579 switch (NewTSK) {
3580 case TSK_Undeclared:
3581 case TSK_ImplicitInstantiation:
3582 assert(false && "Don't check implicit instantiations here");
3583 return false;
3584
3585 case TSK_ExplicitSpecialization:
3586 switch (PrevTSK) {
3587 case TSK_Undeclared:
3588 case TSK_ExplicitSpecialization:
3589 // Okay, we're just specializing something that is either already
3590 // explicitly specialized or has merely been mentioned without any
3591 // instantiation.
3592 return false;
3593
3594 case TSK_ImplicitInstantiation:
3595 if (PrevPointOfInstantiation.isInvalid()) {
3596 // The declaration itself has not actually been instantiated, so it is
3597 // still okay to specialize it.
3598 return false;
3599 }
3600 // Fall through
3601
3602 case TSK_ExplicitInstantiationDeclaration:
3603 case TSK_ExplicitInstantiationDefinition:
3604 assert((PrevTSK == TSK_ImplicitInstantiation ||
3605 PrevPointOfInstantiation.isValid()) &&
3606 "Explicit instantiation without point of instantiation?");
3607
3608 // C++ [temp.expl.spec]p6:
3609 // If a template, a member template or the member of a class template
3610 // is explicitly specialized then that specialization shall be declared
3611 // before the first use of that specialization that would cause an
3612 // implicit instantiation to take place, in every translation unit in
3613 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003614 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003615 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003616 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003617 << (PrevTSK != TSK_ImplicitInstantiation);
3618
3619 return true;
3620 }
3621 break;
3622
3623 case TSK_ExplicitInstantiationDeclaration:
3624 switch (PrevTSK) {
3625 case TSK_ExplicitInstantiationDeclaration:
3626 // This explicit instantiation declaration is redundant (that's okay).
3627 SuppressNew = true;
3628 return false;
3629
3630 case TSK_Undeclared:
3631 case TSK_ImplicitInstantiation:
3632 // We're explicitly instantiating something that may have already been
3633 // implicitly instantiated; that's fine.
3634 return false;
3635
3636 case TSK_ExplicitSpecialization:
3637 // C++0x [temp.explicit]p4:
3638 // For a given set of template parameters, if an explicit instantiation
3639 // of a template appears after a declaration of an explicit
3640 // specialization for that template, the explicit instantiation has no
3641 // effect.
3642 return false;
3643
3644 case TSK_ExplicitInstantiationDefinition:
3645 // C++0x [temp.explicit]p10:
3646 // If an entity is the subject of both an explicit instantiation
3647 // declaration and an explicit instantiation definition in the same
3648 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003649 Diag(NewLoc,
3650 diag::err_explicit_instantiation_declaration_after_definition);
3651 Diag(PrevPointOfInstantiation,
3652 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003653 assert(PrevPointOfInstantiation.isValid() &&
3654 "Explicit instantiation without point of instantiation?");
3655 SuppressNew = true;
3656 return false;
3657 }
3658 break;
3659
3660 case TSK_ExplicitInstantiationDefinition:
3661 switch (PrevTSK) {
3662 case TSK_Undeclared:
3663 case TSK_ImplicitInstantiation:
3664 // We're explicitly instantiating something that may have already been
3665 // implicitly instantiated; that's fine.
3666 return false;
3667
3668 case TSK_ExplicitSpecialization:
3669 // C++ DR 259, C++0x [temp.explicit]p4:
3670 // For a given set of template parameters, if an explicit
3671 // instantiation of a template appears after a declaration of
3672 // an explicit specialization for that template, the explicit
3673 // instantiation has no effect.
3674 //
3675 // In C++98/03 mode, we only give an extension warning here, because it
3676 // is not not harmful to try to explicitly instantiate something that
3677 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003678 if (!getLangOptions().CPlusPlus0x) {
3679 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003680 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003681 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003682 diag::note_previous_template_specialization);
3683 }
3684 SuppressNew = true;
3685 return false;
3686
3687 case TSK_ExplicitInstantiationDeclaration:
3688 // We're explicity instantiating a definition for something for which we
3689 // were previously asked to suppress instantiations. That's fine.
3690 return false;
3691
3692 case TSK_ExplicitInstantiationDefinition:
3693 // C++0x [temp.spec]p5:
3694 // For a given template and a given set of template-arguments,
3695 // - an explicit instantiation definition shall appear at most once
3696 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003697 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003698 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003699 Diag(PrevPointOfInstantiation,
3700 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003701 SuppressNew = true;
3702 return false;
3703 }
3704 break;
3705 }
3706
3707 assert(false && "Missing specialization/instantiation case?");
3708
3709 return false;
3710}
3711
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003712/// \brief Perform semantic analysis for the given function template
3713/// specialization.
3714///
3715/// This routine performs all of the semantic analysis required for an
3716/// explicit function template specialization. On successful completion,
3717/// the function declaration \p FD will become a function template
3718/// specialization.
3719///
3720/// \param FD the function declaration, which will be updated to become a
3721/// function template specialization.
3722///
3723/// \param HasExplicitTemplateArgs whether any template arguments were
3724/// explicitly provided.
3725///
3726/// \param LAngleLoc the location of the left angle bracket ('<'), if
3727/// template arguments were explicitly provided.
3728///
3729/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3730/// if any.
3731///
3732/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3733/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3734/// true as in, e.g., \c void sort<>(char*, char*);
3735///
3736/// \param RAngleLoc the location of the right angle bracket ('>'), if
3737/// template arguments were explicitly provided.
3738///
3739/// \param PrevDecl the set of declarations that
3740bool
3741Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00003742 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00003743 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003744 // The set of function template specializations that could match this
3745 // explicit function template specialization.
3746 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3747 CandidateSet Candidates;
3748
3749 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00003750 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3751 I != E; ++I) {
3752 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3753 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003754 // Only consider templates found within the same semantic lookup scope as
3755 // FD.
3756 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3757 continue;
3758
3759 // C++ [temp.expl.spec]p11:
3760 // A trailing template-argument can be left unspecified in the
3761 // template-id naming an explicit function template specialization
3762 // provided it can be deduced from the function argument type.
3763 // Perform template argument deduction to determine whether we may be
3764 // specializing this template.
3765 // FIXME: It is somewhat wasteful to build
3766 TemplateDeductionInfo Info(Context);
3767 FunctionDecl *Specialization = 0;
3768 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00003769 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003770 FD->getType(),
3771 Specialization,
3772 Info)) {
3773 // FIXME: Template argument deduction failed; record why it failed, so
3774 // that we can provide nifty diagnostics.
3775 (void)TDK;
3776 continue;
3777 }
3778
3779 // Record this candidate.
3780 Candidates.push_back(Specialization);
3781 }
3782 }
3783
Douglas Gregor5de279c2009-09-26 03:41:46 +00003784 // Find the most specialized function template.
3785 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3786 Candidates.size(),
3787 TPOC_Other,
3788 FD->getLocation(),
3789 PartialDiagnostic(diag::err_function_template_spec_no_match)
3790 << FD->getDeclName(),
3791 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00003792 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor5de279c2009-09-26 03:41:46 +00003793 PartialDiagnostic(diag::note_function_template_spec_matched));
3794 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003795 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003796
3797 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003798 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003799
Douglas Gregor54888652009-10-07 00:13:32 +00003800 // Check the scope of this explicit specialization.
3801 if (CheckTemplateSpecializationScope(*this,
3802 Specialization->getPrimaryTemplate(),
3803 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003804 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003805 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003806
3807 // C++ [temp.expl.spec]p6:
3808 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003809 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003810 // before the first use of that specialization that would cause an implicit
3811 // instantiation to take place, in every translation unit in which such a
3812 // use occurs; no diagnostic is required.
3813 FunctionTemplateSpecializationInfo *SpecInfo
3814 = Specialization->getTemplateSpecializationInfo();
3815 assert(SpecInfo && "Function template specialization info missing?");
3816 if (SpecInfo->getPointOfInstantiation().isValid()) {
3817 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3818 << FD;
3819 Diag(SpecInfo->getPointOfInstantiation(),
3820 diag::note_instantiation_required_here)
3821 << (Specialization->getTemplateSpecializationKind()
3822 != TSK_ImplicitInstantiation);
3823 return true;
3824 }
Douglas Gregor54888652009-10-07 00:13:32 +00003825
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003826 // Mark the prior declaration as an explicit specialization, so that later
3827 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003828 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003829
3830 // Turn the given function declaration into a function template
3831 // specialization, with the template arguments from the previous
3832 // specialization.
3833 FD->setFunctionTemplateSpecialization(Context,
3834 Specialization->getPrimaryTemplate(),
3835 new (Context) TemplateArgumentList(
3836 *Specialization->getTemplateSpecializationArgs()),
3837 /*InsertPos=*/0,
3838 TSK_ExplicitSpecialization);
3839
3840 // The "previous declaration" for this function template specialization is
3841 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00003842 Previous.clear();
3843 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003844 return false;
3845}
3846
Douglas Gregor86d142a2009-10-08 07:24:58 +00003847/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003848/// specialization.
3849///
3850/// This routine performs all of the semantic analysis required for an
3851/// explicit member function specialization. On successful completion,
3852/// the function declaration \p FD will become a member function
3853/// specialization.
3854///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003855/// \param Member the member declaration, which will be updated to become a
3856/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003857///
John McCall1f82f242009-11-18 22:49:29 +00003858/// \param Previous the set of declarations, one of which may be specialized
3859/// by this function specialization; the set will be modified to contain the
3860/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003861bool
John McCall1f82f242009-11-18 22:49:29 +00003862Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003863 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3864
3865 // Try to find the member we are instantiating.
3866 NamedDecl *Instantiation = 0;
3867 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003868 MemberSpecializationInfo *MSInfo = 0;
3869
John McCall1f82f242009-11-18 22:49:29 +00003870 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003871 // Nowhere to look anyway.
3872 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003873 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3874 I != E; ++I) {
3875 NamedDecl *D = (*I)->getUnderlyingDecl();
3876 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003877 if (Context.hasSameType(Function->getType(), Method->getType())) {
3878 Instantiation = Method;
3879 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003880 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003881 break;
3882 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003883 }
3884 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003885 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003886 VarDecl *PrevVar;
3887 if (Previous.isSingleResult() &&
3888 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00003889 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00003890 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003891 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003892 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003893 }
3894 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003895 CXXRecordDecl *PrevRecord;
3896 if (Previous.isSingleResult() &&
3897 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3898 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003899 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003900 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003901 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003902 }
3903
3904 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003905 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003906 // specializations are always out-of-line, the caller will complain about
3907 // this mismatch later.
3908 return false;
3909 }
3910
Douglas Gregor86d142a2009-10-08 07:24:58 +00003911 // Make sure that this is a specialization of a member.
3912 if (!InstantiatedFrom) {
3913 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3914 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003915 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3916 return true;
3917 }
3918
Douglas Gregor06db9f52009-10-12 20:18:28 +00003919 // C++ [temp.expl.spec]p6:
3920 // If a template, a member template or the member of a class template is
3921 // explicitly specialized then that spe- cialization shall be declared
3922 // before the first use of that specialization that would cause an implicit
3923 // instantiation to take place, in every translation unit in which such a
3924 // use occurs; no diagnostic is required.
3925 assert(MSInfo && "Member specialization info missing?");
3926 if (MSInfo->getPointOfInstantiation().isValid()) {
3927 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3928 << Member;
3929 Diag(MSInfo->getPointOfInstantiation(),
3930 diag::note_instantiation_required_here)
3931 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3932 return true;
3933 }
3934
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003935 // Check the scope of this explicit specialization.
3936 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003937 InstantiatedFrom,
3938 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003939 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003940 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003941
Douglas Gregor86d142a2009-10-08 07:24:58 +00003942 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003943 // the original declaration to note that it is an explicit specialization
3944 // (if it was previously an implicit instantiation). This latter step
3945 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003946 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003947 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3948 if (InstantiationFunction->getTemplateSpecializationKind() ==
3949 TSK_ImplicitInstantiation) {
3950 InstantiationFunction->setTemplateSpecializationKind(
3951 TSK_ExplicitSpecialization);
3952 InstantiationFunction->setLocation(Member->getLocation());
3953 }
3954
Douglas Gregor86d142a2009-10-08 07:24:58 +00003955 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3956 cast<CXXMethodDecl>(InstantiatedFrom),
3957 TSK_ExplicitSpecialization);
3958 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003959 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3960 if (InstantiationVar->getTemplateSpecializationKind() ==
3961 TSK_ImplicitInstantiation) {
3962 InstantiationVar->setTemplateSpecializationKind(
3963 TSK_ExplicitSpecialization);
3964 InstantiationVar->setLocation(Member->getLocation());
3965 }
3966
Douglas Gregor86d142a2009-10-08 07:24:58 +00003967 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3968 cast<VarDecl>(InstantiatedFrom),
3969 TSK_ExplicitSpecialization);
3970 } else {
3971 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003972 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3973 if (InstantiationClass->getTemplateSpecializationKind() ==
3974 TSK_ImplicitInstantiation) {
3975 InstantiationClass->setTemplateSpecializationKind(
3976 TSK_ExplicitSpecialization);
3977 InstantiationClass->setLocation(Member->getLocation());
3978 }
3979
Douglas Gregor86d142a2009-10-08 07:24:58 +00003980 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003981 cast<CXXRecordDecl>(InstantiatedFrom),
3982 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003983 }
3984
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003985 // Save the caller the trouble of having to figure out which declaration
3986 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00003987 Previous.clear();
3988 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003989 return false;
3990}
3991
Douglas Gregore47f5a72009-10-14 23:41:34 +00003992/// \brief Check the scope of an explicit instantiation.
3993static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3994 SourceLocation InstLoc,
3995 bool WasQualifiedName) {
3996 DeclContext *ExpectedContext
3997 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3998 DeclContext *CurContext = S.CurContext->getLookupContext();
3999
4000 // C++0x [temp.explicit]p2:
4001 // An explicit instantiation shall appear in an enclosing namespace of its
4002 // template.
4003 //
4004 // This is DR275, which we do not retroactively apply to C++98/03.
4005 if (S.getLangOptions().CPlusPlus0x &&
4006 !CurContext->Encloses(ExpectedContext)) {
4007 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4008 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4009 << D << NS;
4010 else
4011 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4012 << D;
4013 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4014 return;
4015 }
4016
4017 // C++0x [temp.explicit]p2:
4018 // If the name declared in the explicit instantiation is an unqualified
4019 // name, the explicit instantiation shall appear in the namespace where
4020 // its template is declared or, if that namespace is inline (7.3.1), any
4021 // namespace from its enclosing namespace set.
4022 if (WasQualifiedName)
4023 return;
4024
4025 if (CurContext->Equals(ExpectedContext))
4026 return;
4027
4028 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4029 << D << ExpectedContext;
4030 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4031}
4032
4033/// \brief Determine whether the given scope specifier has a template-id in it.
4034static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4035 if (!SS.isSet())
4036 return false;
4037
4038 // C++0x [temp.explicit]p2:
4039 // If the explicit instantiation is for a member function, a member class
4040 // or a static data member of a class template specialization, the name of
4041 // the class template specialization in the qualified-id for the member
4042 // name shall be a simple-template-id.
4043 //
4044 // C++98 has the same restriction, just worded differently.
4045 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4046 NNS; NNS = NNS->getPrefix())
4047 if (Type *T = NNS->getAsType())
4048 if (isa<TemplateSpecializationType>(T))
4049 return true;
4050
4051 return false;
4052}
4053
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004054// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004055// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004056Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004057Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004058 SourceLocation ExternLoc,
4059 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004060 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004061 SourceLocation KWLoc,
4062 const CXXScopeSpec &SS,
4063 TemplateTy TemplateD,
4064 SourceLocation TemplateNameLoc,
4065 SourceLocation LAngleLoc,
4066 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004067 SourceLocation RAngleLoc,
4068 AttributeList *Attr) {
4069 // Find the class template we're specializing
4070 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004071 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004072 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4073
4074 // Check that the specialization uses the same tag kind as the
4075 // original template.
4076 TagDecl::TagKind Kind;
4077 switch (TagSpec) {
4078 default: assert(0 && "Unknown tag type!");
4079 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4080 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4081 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4082 }
Douglas Gregord9034f02009-05-14 16:41:31 +00004083 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004084 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004085 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004086 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004087 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00004088 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004089 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004090 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004091 diag::note_previous_use);
4092 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4093 }
4094
Douglas Gregore47f5a72009-10-14 23:41:34 +00004095 // C++0x [temp.explicit]p2:
4096 // There are two forms of explicit instantiation: an explicit instantiation
4097 // definition and an explicit instantiation declaration. An explicit
4098 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004099 TemplateSpecializationKind TSK
4100 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4101 : TSK_ExplicitInstantiationDeclaration;
4102
Douglas Gregora1f49972009-05-13 00:25:59 +00004103 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004104 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004105 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004106
4107 // Check that the template argument list is well-formed for this
4108 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004109 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4110 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004111 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4112 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004113 return true;
4114
Mike Stump11289f42009-09-09 15:08:12 +00004115 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004116 ClassTemplate->getTemplateParameters()->size()) &&
4117 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004118
Douglas Gregora1f49972009-05-13 00:25:59 +00004119 // Find the class template specialization declaration that
4120 // corresponds to these arguments.
4121 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004122 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004123 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004124 Converted.flatSize(),
4125 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004126 void *InsertPos = 0;
4127 ClassTemplateSpecializationDecl *PrevDecl
4128 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4129
Douglas Gregor54888652009-10-07 00:13:32 +00004130 // C++0x [temp.explicit]p2:
4131 // [...] An explicit instantiation shall appear in an enclosing
4132 // namespace of its template. [...]
4133 //
4134 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004135 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4136 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004137
Douglas Gregora1f49972009-05-13 00:25:59 +00004138 ClassTemplateSpecializationDecl *Specialization = 0;
4139
Douglas Gregor0681a352009-11-25 06:01:46 +00004140 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004141 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004142 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004143 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004144 PrevDecl,
4145 PrevDecl->getSpecializationKind(),
4146 PrevDecl->getPointOfInstantiation(),
4147 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004148 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004149
Douglas Gregor12e49d32009-10-15 22:53:21 +00004150 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004151 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004152
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004153 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4154 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4155 // Since the only prior class template specialization with these
4156 // arguments was referenced but not declared, reuse that
4157 // declaration node as our own, updating its source location to
4158 // reflect our new declaration.
4159 Specialization = PrevDecl;
4160 Specialization->setLocation(TemplateNameLoc);
4161 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004162 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004163 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004164 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004165
4166 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004167 // Create a new class template specialization declaration node for
4168 // this explicit specialization.
4169 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00004170 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00004171 ClassTemplate->getDeclContext(),
4172 TemplateNameLoc,
4173 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004174 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004175
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004176 if (PrevDecl) {
4177 // Remove the previous declaration from the folding set, since we want
4178 // to introduce a new declaration.
4179 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4180 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4181 }
4182
4183 // Insert the new specialization.
4184 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004185 }
4186
4187 // Build the fully-sugared type for this explicit instantiation as
4188 // the user wrote in the explicit instantiation itself. This means
4189 // that we'll pretty-print the type retrieved from the
4190 // specialization's declaration the way that the user actually wrote
4191 // the explicit instantiation, rather than formatting the name based
4192 // on the "canonical" representation used to store the template
4193 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004194 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00004195 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004196 Context.getTypeDeclType(Specialization));
4197 Specialization->setTypeAsWritten(WrittenTy);
4198 TemplateArgsIn.release();
4199
Douglas Gregor0681a352009-11-25 06:01:46 +00004200 if (!ReusedDecl) {
4201 // Add the explicit instantiation into its lexical context. However,
4202 // since explicit instantiations are never found by name lookup, we
4203 // just put it into the declaration context directly.
4204 Specialization->setLexicalDeclContext(CurContext);
4205 CurContext->addDecl(Specialization);
4206 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004207
4208 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004209 // A definition of a class template or class member template
4210 // shall be in scope at the point of the explicit instantiation of
4211 // the class template or class member template.
4212 //
4213 // This check comes when we actually try to perform the
4214 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004215 ClassTemplateSpecializationDecl *Def
4216 = cast_or_null<ClassTemplateSpecializationDecl>(
4217 Specialization->getDefinition(Context));
4218 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004219 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004220
4221 // Instantiate the members of this class template specialization.
4222 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4223 Specialization->getDefinition(Context));
4224 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00004225 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004226
4227 return DeclPtrTy::make(Specialization);
4228}
4229
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004230// Explicit instantiation of a member class of a class template.
4231Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004232Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004233 SourceLocation ExternLoc,
4234 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004235 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004236 SourceLocation KWLoc,
4237 const CXXScopeSpec &SS,
4238 IdentifierInfo *Name,
4239 SourceLocation NameLoc,
4240 AttributeList *Attr) {
4241
Douglas Gregord6ab8742009-05-28 23:31:59 +00004242 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004243 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004244 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004245 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004246 MultiTemplateParamsArg(*this, 0, 0),
4247 Owned, IsDependent);
4248 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4249
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004250 if (!TagD)
4251 return true;
4252
4253 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4254 if (Tag->isEnum()) {
4255 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4256 << Context.getTypeDeclType(Tag);
4257 return true;
4258 }
4259
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004260 if (Tag->isInvalidDecl())
4261 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004262
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004263 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4264 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4265 if (!Pattern) {
4266 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4267 << Context.getTypeDeclType(Record);
4268 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4269 return true;
4270 }
4271
Douglas Gregore47f5a72009-10-14 23:41:34 +00004272 // C++0x [temp.explicit]p2:
4273 // If the explicit instantiation is for a class or member class, the
4274 // elaborated-type-specifier in the declaration shall include a
4275 // simple-template-id.
4276 //
4277 // C++98 has the same restriction, just worded differently.
4278 if (!ScopeSpecifierHasTemplateId(SS))
4279 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4280 << Record << SS.getRange();
4281
4282 // C++0x [temp.explicit]p2:
4283 // There are two forms of explicit instantiation: an explicit instantiation
4284 // definition and an explicit instantiation declaration. An explicit
4285 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004286 TemplateSpecializationKind TSK
4287 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4288 : TSK_ExplicitInstantiationDeclaration;
4289
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004290 // C++0x [temp.explicit]p2:
4291 // [...] An explicit instantiation shall appear in an enclosing
4292 // namespace of its template. [...]
4293 //
4294 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004295 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004296
4297 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004298 CXXRecordDecl *PrevDecl
4299 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4300 if (!PrevDecl && Record->getDefinition(Context))
4301 PrevDecl = Record;
4302 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004303 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4304 bool SuppressNew = false;
4305 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004306 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004307 PrevDecl,
4308 MSInfo->getTemplateSpecializationKind(),
4309 MSInfo->getPointOfInstantiation(),
4310 SuppressNew))
4311 return true;
4312 if (SuppressNew)
4313 return TagD;
4314 }
4315
Douglas Gregor12e49d32009-10-15 22:53:21 +00004316 CXXRecordDecl *RecordDef
4317 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4318 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004319 // C++ [temp.explicit]p3:
4320 // A definition of a member class of a class template shall be in scope
4321 // at the point of an explicit instantiation of the member class.
4322 CXXRecordDecl *Def
4323 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4324 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004325 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4326 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004327 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4328 << Pattern;
4329 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004330 } else {
4331 if (InstantiateClass(NameLoc, Record, Def,
4332 getTemplateInstantiationArgs(Record),
4333 TSK))
4334 return true;
4335
4336 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4337 if (!RecordDef)
4338 return true;
4339 }
4340 }
4341
4342 // Instantiate all of the members of the class.
4343 InstantiateClassMembers(NameLoc, RecordDef,
4344 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004345
Mike Stump87c57ac2009-05-16 07:39:55 +00004346 // FIXME: We don't have any representation for explicit instantiations of
4347 // member classes. Such a representation is not needed for compilation, but it
4348 // should be available for clients that want to see all of the declarations in
4349 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004350 return TagD;
4351}
4352
Douglas Gregor450f00842009-09-25 18:43:00 +00004353Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4354 SourceLocation ExternLoc,
4355 SourceLocation TemplateLoc,
4356 Declarator &D) {
4357 // Explicit instantiations always require a name.
4358 DeclarationName Name = GetNameForDeclarator(D);
4359 if (!Name) {
4360 if (!D.isInvalidType())
4361 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4362 diag::err_explicit_instantiation_requires_name)
4363 << D.getDeclSpec().getSourceRange()
4364 << D.getSourceRange();
4365
4366 return true;
4367 }
4368
4369 // The scope passed in may not be a decl scope. Zip up the scope tree until
4370 // we find one that is.
4371 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4372 (S->getFlags() & Scope::TemplateParamScope) != 0)
4373 S = S->getParent();
4374
4375 // Determine the type of the declaration.
4376 QualType R = GetTypeForDeclarator(D, S, 0);
4377 if (R.isNull())
4378 return true;
4379
4380 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4381 // Cannot explicitly instantiate a typedef.
4382 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4383 << Name;
4384 return true;
4385 }
4386
Douglas Gregor3c74d412009-10-14 20:14:33 +00004387 // C++0x [temp.explicit]p1:
4388 // [...] An explicit instantiation of a function template shall not use the
4389 // inline or constexpr specifiers.
4390 // Presumably, this also applies to member functions of class templates as
4391 // well.
4392 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4393 Diag(D.getDeclSpec().getInlineSpecLoc(),
4394 diag::err_explicit_instantiation_inline)
Chris Lattner3c7b86f2009-12-06 17:36:05 +00004395 <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004396
4397 // FIXME: check for constexpr specifier.
4398
Douglas Gregore47f5a72009-10-14 23:41:34 +00004399 // C++0x [temp.explicit]p2:
4400 // There are two forms of explicit instantiation: an explicit instantiation
4401 // definition and an explicit instantiation declaration. An explicit
4402 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004403 TemplateSpecializationKind TSK
4404 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4405 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004406
John McCall27b18f82009-11-17 02:14:36 +00004407 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4408 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004409
4410 if (!R->isFunctionType()) {
4411 // C++ [temp.explicit]p1:
4412 // A [...] static data member of a class template can be explicitly
4413 // instantiated from the member definition associated with its class
4414 // template.
John McCall27b18f82009-11-17 02:14:36 +00004415 if (Previous.isAmbiguous())
4416 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004417
John McCall67c00872009-12-02 08:25:40 +00004418 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00004419 if (!Prev || !Prev->isStaticDataMember()) {
4420 // We expect to see a data data member here.
4421 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4422 << Name;
4423 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4424 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004425 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004426 return true;
4427 }
4428
4429 if (!Prev->getInstantiatedFromStaticDataMember()) {
4430 // FIXME: Check for explicit specialization?
4431 Diag(D.getIdentifierLoc(),
4432 diag::err_explicit_instantiation_data_member_not_instantiated)
4433 << Prev;
4434 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4435 // FIXME: Can we provide a note showing where this was declared?
4436 return true;
4437 }
4438
Douglas Gregore47f5a72009-10-14 23:41:34 +00004439 // C++0x [temp.explicit]p2:
4440 // If the explicit instantiation is for a member function, a member class
4441 // or a static data member of a class template specialization, the name of
4442 // the class template specialization in the qualified-id for the member
4443 // name shall be a simple-template-id.
4444 //
4445 // C++98 has the same restriction, just worded differently.
4446 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4447 Diag(D.getIdentifierLoc(),
4448 diag::err_explicit_instantiation_without_qualified_id)
4449 << Prev << D.getCXXScopeSpec().getRange();
4450
4451 // Check the scope of this explicit instantiation.
4452 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4453
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004454 // Verify that it is okay to explicitly instantiate here.
4455 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4456 assert(MSInfo && "Missing static data member specialization info?");
4457 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004458 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004459 MSInfo->getTemplateSpecializationKind(),
4460 MSInfo->getPointOfInstantiation(),
4461 SuppressNew))
4462 return true;
4463 if (SuppressNew)
4464 return DeclPtrTy();
4465
Douglas Gregor450f00842009-09-25 18:43:00 +00004466 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004467 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004468 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004469 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4470 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004471
4472 // FIXME: Create an ExplicitInstantiation node?
4473 return DeclPtrTy();
4474 }
4475
Douglas Gregor0e876e02009-09-25 23:53:26 +00004476 // If the declarator is a template-id, translate the parser's template
4477 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004478 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004479 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004480 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4481 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004482 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4483 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004484 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4485 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004486 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004487 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004488 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004489 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004490 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004491
Douglas Gregor450f00842009-09-25 18:43:00 +00004492 // C++ [temp.explicit]p1:
4493 // A [...] function [...] can be explicitly instantiated from its template.
4494 // A member function [...] of a class template can be explicitly
4495 // instantiated from the member definition associated with its class
4496 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004497 llvm::SmallVector<FunctionDecl *, 8> Matches;
4498 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4499 P != PEnd; ++P) {
4500 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004501 if (!HasExplicitTemplateArgs) {
4502 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4503 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4504 Matches.clear();
4505 Matches.push_back(Method);
4506 break;
4507 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004508 }
4509 }
4510
4511 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4512 if (!FunTmpl)
4513 continue;
4514
4515 TemplateDeductionInfo Info(Context);
4516 FunctionDecl *Specialization = 0;
4517 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004518 = DeduceTemplateArguments(FunTmpl,
4519 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004520 R, Specialization, Info)) {
4521 // FIXME: Keep track of almost-matches?
4522 (void)TDK;
4523 continue;
4524 }
4525
4526 Matches.push_back(Specialization);
4527 }
4528
4529 // Find the most specialized function template specialization.
4530 FunctionDecl *Specialization
4531 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4532 D.getIdentifierLoc(),
4533 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4534 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4535 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4536
4537 if (!Specialization)
4538 return true;
4539
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004540 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004541 Diag(D.getIdentifierLoc(),
4542 diag::err_explicit_instantiation_member_function_not_instantiated)
4543 << Specialization
4544 << (Specialization->getTemplateSpecializationKind() ==
4545 TSK_ExplicitSpecialization);
4546 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4547 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004548 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004549
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004550 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004551 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4552 PrevDecl = Specialization;
4553
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004554 if (PrevDecl) {
4555 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004556 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004557 PrevDecl,
4558 PrevDecl->getTemplateSpecializationKind(),
4559 PrevDecl->getPointOfInstantiation(),
4560 SuppressNew))
4561 return true;
4562
4563 // FIXME: We may still want to build some representation of this
4564 // explicit specialization.
4565 if (SuppressNew)
4566 return DeclPtrTy();
4567 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00004568
4569 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004570
4571 if (TSK == TSK_ExplicitInstantiationDefinition)
4572 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4573 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004574
Douglas Gregore47f5a72009-10-14 23:41:34 +00004575 // C++0x [temp.explicit]p2:
4576 // If the explicit instantiation is for a member function, a member class
4577 // or a static data member of a class template specialization, the name of
4578 // the class template specialization in the qualified-id for the member
4579 // name shall be a simple-template-id.
4580 //
4581 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004582 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004583 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004584 D.getCXXScopeSpec().isSet() &&
4585 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4586 Diag(D.getIdentifierLoc(),
4587 diag::err_explicit_instantiation_without_qualified_id)
4588 << Specialization << D.getCXXScopeSpec().getRange();
4589
4590 CheckExplicitInstantiationScope(*this,
4591 FunTmpl? (NamedDecl *)FunTmpl
4592 : Specialization->getInstantiatedFromMemberFunction(),
4593 D.getIdentifierLoc(),
4594 D.getCXXScopeSpec().isSet());
4595
Douglas Gregor450f00842009-09-25 18:43:00 +00004596 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4597 return DeclPtrTy();
4598}
4599
Douglas Gregor333489b2009-03-27 23:10:48 +00004600Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004601Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4602 const CXXScopeSpec &SS, IdentifierInfo *Name,
4603 SourceLocation TagLoc, SourceLocation NameLoc) {
4604 // This has to hold, because SS is expected to be defined.
4605 assert(Name && "Expected a name in a dependent tag");
4606
4607 NestedNameSpecifier *NNS
4608 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4609 if (!NNS)
4610 return true;
4611
4612 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4613 if (T.isNull())
4614 return true;
4615
4616 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4617 QualType ElabType = Context.getElaboratedType(T, TagKind);
4618
4619 return ElabType.getAsOpaquePtr();
4620}
4621
4622Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004623Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4624 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004625 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004626 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4627 if (!NNS)
4628 return true;
4629
4630 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004631 if (T.isNull())
4632 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004633 return T.getAsOpaquePtr();
4634}
4635
Douglas Gregordce2b622009-04-01 00:28:59 +00004636Sema::TypeResult
4637Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4638 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004639 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004640 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004641 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004642 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004643 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004644 assert(TemplateId && "Expected a template specialization type");
4645
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004646 if (computeDeclContext(SS, false)) {
4647 // If we can compute a declaration context, then the "typename"
4648 // keyword was superfluous. Just build a QualifiedNameType to keep
4649 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004650
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004651 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4652 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4653 }
Mike Stump11289f42009-09-09 15:08:12 +00004654
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004655 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004656}
4657
Douglas Gregor333489b2009-03-27 23:10:48 +00004658/// \brief Build the type that describes a C++ typename specifier,
4659/// e.g., "typename T::type".
4660QualType
4661Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4662 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004663 CXXRecordDecl *CurrentInstantiation = 0;
4664 if (NNS->isDependent()) {
4665 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004666
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004667 // If the nested-name-specifier does not refer to the current
4668 // instantiation, then build a typename type.
4669 if (!CurrentInstantiation)
4670 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004671
Douglas Gregorc707da62009-09-02 13:12:51 +00004672 // The nested-name-specifier refers to the current instantiation, so the
4673 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004674 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004675 // extraneous "typename" keywords, and we retroactively apply this DR to
4676 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004677 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004678
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004679 DeclContext *Ctx = 0;
4680
4681 if (CurrentInstantiation)
4682 Ctx = CurrentInstantiation;
4683 else {
4684 CXXScopeSpec SS;
4685 SS.setScopeRep(NNS);
4686 SS.setRange(Range);
4687 if (RequireCompleteDeclContext(SS))
4688 return QualType();
4689
4690 Ctx = computeDeclContext(SS);
4691 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004692 assert(Ctx && "No declaration context?");
4693
4694 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00004695 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4696 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00004697 unsigned DiagID = 0;
4698 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00004699 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004700 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004701 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004702 break;
4703
4704 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004705 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004706 // We found a type. Build a QualifiedNameType, since the
4707 // typename-specifier was just sugar. FIXME: Tell
4708 // QualifiedNameType that it has a "typename" prefix.
4709 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4710 }
4711
4712 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004713 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004714 break;
4715
John McCalle61f2ba2009-11-18 02:36:19 +00004716 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004717 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00004718 return QualType();
4719
Douglas Gregor333489b2009-03-27 23:10:48 +00004720 case LookupResult::FoundOverloaded:
4721 DiagID = diag::err_typename_nested_not_type;
4722 Referenced = *Result.begin();
4723 break;
4724
John McCall6538c932009-10-10 05:48:19 +00004725 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004726 return QualType();
4727 }
4728
4729 // If we get here, it's because name lookup did not find a
4730 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004731 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004732 if (Referenced)
4733 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4734 << Name;
4735 return QualType();
4736}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004737
4738namespace {
4739 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00004740 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00004741 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004742 SourceLocation Loc;
4743 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004744
Douglas Gregor15acfb92009-08-06 16:20:37 +00004745 public:
Mike Stump11289f42009-09-09 15:08:12 +00004746 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004747 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004748 DeclarationName Entity)
4749 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004750 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004751
4752 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004753 /// transformed.
4754 ///
4755 /// For the purposes of type reconstruction, a type has already been
4756 /// transformed if it is NULL or if it is not dependent.
4757 bool AlreadyTransformed(QualType T) {
4758 return T.isNull() || !T->isDependentType();
4759 }
Mike Stump11289f42009-09-09 15:08:12 +00004760
4761 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004762 /// rebuilt.
4763 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004764
Douglas Gregor15acfb92009-08-06 16:20:37 +00004765 /// \brief Returns the name of the entity whose type is being rebuilt.
4766 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004767
Douglas Gregoref6ab412009-10-27 06:26:26 +00004768 /// \brief Sets the "base" location and entity when that
4769 /// information is known based on another transformation.
4770 void setBase(SourceLocation Loc, DeclarationName Entity) {
4771 this->Loc = Loc;
4772 this->Entity = Entity;
4773 }
4774
Douglas Gregor15acfb92009-08-06 16:20:37 +00004775 /// \brief Transforms an expression by returning the expression itself
4776 /// (an identity function).
4777 ///
4778 /// FIXME: This is completely unsafe; we will need to actually clone the
4779 /// expressions.
4780 Sema::OwningExprResult TransformExpr(Expr *E) {
4781 return getSema().Owned(E);
4782 }
Mike Stump11289f42009-09-09 15:08:12 +00004783
Douglas Gregor15acfb92009-08-06 16:20:37 +00004784 /// \brief Transforms a typename type by determining whether the type now
4785 /// refers to a member of the current instantiation, and then
4786 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004787 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004788 };
4789}
4790
Mike Stump11289f42009-09-09 15:08:12 +00004791QualType
John McCall550e0c22009-10-21 00:40:46 +00004792CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4793 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004794 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004795
Douglas Gregor15acfb92009-08-06 16:20:37 +00004796 NestedNameSpecifier *NNS
4797 = TransformNestedNameSpecifier(T->getQualifier(),
4798 /*FIXME:*/SourceRange(getBaseLocation()));
4799 if (!NNS)
4800 return QualType();
4801
4802 // If the nested-name-specifier did not change, and we cannot compute the
4803 // context corresponding to the nested-name-specifier, then this
4804 // typename type will not change; exit early.
4805 CXXScopeSpec SS;
4806 SS.setRange(SourceRange(getBaseLocation()));
4807 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004808
4809 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004810 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004811 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004812
4813 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004814 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004815 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004816 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004817 = TransformType(QualType(TemplateId, 0));
4818 if (NewTemplateId.isNull())
4819 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004820
Douglas Gregor15acfb92009-08-06 16:20:37 +00004821 if (NNS == T->getQualifier() &&
4822 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004823 Result = QualType(T, 0);
4824 else
4825 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4826 } else
4827 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4828 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004829
John McCall0ad16662009-10-29 08:12:44 +00004830 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4831 NewTL.setNameLoc(TL.getNameLoc());
4832 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004833}
4834
4835/// \brief Rebuilds a type within the context of the current instantiation.
4836///
Mike Stump11289f42009-09-09 15:08:12 +00004837/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004838/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004839/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004840/// partial specialization thereof). This routine will rebuild that type now
4841/// that we have entered the declarator's scope, which may produce different
4842/// canonical types, e.g.,
4843///
4844/// \code
4845/// template<typename T>
4846/// struct X {
4847/// typedef T* pointer;
4848/// pointer data();
4849/// };
4850///
4851/// template<typename T>
4852/// typename X<T>::pointer X<T>::data() { ... }
4853/// \endcode
4854///
4855/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4856/// since we do not know that we can look into X<T> when we parsed the type.
4857/// This function will rebuild the type, performing the lookup of "pointer"
4858/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4859/// as the canonical type of T*, allowing the return types of the out-of-line
4860/// definition and the declaration to match.
4861QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4862 DeclarationName Name) {
4863 if (T.isNull() || !T->isDependentType())
4864 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004865
Douglas Gregor15acfb92009-08-06 16:20:37 +00004866 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4867 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004868}
Douglas Gregorbe999392009-09-15 16:23:51 +00004869
4870/// \brief Produces a formatted string that describes the binding of
4871/// template parameters to template arguments.
4872std::string
4873Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4874 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004875 // FIXME: For variadic templates, we'll need to get the structured list.
4876 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4877 Args.flat_size());
4878}
4879
4880std::string
4881Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4882 const TemplateArgument *Args,
4883 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004884 std::string Result;
4885
Douglas Gregore62e6a02009-11-11 19:13:48 +00004886 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00004887 return Result;
4888
4889 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004890 if (I >= NumArgs)
4891 break;
4892
Douglas Gregorbe999392009-09-15 16:23:51 +00004893 if (I == 0)
4894 Result += "[with ";
4895 else
4896 Result += ", ";
4897
4898 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4899 Result += Id->getName();
4900 } else {
4901 Result += '$';
4902 Result += llvm::utostr(I);
4903 }
4904
4905 Result += " = ";
4906
4907 switch (Args[I].getKind()) {
4908 case TemplateArgument::Null:
4909 Result += "<no value>";
4910 break;
4911
4912 case TemplateArgument::Type: {
4913 std::string TypeStr;
4914 Args[I].getAsType().getAsStringInternal(TypeStr,
4915 Context.PrintingPolicy);
4916 Result += TypeStr;
4917 break;
4918 }
4919
4920 case TemplateArgument::Declaration: {
4921 bool Unnamed = true;
4922 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4923 if (ND->getDeclName()) {
4924 Unnamed = false;
4925 Result += ND->getNameAsString();
4926 }
4927 }
4928
4929 if (Unnamed) {
4930 Result += "<anonymous>";
4931 }
4932 break;
4933 }
4934
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004935 case TemplateArgument::Template: {
4936 std::string Str;
4937 llvm::raw_string_ostream OS(Str);
4938 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4939 Result += OS.str();
4940 break;
4941 }
4942
Douglas Gregorbe999392009-09-15 16:23:51 +00004943 case TemplateArgument::Integral: {
4944 Result += Args[I].getAsIntegral()->toString(10);
4945 break;
4946 }
4947
4948 case TemplateArgument::Expression: {
4949 assert(false && "No expressions in deduced template arguments!");
4950 Result += "<expression>";
4951 break;
4952 }
4953
4954 case TemplateArgument::Pack:
4955 // FIXME: Format template argument packs
4956 Result += "<template argument pack>";
4957 break;
4958 }
4959 }
4960
4961 Result += ']';
4962 return Result;
4963}