blob: 8c6aa6a7d4a9426a60320e91cfc4b3a25aecfe4f [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
Douglas Gregorff18cc12009-12-31 08:11:17 +0000105 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
106 LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +0000107 R.suppressDiagnostics();
108 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
109 if (R.empty())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000110 return TNK_Non_template;
111
John McCalld28ae272009-12-02 08:04:21 +0000112 TemplateName Template;
113 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000114
John McCalld28ae272009-12-02 08:04:21 +0000115 unsigned ResultCount = R.end() - R.begin();
116 if (ResultCount > 1) {
117 // We assume that we'll preserve the qualifier from a function
118 // template name in other ways.
119 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
120 TemplateKind = TNK_Function_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000121 } else {
John McCalld28ae272009-12-02 08:04:21 +0000122 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
123
124 if (SS.isSet() && !SS.isInvalid()) {
125 NestedNameSpecifier *Qualifier
126 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
127 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
128 } else {
129 Template = TemplateName(TD);
130 }
131
132 if (isa<FunctionTemplateDecl>(TD))
133 TemplateKind = TNK_Function_template;
134 else {
135 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
136 TemplateKind = TNK_Type_template;
137 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000138 }
Mike Stump11289f42009-09-09 15:08:12 +0000139
John McCalld28ae272009-12-02 08:04:21 +0000140 TemplateResult = TemplateTy::make(Template);
141 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000142}
143
144void Sema::LookupTemplateName(LookupResult &Found,
145 Scope *S, const CXXScopeSpec &SS,
146 QualType ObjectType,
147 bool EnteringContext) {
148 // Determine where to perform name lookup
149 DeclContext *LookupCtx = 0;
150 bool isDependent = false;
151 if (!ObjectType.isNull()) {
152 // This nested-name-specifier occurs in a member access expression, e.g.,
153 // x->B::f, and we are looking into the type of the object.
154 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
155 LookupCtx = computeDeclContext(ObjectType);
156 isDependent = ObjectType->isDependentType();
157 assert((isDependent || !ObjectType->isIncompleteType()) &&
158 "Caller should have completed object type");
159 } else if (SS.isSet()) {
160 // This nested-name-specifier occurs after another nested-name-specifier,
161 // so long into the context associated with the prior nested-name-specifier.
162 LookupCtx = computeDeclContext(SS, EnteringContext);
163 isDependent = isDependentScopeSpecifier(SS);
164
165 // The declaration context must be complete.
166 if (LookupCtx && RequireCompleteDeclContext(SS))
167 return;
168 }
169
170 bool ObjectTypeSearchedInScope = false;
171 if (LookupCtx) {
172 // Perform "qualified" name lookup into the declaration context we
173 // computed, which is either the type of the base of a member access
174 // expression or the declaration context associated with a prior
175 // nested-name-specifier.
176 LookupQualifiedName(Found, LookupCtx);
177
178 if (!ObjectType.isNull() && Found.empty()) {
179 // C++ [basic.lookup.classref]p1:
180 // In a class member access expression (5.2.5), if the . or -> token is
181 // immediately followed by an identifier followed by a <, the
182 // identifier must be looked up to determine whether the < is the
183 // beginning of a template argument list (14.2) or a less-than operator.
184 // The identifier is first looked up in the class of the object
185 // expression. If the identifier is not found, it is then looked up in
186 // the context of the entire postfix-expression and shall name a class
187 // or function template.
188 //
189 // FIXME: When we're instantiating a template, do we actually have to
190 // look in the scope of the template? Seems fishy...
191 if (S) LookupName(Found, S);
192 ObjectTypeSearchedInScope = true;
193 }
194 } else if (isDependent) {
195 // We cannot look into a dependent object type or
196 return;
197 } else {
198 // Perform unqualified name lookup in the current scope.
199 LookupName(Found, S);
200 }
201
202 // FIXME: Cope with ambiguous name-lookup results.
203 assert(!Found.isAmbiguous() &&
204 "Cannot handle template name-lookup ambiguities");
205
Douglas Gregorff18cc12009-12-31 08:11:17 +0000206 if (Found.empty()) {
207 // If we did not find any names, attempt to correct any typos.
208 DeclarationName Name = Found.getLookupName();
209 if (CorrectTypo(Found, S, &SS, LookupCtx)) {
210 FilterAcceptableTemplateNames(Context, Found);
211 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
212 if (LookupCtx)
213 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
214 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
215 << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
216 Found.getLookupName().getAsString());
217 else
218 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
219 << Name << Found.getLookupName()
220 << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
221 Found.getLookupName().getAsString());
222 } else
223 Found.clear();
224 } else {
225 Found.clear();
226 }
227 }
228
John McCalle66edc12009-11-24 19:00:30 +0000229 FilterAcceptableTemplateNames(Context, Found);
230 if (Found.empty())
231 return;
232
233 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
234 // C++ [basic.lookup.classref]p1:
235 // [...] If the lookup in the class of the object expression finds a
236 // template, the name is also looked up in the context of the entire
237 // postfix-expression and [...]
238 //
239 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
240 LookupOrdinaryName);
241 LookupName(FoundOuter, S);
242 FilterAcceptableTemplateNames(Context, FoundOuter);
243 // FIXME: Handle ambiguities in this lookup better
244
245 if (FoundOuter.empty()) {
246 // - if the name is not found, the name found in the class of the
247 // object expression is used, otherwise
248 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
249 // - if the name is found in the context of the entire
250 // postfix-expression and does not name a class template, the name
251 // found in the class of the object expression is used, otherwise
252 } else {
253 // - if the name found is a class template, it must refer to the same
254 // entity as the one found in the class of the object expression,
255 // otherwise the program is ill-formed.
256 if (!Found.isSingleResult() ||
257 Found.getFoundDecl()->getCanonicalDecl()
258 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
259 Diag(Found.getNameLoc(),
260 diag::err_nested_name_member_ref_lookup_ambiguous)
261 << Found.getLookupName();
262 Diag(Found.getRepresentativeDecl()->getLocation(),
263 diag::note_ambig_member_ref_object_type)
264 << ObjectType;
265 Diag(FoundOuter.getFoundDecl()->getLocation(),
266 diag::note_ambig_member_ref_scope);
267
268 // Recover by taking the template that we found in the object
269 // expression's type.
270 }
271 }
272 }
273}
274
John McCallcd4b4772009-12-02 03:53:29 +0000275/// ActOnDependentIdExpression - Handle a dependent id-expression that
276/// was just parsed. This is only possible with an explicit scope
277/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000278Sema::OwningExprResult
279Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
280 DeclarationName Name,
281 SourceLocation NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000282 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000283 const TemplateArgumentListInfo *TemplateArgs) {
284 NestedNameSpecifier *Qualifier
285 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
286
John McCallcd4b4772009-12-02 03:53:29 +0000287 if (!isAddressOfOperand &&
288 isa<CXXMethodDecl>(CurContext) &&
289 cast<CXXMethodDecl>(CurContext)->isInstance()) {
290 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
291
John McCalle66edc12009-11-24 19:00:30 +0000292 // Since the 'this' expression is synthesized, we don't need to
293 // perform the double-lookup check.
294 NamedDecl *FirstQualifierInScope = 0;
295
John McCall2d74de92009-12-01 22:10:20 +0000296 return Owned(CXXDependentScopeMemberExpr::Create(Context,
297 /*This*/ 0, ThisType,
298 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000299 /*Op*/ SourceLocation(),
300 Qualifier, SS.getRange(),
301 FirstQualifierInScope,
302 Name, NameLoc,
303 TemplateArgs));
304 }
305
306 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
307}
308
309Sema::OwningExprResult
310Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
311 DeclarationName Name,
312 SourceLocation NameLoc,
313 const TemplateArgumentListInfo *TemplateArgs) {
314 return Owned(DependentScopeDeclRefExpr::Create(Context,
315 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
316 SS.getRange(),
317 Name, NameLoc,
318 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000319}
320
Douglas Gregor5101c242008-12-05 18:15:24 +0000321/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
322/// that the template parameter 'PrevDecl' is being shadowed by a new
323/// declaration at location Loc. Returns true to indicate that this is
324/// an error, and false otherwise.
325bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000326 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000327
328 // Microsoft Visual C++ permits template parameters to be shadowed.
329 if (getLangOptions().Microsoft)
330 return false;
331
332 // C++ [temp.local]p4:
333 // A template-parameter shall not be redeclared within its
334 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000335 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000336 << cast<NamedDecl>(PrevDecl)->getDeclName();
337 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
338 return true;
339}
340
Douglas Gregor463421d2009-03-03 04:44:36 +0000341/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000342/// the parameter D to reference the templated declaration and return a pointer
343/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000344TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000345 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000346 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000347 return Temp;
348 }
349 return 0;
350}
351
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000352static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
353 const ParsedTemplateArgument &Arg) {
354
355 switch (Arg.getKind()) {
356 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000357 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000358 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
359 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000360 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000361 return TemplateArgumentLoc(TemplateArgument(T), DI);
362 }
363
364 case ParsedTemplateArgument::NonType: {
365 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
366 return TemplateArgumentLoc(TemplateArgument(E), E);
367 }
368
369 case ParsedTemplateArgument::Template: {
370 TemplateName Template
371 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
372 return TemplateArgumentLoc(TemplateArgument(Template),
373 Arg.getScopeSpec().getRange(),
374 Arg.getLocation());
375 }
376 }
377
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000378 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000379 return TemplateArgumentLoc();
380}
381
382/// \brief Translates template arguments as provided by the parser
383/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000384void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
385 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000386 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000387 TemplateArgs.addArgument(translateTemplateArgument(*this,
388 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000389}
390
Douglas Gregor5101c242008-12-05 18:15:24 +0000391/// ActOnTypeParameter - Called when a C++ template type parameter
392/// (e.g., "typename T") has been parsed. Typename specifies whether
393/// the keyword "typename" was used to declare the type parameter
394/// (otherwise, "class" was used), and KeyLoc is the location of the
395/// "class" or "typename" keyword. ParamName is the name of the
396/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000397/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000398/// If the type parameter has a default argument, it will be added
399/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000400Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000401 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000402 SourceLocation KeyLoc,
403 IdentifierInfo *ParamName,
404 SourceLocation ParamNameLoc,
405 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000406 assert(S->isTemplateParamScope() &&
407 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000408 bool Invalid = false;
409
410 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000411 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000412 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000413 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000414 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000415 }
416
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000417 SourceLocation Loc = ParamNameLoc;
418 if (!ParamName)
419 Loc = KeyLoc;
420
Douglas Gregor5101c242008-12-05 18:15:24 +0000421 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000422 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
423 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000424 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000425 if (Invalid)
426 Param->setInvalidDecl();
427
428 if (ParamName) {
429 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000430 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000431 IdResolver.AddDecl(Param);
432 }
433
Chris Lattner83f095c2009-03-28 19:18:32 +0000434 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000435}
436
Douglas Gregordba32632009-02-10 19:49:53 +0000437/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000438/// Default) to the given template type parameter (TypeParam).
439void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000440 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000441 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000442 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000443 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000444 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000445
John McCallbcd03502009-12-07 02:54:59 +0000446 TypeSourceInfo *DefaultTInfo;
447 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall0ad16662009-10-29 08:12:44 +0000448
John McCallbcd03502009-12-07 02:54:59 +0000449 assert(DefaultTInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000450
Anders Carlssond3824352009-06-12 22:30:13 +0000451 // C++0x [temp.param]p9:
452 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000453 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000454 if (Parm->isParameterPack()) {
455 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000456 return;
457 }
Mike Stump11289f42009-09-09 15:08:12 +0000458
Douglas Gregordba32632009-02-10 19:49:53 +0000459 // C++ [temp.param]p14:
460 // A template-parameter shall not be used in its own default argument.
461 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000462
Douglas Gregordba32632009-02-10 19:49:53 +0000463 // Check the template argument itself.
John McCallbcd03502009-12-07 02:54:59 +0000464 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000465 Parm->setInvalidDecl();
466 return;
467 }
468
John McCallbcd03502009-12-07 02:54:59 +0000469 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000470}
471
Douglas Gregor463421d2009-03-03 04:44:36 +0000472/// \brief Check that the type of a non-type template parameter is
473/// well-formed.
474///
475/// \returns the (possibly-promoted) parameter type if valid;
476/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000477QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000478Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
479 // C++ [temp.param]p4:
480 //
481 // A non-type template-parameter shall have one of the following
482 // (optionally cv-qualified) types:
483 //
484 // -- integral or enumeration type,
485 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000486 // -- pointer to object or pointer to function,
487 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000488 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
489 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000490 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000491 T->isReferenceType() ||
492 // -- pointer to member.
493 T->isMemberPointerType() ||
494 // If T is a dependent type, we can't do the check now, so we
495 // assume that it is well-formed.
496 T->isDependentType())
497 return T;
498 // C++ [temp.param]p8:
499 //
500 // A non-type template-parameter of type "array of T" or
501 // "function returning T" is adjusted to be of type "pointer to
502 // T" or "pointer to function returning T", respectively.
503 else if (T->isArrayType())
504 // FIXME: Keep the type prior to promotion?
505 return Context.getArrayDecayedType(T);
506 else if (T->isFunctionType())
507 // FIXME: Keep the type prior to promotion?
508 return Context.getPointerType(T);
509
510 Diag(Loc, diag::err_template_nontype_parm_bad_type)
511 << T;
512
513 return QualType();
514}
515
Douglas Gregor5101c242008-12-05 18:15:24 +0000516/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
517/// template parameter (e.g., "int Size" in "template<int Size>
518/// class Array") has been parsed. S is the current scope and D is
519/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000520Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000521 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000522 unsigned Position) {
John McCallbcd03502009-12-07 02:54:59 +0000523 TypeSourceInfo *TInfo = 0;
524 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000525
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000526 assert(S->isTemplateParamScope() &&
527 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000528 bool Invalid = false;
529
530 IdentifierInfo *ParamName = D.getIdentifier();
531 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000532 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000533 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000534 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000535 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000536 }
537
Douglas Gregor463421d2009-03-03 04:44:36 +0000538 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000539 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000540 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000541 Invalid = true;
542 }
Douglas Gregor81338792009-02-10 17:43:50 +0000543
Douglas Gregor5101c242008-12-05 18:15:24 +0000544 NonTypeTemplateParmDecl *Param
545 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000546 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000547 if (Invalid)
548 Param->setInvalidDecl();
549
550 if (D.getIdentifier()) {
551 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000552 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000553 IdResolver.AddDecl(Param);
554 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000555 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000556}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000557
Douglas Gregordba32632009-02-10 19:49:53 +0000558/// \brief Adds a default argument to the given non-type template
559/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000560void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000561 SourceLocation EqualLoc,
562 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000563 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000564 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000565 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000566
Douglas Gregordba32632009-02-10 19:49:53 +0000567 // C++ [temp.param]p14:
568 // A template-parameter shall not be used in its own default argument.
569 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000570
Douglas Gregordba32632009-02-10 19:49:53 +0000571 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000572 TemplateArgument Converted;
573 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
574 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000575 TemplateParm->setInvalidDecl();
576 return;
577 }
578
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000579 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000580}
581
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000582
583/// ActOnTemplateTemplateParameter - Called when a C++ template template
584/// parameter (e.g. T in template <template <typename> class T> class array)
585/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000586Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
587 SourceLocation TmpLoc,
588 TemplateParamsTy *Params,
589 IdentifierInfo *Name,
590 SourceLocation NameLoc,
591 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000592 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000593 assert(S->isTemplateParamScope() &&
594 "Template template parameter not in template parameter scope!");
595
596 // Construct the parameter object.
597 TemplateTemplateParmDecl *Param =
598 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
599 Position, Name,
600 (TemplateParameterList*)Params);
601
602 // Make sure the parameter is valid.
603 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
604 // do anything yet. However, if the template parameter list or (eventual)
605 // default value is ever invalidated, that will propagate here.
606 bool Invalid = false;
607 if (Invalid) {
608 Param->setInvalidDecl();
609 }
610
611 // If the tt-param has a name, then link the identifier into the scope
612 // and lookup mechanisms.
613 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000614 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000615 IdResolver.AddDecl(Param);
616 }
617
Chris Lattner83f095c2009-03-28 19:18:32 +0000618 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000619}
620
Douglas Gregordba32632009-02-10 19:49:53 +0000621/// \brief Adds a default argument to the given template template
622/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000623void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000624 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000625 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000626 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000627 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000628
Douglas Gregordba32632009-02-10 19:49:53 +0000629 // C++ [temp.param]p14:
630 // A template-parameter shall not be used in its own default argument.
631 // FIXME: Implement this check! Needs a recursive walk over the types.
632
Douglas Gregore62e6a02009-11-11 19:13:48 +0000633 // Check only that we have a template template argument. We don't want to
634 // try to check well-formedness now, because our template template parameter
635 // might have dependent types in its template parameters, which we wouldn't
636 // be able to match now.
637 //
638 // If none of the template template parameter's template arguments mention
639 // other template parameters, we could actually perform more checking here.
640 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000641 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000642 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
643 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
644 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000645 return;
646 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000647
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000648 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000649}
650
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000651/// ActOnTemplateParameterList - Builds a TemplateParameterList that
652/// contains the template parameters in Params/NumParams.
653Sema::TemplateParamsTy *
654Sema::ActOnTemplateParameterList(unsigned Depth,
655 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000656 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000657 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000658 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000659 SourceLocation RAngleLoc) {
660 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000661 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000662
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000663 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000664 (NamedDecl**)Params, NumParams,
665 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000666}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000667
Douglas Gregorc08f4892009-03-25 00:13:59 +0000668Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000669Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000670 SourceLocation KWLoc, const CXXScopeSpec &SS,
671 IdentifierInfo *Name, SourceLocation NameLoc,
672 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000673 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000674 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000675 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000676 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000677 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000678 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000679
680 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000681 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000682 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000683
John McCall27b5c252009-09-14 21:59:20 +0000684 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
685 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000686
687 // There is no such thing as an unnamed class template.
688 if (!Name) {
689 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000690 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000691 }
692
693 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000694 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000695 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000696 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000697 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000698 if (RequireCompleteDeclContext(SS))
699 return true;
700
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000701 SemanticContext = computeDeclContext(SS, true);
702 if (!SemanticContext) {
703 // FIXME: Produce a reasonable diagnostic here
704 return true;
705 }
Mike Stump11289f42009-09-09 15:08:12 +0000706
John McCall27b18f82009-11-17 02:14:36 +0000707 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000708 } else {
709 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000710 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000711 }
Mike Stump11289f42009-09-09 15:08:12 +0000712
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000713 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
714 NamedDecl *PrevDecl = 0;
715 if (Previous.begin() != Previous.end())
716 PrevDecl = *Previous.begin();
717
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000718 // If there is a previous declaration with the same name, check
719 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000720 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000721 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000722
723 // We may have found the injected-class-name of a class template,
724 // class template partial specialization, or class template specialization.
725 // In these cases, grab the template that is being defined or specialized.
726 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
727 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
728 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
729 PrevClassTemplate
730 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
731 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
732 PrevClassTemplate
733 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
734 ->getSpecializedTemplate();
735 }
736 }
737
John McCalld43784f2009-12-18 11:25:59 +0000738 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000739 // C++ [namespace.memdef]p3:
740 // [...] When looking for a prior declaration of a class or a function
741 // declared as a friend, and when the name of the friend class or
742 // function is neither a qualified name nor a template-id, scopes outside
743 // the innermost enclosing namespace scope are not considered.
744 DeclContext *OutermostContext = CurContext;
745 while (!OutermostContext->isFileContext())
746 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000747
748 if (PrevDecl &&
749 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
750 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
John McCall90d3bb92009-12-17 23:21:11 +0000751 SemanticContext = PrevDecl->getDeclContext();
752 } else {
753 // Declarations in outer scopes don't matter. However, the outermost
754 // context we computed is the semantic context for our new
755 // declaration.
756 PrevDecl = PrevClassTemplate = 0;
757 SemanticContext = OutermostContext;
758 }
759
760 if (CurContext->isDependentContext()) {
761 // If this is a dependent context, we don't want to link the friend
762 // class template to the template in scope, because that would perform
763 // checking of the template parameter lists that can't be performed
764 // until the outer context is instantiated.
765 PrevDecl = PrevClassTemplate = 0;
766 }
767 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
768 PrevDecl = PrevClassTemplate = 0;
769
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000770 if (PrevClassTemplate) {
771 // Ensure that the template parameter lists are compatible.
772 if (!TemplateParameterListsAreEqual(TemplateParams,
773 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000774 /*Complain=*/true,
775 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000776 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000777
778 // C++ [temp.class]p4:
779 // In a redeclaration, partial specialization, explicit
780 // specialization or explicit instantiation of a class template,
781 // the class-key shall agree in kind with the original class
782 // template declaration (7.1.5.3).
783 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000784 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000785 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000786 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000787 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000788 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000789 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000790 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000791 }
792
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000793 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000794 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000795 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
796 Diag(NameLoc, diag::err_redefinition) << Name;
797 Diag(Def->getLocation(), diag::note_previous_definition);
798 // FIXME: Would it make sense to try to "forget" the previous
799 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000800 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000801 }
802 }
803 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
804 // Maybe we will complain about the shadowed template parameter.
805 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
806 // Just pretend that we didn't see the previous declaration.
807 PrevDecl = 0;
808 } else if (PrevDecl) {
809 // C++ [temp]p5:
810 // A class template shall not have the same name as any other
811 // template, class, function, object, enumeration, enumerator,
812 // namespace, or type in the same scope (3.3), except as specified
813 // in (14.5.4).
814 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
815 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000816 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000817 }
818
Douglas Gregordba32632009-02-10 19:49:53 +0000819 // Check the template parameter list of this declaration, possibly
820 // merging in the template parameter list from the previous class
821 // template declaration.
822 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000823 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
824 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000825 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000826
Douglas Gregore362cea2009-05-10 22:57:19 +0000827 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000828 // declaration!
829
Mike Stump11289f42009-09-09 15:08:12 +0000830 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000831 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000832 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000833 PrevClassTemplate->getTemplatedDecl() : 0,
834 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000835
836 ClassTemplateDecl *NewTemplate
837 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
838 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000839 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000840 NewClass->setDescribedClassTemplate(NewTemplate);
841
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000842 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000843 QualType T =
844 Context.getTypeDeclType(NewClass,
845 PrevClassTemplate?
846 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000847 assert(T->isDependentType() && "Class template type is not dependent?");
848 (void)T;
849
Douglas Gregorcf915552009-10-13 16:30:37 +0000850 // If we are providing an explicit specialization of a member that is a
851 // class template, make a note of that.
852 if (PrevClassTemplate &&
853 PrevClassTemplate->getInstantiatedFromMemberTemplate())
854 PrevClassTemplate->setMemberSpecialization();
855
Anders Carlsson137108d2009-03-26 01:24:28 +0000856 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000857 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000858 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000859
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000860 // Set the lexical context of these templates
861 NewClass->setLexicalDeclContext(CurContext);
862 NewTemplate->setLexicalDeclContext(CurContext);
863
John McCall9bb74a52009-07-31 02:45:11 +0000864 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000865 NewClass->startDefinition();
866
867 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000868 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000869
John McCall27b5c252009-09-14 21:59:20 +0000870 if (TUK != TUK_Friend)
871 PushOnScopeChains(NewTemplate, S);
872 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000873 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000874 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000875 NewClass->setAccess(PrevClassTemplate->getAccess());
876 }
John McCall27b5c252009-09-14 21:59:20 +0000877
Douglas Gregor3dad8422009-09-26 06:47:28 +0000878 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
879 PrevClassTemplate != NULL);
880
John McCall27b5c252009-09-14 21:59:20 +0000881 // Friend templates are visible in fairly strange ways.
882 if (!CurContext->isDependentContext()) {
883 DeclContext *DC = SemanticContext->getLookupContext();
884 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
885 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
886 PushOnScopeChains(NewTemplate, EnclosingScope,
887 /* AddToContext = */ false);
888 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000889
890 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
891 NewClass->getLocation(),
892 NewTemplate,
893 /*FIXME:*/NewClass->getLocation());
894 Friend->setAccess(AS_public);
895 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000896 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000897
Douglas Gregordba32632009-02-10 19:49:53 +0000898 if (Invalid) {
899 NewTemplate->setInvalidDecl();
900 NewClass->setInvalidDecl();
901 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000902 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000903}
904
Douglas Gregored5731f2009-11-25 17:50:39 +0000905/// \brief Diagnose the presence of a default template argument on a
906/// template parameter, which is ill-formed in certain contexts.
907///
908/// \returns true if the default template argument should be dropped.
909static bool DiagnoseDefaultTemplateArgument(Sema &S,
910 Sema::TemplateParamListContext TPC,
911 SourceLocation ParamLoc,
912 SourceRange DefArgRange) {
913 switch (TPC) {
914 case Sema::TPC_ClassTemplate:
915 return false;
916
917 case Sema::TPC_FunctionTemplate:
918 // C++ [temp.param]p9:
919 // A default template-argument shall not be specified in a
920 // function template declaration or a function template
921 // definition [...]
922 // (This sentence is not in C++0x, per DR226).
923 if (!S.getLangOptions().CPlusPlus0x)
924 S.Diag(ParamLoc,
925 diag::err_template_parameter_default_in_function_template)
926 << DefArgRange;
927 return false;
928
929 case Sema::TPC_ClassTemplateMember:
930 // C++0x [temp.param]p9:
931 // A default template-argument shall not be specified in the
932 // template-parameter-lists of the definition of a member of a
933 // class template that appears outside of the member's class.
934 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
935 << DefArgRange;
936 return true;
937
938 case Sema::TPC_FriendFunctionTemplate:
939 // C++ [temp.param]p9:
940 // A default template-argument shall not be specified in a
941 // friend template declaration.
942 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
943 << DefArgRange;
944 return true;
945
946 // FIXME: C++0x [temp.param]p9 allows default template-arguments
947 // for friend function templates if there is only a single
948 // declaration (and it is a definition). Strange!
949 }
950
951 return false;
952}
953
Douglas Gregordba32632009-02-10 19:49:53 +0000954/// \brief Checks the validity of a template parameter list, possibly
955/// considering the template parameter list from a previous
956/// declaration.
957///
958/// If an "old" template parameter list is provided, it must be
959/// equivalent (per TemplateParameterListsAreEqual) to the "new"
960/// template parameter list.
961///
962/// \param NewParams Template parameter list for a new template
963/// declaration. This template parameter list will be updated with any
964/// default arguments that are carried through from the previous
965/// template parameter list.
966///
967/// \param OldParams If provided, template parameter list from a
968/// previous declaration of the same template. Default template
969/// arguments will be merged from the old template parameter list to
970/// the new template parameter list.
971///
Douglas Gregored5731f2009-11-25 17:50:39 +0000972/// \param TPC Describes the context in which we are checking the given
973/// template parameter list.
974///
Douglas Gregordba32632009-02-10 19:49:53 +0000975/// \returns true if an error occurred, false otherwise.
976bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000977 TemplateParameterList *OldParams,
978 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +0000979 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000980
Douglas Gregordba32632009-02-10 19:49:53 +0000981 // C++ [temp.param]p10:
982 // The set of default template-arguments available for use with a
983 // template declaration or definition is obtained by merging the
984 // default arguments from the definition (if in scope) and all
985 // declarations in scope in the same way default function
986 // arguments are (8.3.6).
987 bool SawDefaultArgument = false;
988 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000989
Anders Carlsson327865d2009-06-12 23:20:15 +0000990 bool SawParameterPack = false;
991 SourceLocation ParameterPackLoc;
992
Mike Stumpc89c8e32009-02-11 23:03:27 +0000993 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000994 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000995 if (OldParams)
996 OldParam = OldParams->begin();
997
998 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
999 NewParamEnd = NewParams->end();
1000 NewParam != NewParamEnd; ++NewParam) {
1001 // Variables used to diagnose redundant default arguments
1002 bool RedundantDefaultArg = false;
1003 SourceLocation OldDefaultLoc;
1004 SourceLocation NewDefaultLoc;
1005
1006 // Variables used to diagnose missing default arguments
1007 bool MissingDefaultArg = false;
1008
Anders Carlsson327865d2009-06-12 23:20:15 +00001009 // C++0x [temp.param]p11:
1010 // If a template parameter of a class template is a template parameter pack,
1011 // it must be the last template parameter.
1012 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001013 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001014 diag::err_template_param_pack_must_be_last_template_parameter);
1015 Invalid = true;
1016 }
1017
Douglas Gregordba32632009-02-10 19:49:53 +00001018 if (TemplateTypeParmDecl *NewTypeParm
1019 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001020 // Check the presence of a default argument here.
1021 if (NewTypeParm->hasDefaultArgument() &&
1022 DiagnoseDefaultTemplateArgument(*this, TPC,
1023 NewTypeParm->getLocation(),
1024 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1025 .getFullSourceRange()))
1026 NewTypeParm->removeDefaultArgument();
1027
1028 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001029 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001030 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001031
Anders Carlsson327865d2009-06-12 23:20:15 +00001032 if (NewTypeParm->isParameterPack()) {
1033 assert(!NewTypeParm->hasDefaultArgument() &&
1034 "Parameter packs can't have a default argument!");
1035 SawParameterPack = true;
1036 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001037 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001038 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001039 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1040 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1041 SawDefaultArgument = true;
1042 RedundantDefaultArg = true;
1043 PreviousDefaultArgLoc = NewDefaultLoc;
1044 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1045 // Merge the default argument from the old declaration to the
1046 // new declaration.
1047 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001048 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001049 true);
1050 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1051 } else if (NewTypeParm->hasDefaultArgument()) {
1052 SawDefaultArgument = true;
1053 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1054 } else if (SawDefaultArgument)
1055 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001056 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001057 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001058 // Check the presence of a default argument here.
1059 if (NewNonTypeParm->hasDefaultArgument() &&
1060 DiagnoseDefaultTemplateArgument(*this, TPC,
1061 NewNonTypeParm->getLocation(),
1062 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1063 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1064 NewNonTypeParm->setDefaultArgument(0);
1065 }
1066
Mike Stump12b8ce12009-08-04 21:02:39 +00001067 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001068 NonTypeTemplateParmDecl *OldNonTypeParm
1069 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001070 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001071 NewNonTypeParm->hasDefaultArgument()) {
1072 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1073 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1074 SawDefaultArgument = true;
1075 RedundantDefaultArg = true;
1076 PreviousDefaultArgLoc = NewDefaultLoc;
1077 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1078 // Merge the default argument from the old declaration to the
1079 // new declaration.
1080 SawDefaultArgument = true;
1081 // FIXME: We need to create a new kind of "default argument"
1082 // expression that points to a previous template template
1083 // parameter.
1084 NewNonTypeParm->setDefaultArgument(
1085 OldNonTypeParm->getDefaultArgument());
1086 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1087 } else if (NewNonTypeParm->hasDefaultArgument()) {
1088 SawDefaultArgument = true;
1089 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1090 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001091 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001092 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001093 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001094 TemplateTemplateParmDecl *NewTemplateParm
1095 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001096 if (NewTemplateParm->hasDefaultArgument() &&
1097 DiagnoseDefaultTemplateArgument(*this, TPC,
1098 NewTemplateParm->getLocation(),
1099 NewTemplateParm->getDefaultArgument().getSourceRange()))
1100 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1101
1102 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001103 TemplateTemplateParmDecl *OldTemplateParm
1104 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001105 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001106 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001107 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1108 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001109 SawDefaultArgument = true;
1110 RedundantDefaultArg = true;
1111 PreviousDefaultArgLoc = NewDefaultLoc;
1112 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1113 // Merge the default argument from the old declaration to the
1114 // new declaration.
1115 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001116 // FIXME: We need to create a new kind of "default argument" expression
1117 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001118 NewTemplateParm->setDefaultArgument(
1119 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001120 PreviousDefaultArgLoc
1121 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001122 } else if (NewTemplateParm->hasDefaultArgument()) {
1123 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001124 PreviousDefaultArgLoc
1125 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001126 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001127 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001128 }
1129
1130 if (RedundantDefaultArg) {
1131 // C++ [temp.param]p12:
1132 // A template-parameter shall not be given default arguments
1133 // by two different declarations in the same scope.
1134 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1135 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1136 Invalid = true;
1137 } else if (MissingDefaultArg) {
1138 // C++ [temp.param]p11:
1139 // If a template-parameter has a default template-argument,
1140 // all subsequent template-parameters shall have a default
1141 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001142 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001143 diag::err_template_param_default_arg_missing);
1144 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1145 Invalid = true;
1146 }
1147
1148 // If we have an old template parameter list that we're merging
1149 // in, move on to the next parameter.
1150 if (OldParams)
1151 ++OldParam;
1152 }
1153
1154 return Invalid;
1155}
Douglas Gregord32e0282009-02-09 23:23:08 +00001156
Mike Stump11289f42009-09-09 15:08:12 +00001157/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001158/// specifier, returning the template parameter list that applies to the
1159/// name.
1160///
1161/// \param DeclStartLoc the start of the declaration that has a scope
1162/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001163///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001164/// \param SS the scope specifier that will be matched to the given template
1165/// parameter lists. This scope specifier precedes a qualified name that is
1166/// being declared.
1167///
1168/// \param ParamLists the template parameter lists, from the outermost to the
1169/// innermost template parameter lists.
1170///
1171/// \param NumParamLists the number of template parameter lists in ParamLists.
1172///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001173/// \param IsExplicitSpecialization will be set true if the entity being
1174/// declared is an explicit specialization, false otherwise.
1175///
Mike Stump11289f42009-09-09 15:08:12 +00001176/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001177/// name that is preceded by the scope specifier @p SS. This template
1178/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001179/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001180/// template specialization), or may be NULL (if we were's declaring isn't
1181/// itself a template).
1182TemplateParameterList *
1183Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1184 const CXXScopeSpec &SS,
1185 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001186 unsigned NumParamLists,
1187 bool &IsExplicitSpecialization) {
1188 IsExplicitSpecialization = false;
1189
Douglas Gregord8d297c2009-07-21 23:53:31 +00001190 // Find the template-ids that occur within the nested-name-specifier. These
1191 // template-ids will match up with the template parameter lists.
1192 llvm::SmallVector<const TemplateSpecializationType *, 4>
1193 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001194 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1195 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001196 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1197 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001198 const Type *T = NNS->getAsType();
1199 if (!T) break;
1200
1201 // C++0x [temp.expl.spec]p17:
1202 // A member or a member template may be nested within many
1203 // enclosing class templates. In an explicit specialization for
1204 // such a member, the member declaration shall be preceded by a
1205 // template<> for each enclosing class template that is
1206 // explicitly specialized.
1207 // We interpret this as forbidding typedefs of template
1208 // specializations in the scope specifiers of out-of-line decls.
1209 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) {
1210 const Type *UnderlyingT = TT->LookThroughTypedefs().getTypePtr();
1211 if (isa<TemplateSpecializationType>(UnderlyingT))
1212 // FIXME: better source location information.
1213 Diag(DeclStartLoc, diag::err_typedef_in_def_scope) << QualType(T,0);
1214 T = UnderlyingT;
1215 }
1216
Mike Stump11289f42009-09-09 15:08:12 +00001217 if (const TemplateSpecializationType *SpecType
John McCall90034062009-12-15 02:19:47 +00001218 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001219 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1220 if (!Template)
1221 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001222
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001223 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001224 ClassTemplateSpecializationDecl *SpecDecl
1225 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1226 // If the nested name specifier refers to an explicit specialization,
1227 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001228 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1229 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001230 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001231 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001232 }
Mike Stump11289f42009-09-09 15:08:12 +00001233
Douglas Gregord8d297c2009-07-21 23:53:31 +00001234 TemplateIdsInSpecifier.push_back(SpecType);
1235 }
1236 }
Mike Stump11289f42009-09-09 15:08:12 +00001237
Douglas Gregord8d297c2009-07-21 23:53:31 +00001238 // Reverse the list of template-ids in the scope specifier, so that we can
1239 // more easily match up the template-ids and the template parameter lists.
1240 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001241
Douglas Gregord8d297c2009-07-21 23:53:31 +00001242 SourceLocation FirstTemplateLoc = DeclStartLoc;
1243 if (NumParamLists)
1244 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001245
Douglas Gregord8d297c2009-07-21 23:53:31 +00001246 // Match the template-ids found in the specifier to the template parameter
1247 // lists.
1248 unsigned Idx = 0;
1249 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1250 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001251 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1252 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001253 if (Idx >= NumParamLists) {
1254 // We have a template-id without a corresponding template parameter
1255 // list.
1256 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001257 // FIXME: the location information here isn't great.
1258 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001259 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001260 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001261 << SS.getRange();
1262 } else {
1263 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1264 << SS.getRange()
1265 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1266 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001267 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001268 }
1269 return 0;
1270 }
Mike Stump11289f42009-09-09 15:08:12 +00001271
Douglas Gregord8d297c2009-07-21 23:53:31 +00001272 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001273 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001274 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001275 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1276
Mike Stump11289f42009-09-09 15:08:12 +00001277 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001278 = dyn_cast<ClassTemplateDecl>(Template)) {
1279 TemplateParameterList *ExpectedTemplateParams = 0;
1280 // Is this template-id naming the primary template?
1281 if (Context.hasSameType(TemplateId,
1282 ClassTemplate->getInjectedClassNameType(Context)))
1283 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1284 // ... or a partial specialization?
1285 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1286 = ClassTemplate->findPartialSpecialization(TemplateId))
1287 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1288
1289 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001290 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001291 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001292 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001293 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001294
1295 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001296 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001297 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001298 diag::err_template_param_list_matches_nontemplate)
1299 << TemplateId
1300 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001301 else
1302 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001303 }
Mike Stump11289f42009-09-09 15:08:12 +00001304
Douglas Gregord8d297c2009-07-21 23:53:31 +00001305 // If there were at least as many template-ids as there were template
1306 // parameter lists, then there are no template parameter lists remaining for
1307 // the declaration itself.
1308 if (Idx >= NumParamLists)
1309 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001310
Douglas Gregord8d297c2009-07-21 23:53:31 +00001311 // If there were too many template parameter lists, complain about that now.
1312 if (Idx != NumParamLists - 1) {
1313 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001314 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001315 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001316 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1317 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001318 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1319 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001320
1321 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1322 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1323 diag::note_explicit_template_spec_does_not_need_header)
1324 << ExplicitSpecializationsInSpecifier.back();
1325 ExplicitSpecializationsInSpecifier.pop_back();
1326 }
1327
Douglas Gregord8d297c2009-07-21 23:53:31 +00001328 ++Idx;
1329 }
1330 }
Mike Stump11289f42009-09-09 15:08:12 +00001331
Douglas Gregord8d297c2009-07-21 23:53:31 +00001332 // Return the last template parameter list, which corresponds to the
1333 // entity being declared.
1334 return ParamLists[NumParamLists - 1];
1335}
1336
Douglas Gregordc572a32009-03-30 22:58:21 +00001337QualType Sema::CheckTemplateIdType(TemplateName Name,
1338 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001339 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001340 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001341 if (!Template) {
1342 // The template name does not resolve to a template, so we just
1343 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001344 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001345 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001346
Douglas Gregorc40290e2009-03-09 23:48:35 +00001347 // Check that the template argument list is well-formed for this
1348 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001349 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001350 TemplateArgs.size());
1351 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001352 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001353 return QualType();
1354
Mike Stump11289f42009-09-09 15:08:12 +00001355 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001356 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001357 "Converted template argument list is too short!");
1358
1359 QualType CanonType;
1360
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001361 if (Name.isDependent() ||
1362 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001363 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001364 // This class template specialization is a dependent
1365 // type. Therefore, its canonical type is another class template
1366 // specialization type that contains all of the converted
1367 // arguments in canonical form. This ensures that, e.g., A<T> and
1368 // A<T, T> have identical types when A is declared as:
1369 //
1370 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001371 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001372 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001373 Converted.getFlatArguments(),
1374 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001375
Douglas Gregora8e02e72009-07-28 23:00:59 +00001376 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001377 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001378 // In the future, we need to teach getTemplateSpecializationType to only
1379 // build the canonical type and return that to us.
1380 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001381 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001382 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001383 // Find the class template specialization declaration that
1384 // corresponds to these arguments.
1385 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001386 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001387 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001388 Converted.flatSize(),
1389 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001390 void *InsertPos = 0;
1391 ClassTemplateSpecializationDecl *Decl
1392 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1393 if (!Decl) {
1394 // This is the first time we have referenced this class template
1395 // specialization. Create the canonical declaration and add it to
1396 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001397 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001398 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001399 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001400 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001401 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001402 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1403 Decl->setLexicalDeclContext(CurContext);
1404 }
1405
1406 CanonType = Context.getTypeDeclType(Decl);
1407 }
Mike Stump11289f42009-09-09 15:08:12 +00001408
Douglas Gregorc40290e2009-03-09 23:48:35 +00001409 // Build the fully-sugared type for this class template
1410 // specialization, which refers back to the class template
1411 // specialization we created or found.
John McCall6b51f282009-11-23 01:53:49 +00001412 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001413}
1414
Douglas Gregor67a65642009-02-17 23:15:12 +00001415Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001416Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001417 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001418 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001419 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001420 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001421
Douglas Gregorc40290e2009-03-09 23:48:35 +00001422 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001423 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001424 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001425
John McCall6b51f282009-11-23 01:53:49 +00001426 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001427 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001428
1429 if (Result.isNull())
1430 return true;
1431
John McCallbcd03502009-12-07 02:54:59 +00001432 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001433 TemplateSpecializationTypeLoc TL
1434 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1435 TL.setTemplateNameLoc(TemplateLoc);
1436 TL.setLAngleLoc(LAngleLoc);
1437 TL.setRAngleLoc(RAngleLoc);
1438 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1439 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1440
1441 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001442}
John McCall06f6fe8d2009-09-04 01:14:41 +00001443
John McCalld8fe9af2009-09-08 17:47:29 +00001444Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1445 TagUseKind TUK,
1446 DeclSpec::TST TagSpec,
1447 SourceLocation TagLoc) {
1448 if (TypeResult.isInvalid())
1449 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001450
John McCall0ad16662009-10-29 08:12:44 +00001451 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001452 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001453 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001454
John McCalld8fe9af2009-09-08 17:47:29 +00001455 // Verify the tag specifier.
1456 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001457
John McCalld8fe9af2009-09-08 17:47:29 +00001458 if (const RecordType *RT = Type->getAs<RecordType>()) {
1459 RecordDecl *D = RT->getDecl();
1460
1461 IdentifierInfo *Id = D->getIdentifier();
1462 assert(Id && "templated class must have an identifier");
1463
1464 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1465 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001466 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001467 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1468 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001469 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001470 }
1471 }
1472
John McCalld8fe9af2009-09-08 17:47:29 +00001473 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1474
1475 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001476}
1477
John McCalle66edc12009-11-24 19:00:30 +00001478Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1479 LookupResult &R,
1480 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001481 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001482 // FIXME: Can we do any checking at this point? I guess we could check the
1483 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001484 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001485 // though.
John McCalle66edc12009-11-24 19:00:30 +00001486
1487 // These should be filtered out by our callers.
1488 assert(!R.empty() && "empty lookup results when building templateid");
1489 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1490
1491 NestedNameSpecifier *Qualifier = 0;
1492 SourceRange QualifierRange;
1493 if (SS.isSet()) {
1494 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1495 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001496 }
1497
John McCalle66edc12009-11-24 19:00:30 +00001498 bool Dependent
1499 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1500 &TemplateArgs);
1501 UnresolvedLookupExpr *ULE
1502 = UnresolvedLookupExpr::Create(Context, Dependent,
1503 Qualifier, QualifierRange,
1504 R.getLookupName(), R.getNameLoc(),
1505 RequiresADL, TemplateArgs);
1506 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1507 ULE->addDecl(*I);
1508
1509 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001510}
1511
John McCalle66edc12009-11-24 19:00:30 +00001512// We actually only call this from template instantiation.
1513Sema::OwningExprResult
1514Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1515 DeclarationName Name,
1516 SourceLocation NameLoc,
1517 const TemplateArgumentListInfo &TemplateArgs) {
1518 DeclContext *DC;
1519 if (!(DC = computeDeclContext(SS, false)) ||
1520 DC->isDependentContext() ||
1521 RequireCompleteDeclContext(SS))
1522 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001523
John McCalle66edc12009-11-24 19:00:30 +00001524 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1525 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00001526
John McCalle66edc12009-11-24 19:00:30 +00001527 if (R.isAmbiguous())
1528 return ExprError();
1529
1530 if (R.empty()) {
1531 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1532 << Name << SS.getRange();
1533 return ExprError();
1534 }
1535
1536 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1537 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1538 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1539 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1540 return ExprError();
1541 }
1542
1543 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001544}
1545
Douglas Gregorb67535d2009-03-31 00:43:58 +00001546/// \brief Form a dependent template name.
1547///
1548/// This action forms a dependent template name given the template
1549/// name and its (presumably dependent) scope specifier. For
1550/// example, given "MetaFun::template apply", the scope specifier \p
1551/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1552/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001553Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001554Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001555 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001556 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001557 TypeTy *ObjectType,
1558 bool EnteringContext) {
Mike Stump11289f42009-09-09 15:08:12 +00001559 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001560 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001561 (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001562 // C++0x [temp.names]p5:
1563 // If a name prefixed by the keyword template is not the name of
1564 // a template, the program is ill-formed. [Note: the keyword
1565 // template may not be applied to non-template members of class
1566 // templates. -end note ] [ Note: as is the case with the
1567 // typename prefix, the template prefix is allowed in cases
1568 // where it is not strictly necessary; i.e., when the
1569 // nested-name-specifier or the expression on the left of the ->
1570 // or . is not dependent on a template-parameter, or the use
1571 // does not appear in the scope of a template. -end note]
1572 //
1573 // Note: C++03 was more strict here, because it banned the use of
1574 // the "template" keyword prior to a template-name that was not a
1575 // dependent name. C++ DR468 relaxed this requirement (the
1576 // "template" keyword is now permitted). We follow the C++0x
1577 // rules, even in C++03 mode, retroactively applying the DR.
1578 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001579 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001580 EnteringContext, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001581 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001582 Diag(Name.getSourceRange().getBegin(),
1583 diag::err_template_kw_refers_to_non_template)
1584 << GetNameFromUnqualifiedId(Name)
1585 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001586 return TemplateTy();
1587 }
1588
1589 return Template;
1590 }
1591
Mike Stump11289f42009-09-09 15:08:12 +00001592 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001593 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001594
1595 switch (Name.getKind()) {
1596 case UnqualifiedId::IK_Identifier:
1597 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1598 Name.Identifier));
1599
Douglas Gregor71395fa2009-11-04 00:56:37 +00001600 case UnqualifiedId::IK_OperatorFunctionId:
1601 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1602 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001603
1604 case UnqualifiedId::IK_LiteralOperatorId:
1605 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1606
Douglas Gregor3cf81312009-11-03 23:16:33 +00001607 default:
1608 break;
1609 }
1610
1611 Diag(Name.getSourceRange().getBegin(),
1612 diag::err_template_kw_refers_to_non_template)
1613 << GetNameFromUnqualifiedId(Name)
1614 << Name.getSourceRange();
1615 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001616}
1617
Mike Stump11289f42009-09-09 15:08:12 +00001618bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001619 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001620 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001621 const TemplateArgument &Arg = AL.getArgument();
1622
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001623 // Check template type parameter.
1624 if (Arg.getKind() != TemplateArgument::Type) {
1625 // C++ [temp.arg.type]p1:
1626 // A template-argument for a template-parameter which is a
1627 // type shall be a type-id.
1628
1629 // We have a template type parameter but the template argument
1630 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001631 SourceRange SR = AL.getSourceRange();
1632 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001633 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001634
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001635 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001636 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001637
John McCallbcd03502009-12-07 02:54:59 +00001638 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001639 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001640
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001641 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001642 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001643 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001644 return false;
1645}
1646
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001647/// \brief Substitute template arguments into the default template argument for
1648/// the given template type parameter.
1649///
1650/// \param SemaRef the semantic analysis object for which we are performing
1651/// the substitution.
1652///
1653/// \param Template the template that we are synthesizing template arguments
1654/// for.
1655///
1656/// \param TemplateLoc the location of the template name that started the
1657/// template-id we are checking.
1658///
1659/// \param RAngleLoc the location of the right angle bracket ('>') that
1660/// terminates the template-id.
1661///
1662/// \param Param the template template parameter whose default we are
1663/// substituting into.
1664///
1665/// \param Converted the list of template arguments provided for template
1666/// parameters that precede \p Param in the template parameter list.
1667///
1668/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001669static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001670SubstDefaultTemplateArgument(Sema &SemaRef,
1671 TemplateDecl *Template,
1672 SourceLocation TemplateLoc,
1673 SourceLocation RAngleLoc,
1674 TemplateTypeParmDecl *Param,
1675 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001676 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001677
1678 // If the argument type is dependent, instantiate it now based
1679 // on the previously-computed template arguments.
1680 if (ArgType->getType()->isDependentType()) {
1681 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1682 /*TakeArgs=*/false);
1683
1684 MultiLevelTemplateArgumentList AllTemplateArgs
1685 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1686
1687 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1688 Template, Converted.getFlatArguments(),
1689 Converted.flatSize(),
1690 SourceRange(TemplateLoc, RAngleLoc));
1691
1692 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1693 Param->getDefaultArgumentLoc(),
1694 Param->getDeclName());
1695 }
1696
1697 return ArgType;
1698}
1699
1700/// \brief Substitute template arguments into the default template argument for
1701/// the given non-type template parameter.
1702///
1703/// \param SemaRef the semantic analysis object for which we are performing
1704/// the substitution.
1705///
1706/// \param Template the template that we are synthesizing template arguments
1707/// for.
1708///
1709/// \param TemplateLoc the location of the template name that started the
1710/// template-id we are checking.
1711///
1712/// \param RAngleLoc the location of the right angle bracket ('>') that
1713/// terminates the template-id.
1714///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001715/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001716/// substituting into.
1717///
1718/// \param Converted the list of template arguments provided for template
1719/// parameters that precede \p Param in the template parameter list.
1720///
1721/// \returns the substituted template argument, or NULL if an error occurred.
1722static Sema::OwningExprResult
1723SubstDefaultTemplateArgument(Sema &SemaRef,
1724 TemplateDecl *Template,
1725 SourceLocation TemplateLoc,
1726 SourceLocation RAngleLoc,
1727 NonTypeTemplateParmDecl *Param,
1728 TemplateArgumentListBuilder &Converted) {
1729 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1730 /*TakeArgs=*/false);
1731
1732 MultiLevelTemplateArgumentList AllTemplateArgs
1733 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1734
1735 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1736 Template, Converted.getFlatArguments(),
1737 Converted.flatSize(),
1738 SourceRange(TemplateLoc, RAngleLoc));
1739
1740 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1741}
1742
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001743/// \brief Substitute template arguments into the default template argument for
1744/// the given template template parameter.
1745///
1746/// \param SemaRef the semantic analysis object for which we are performing
1747/// the substitution.
1748///
1749/// \param Template the template that we are synthesizing template arguments
1750/// for.
1751///
1752/// \param TemplateLoc the location of the template name that started the
1753/// template-id we are checking.
1754///
1755/// \param RAngleLoc the location of the right angle bracket ('>') that
1756/// terminates the template-id.
1757///
1758/// \param Param the template template parameter whose default we are
1759/// substituting into.
1760///
1761/// \param Converted the list of template arguments provided for template
1762/// parameters that precede \p Param in the template parameter list.
1763///
1764/// \returns the substituted template argument, or NULL if an error occurred.
1765static TemplateName
1766SubstDefaultTemplateArgument(Sema &SemaRef,
1767 TemplateDecl *Template,
1768 SourceLocation TemplateLoc,
1769 SourceLocation RAngleLoc,
1770 TemplateTemplateParmDecl *Param,
1771 TemplateArgumentListBuilder &Converted) {
1772 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1773 /*TakeArgs=*/false);
1774
1775 MultiLevelTemplateArgumentList AllTemplateArgs
1776 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1777
1778 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1779 Template, Converted.getFlatArguments(),
1780 Converted.flatSize(),
1781 SourceRange(TemplateLoc, RAngleLoc));
1782
1783 return SemaRef.SubstTemplateName(
1784 Param->getDefaultArgument().getArgument().getAsTemplate(),
1785 Param->getDefaultArgument().getTemplateNameLoc(),
1786 AllTemplateArgs);
1787}
1788
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001789/// \brief If the given template parameter has a default template
1790/// argument, substitute into that default template argument and
1791/// return the corresponding template argument.
1792TemplateArgumentLoc
1793Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1794 SourceLocation TemplateLoc,
1795 SourceLocation RAngleLoc,
1796 Decl *Param,
1797 TemplateArgumentListBuilder &Converted) {
1798 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1799 if (!TypeParm->hasDefaultArgument())
1800 return TemplateArgumentLoc();
1801
John McCallbcd03502009-12-07 02:54:59 +00001802 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001803 TemplateLoc,
1804 RAngleLoc,
1805 TypeParm,
1806 Converted);
1807 if (DI)
1808 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1809
1810 return TemplateArgumentLoc();
1811 }
1812
1813 if (NonTypeTemplateParmDecl *NonTypeParm
1814 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1815 if (!NonTypeParm->hasDefaultArgument())
1816 return TemplateArgumentLoc();
1817
1818 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1819 TemplateLoc,
1820 RAngleLoc,
1821 NonTypeParm,
1822 Converted);
1823 if (Arg.isInvalid())
1824 return TemplateArgumentLoc();
1825
1826 Expr *ArgE = Arg.takeAs<Expr>();
1827 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1828 }
1829
1830 TemplateTemplateParmDecl *TempTempParm
1831 = cast<TemplateTemplateParmDecl>(Param);
1832 if (!TempTempParm->hasDefaultArgument())
1833 return TemplateArgumentLoc();
1834
1835 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1836 TemplateLoc,
1837 RAngleLoc,
1838 TempTempParm,
1839 Converted);
1840 if (TName.isNull())
1841 return TemplateArgumentLoc();
1842
1843 return TemplateArgumentLoc(TemplateArgument(TName),
1844 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1845 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1846}
1847
Douglas Gregorda0fb532009-11-11 19:31:23 +00001848/// \brief Check that the given template argument corresponds to the given
1849/// template parameter.
1850bool Sema::CheckTemplateArgument(NamedDecl *Param,
1851 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001852 TemplateDecl *Template,
1853 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001854 SourceLocation RAngleLoc,
1855 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001856 // Check template type parameters.
1857 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001858 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001859
Douglas Gregoreebed722009-11-11 19:41:09 +00001860 // Check non-type template parameters.
1861 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001862 // Do substitution on the type of the non-type template parameter
1863 // with the template arguments we've seen thus far.
1864 QualType NTTPType = NTTP->getType();
1865 if (NTTPType->isDependentType()) {
1866 // Do substitution on the type of the non-type template parameter.
1867 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1868 NTTP, Converted.getFlatArguments(),
1869 Converted.flatSize(),
1870 SourceRange(TemplateLoc, RAngleLoc));
1871
1872 TemplateArgumentList TemplateArgs(Context, Converted,
1873 /*TakeArgs=*/false);
1874 NTTPType = SubstType(NTTPType,
1875 MultiLevelTemplateArgumentList(TemplateArgs),
1876 NTTP->getLocation(),
1877 NTTP->getDeclName());
1878 // If that worked, check the non-type template parameter type
1879 // for validity.
1880 if (!NTTPType.isNull())
1881 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1882 NTTP->getLocation());
1883 if (NTTPType.isNull())
1884 return true;
1885 }
1886
1887 switch (Arg.getArgument().getKind()) {
1888 case TemplateArgument::Null:
1889 assert(false && "Should never see a NULL template argument here");
1890 return true;
1891
1892 case TemplateArgument::Expression: {
1893 Expr *E = Arg.getArgument().getAsExpr();
1894 TemplateArgument Result;
1895 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1896 return true;
1897
1898 Converted.Append(Result);
1899 break;
1900 }
1901
1902 case TemplateArgument::Declaration:
1903 case TemplateArgument::Integral:
1904 // We've already checked this template argument, so just copy
1905 // it to the list of converted arguments.
1906 Converted.Append(Arg.getArgument());
1907 break;
1908
1909 case TemplateArgument::Template:
1910 // We were given a template template argument. It may not be ill-formed;
1911 // see below.
1912 if (DependentTemplateName *DTN
1913 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1914 // We have a template argument such as \c T::template X, which we
1915 // parsed as a template template argument. However, since we now
1916 // know that we need a non-type template argument, convert this
1917 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00001918 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1919 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00001920 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00001921 DTN->getIdentifier(),
1922 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00001923
1924 TemplateArgument Result;
1925 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1926 return true;
1927
1928 Converted.Append(Result);
1929 break;
1930 }
1931
1932 // We have a template argument that actually does refer to a class
1933 // template, template alias, or template template parameter, and
1934 // therefore cannot be a non-type template argument.
1935 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1936 << Arg.getSourceRange();
1937
1938 Diag(Param->getLocation(), diag::note_template_param_here);
1939 return true;
1940
1941 case TemplateArgument::Type: {
1942 // We have a non-type template parameter but the template
1943 // argument is a type.
1944
1945 // C++ [temp.arg]p2:
1946 // In a template-argument, an ambiguity between a type-id and
1947 // an expression is resolved to a type-id, regardless of the
1948 // form of the corresponding template-parameter.
1949 //
1950 // We warn specifically about this case, since it can be rather
1951 // confusing for users.
1952 QualType T = Arg.getArgument().getAsType();
1953 SourceRange SR = Arg.getSourceRange();
1954 if (T->isFunctionType())
1955 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1956 else
1957 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1958 Diag(Param->getLocation(), diag::note_template_param_here);
1959 return true;
1960 }
1961
1962 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001963 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001964 break;
1965 }
1966
1967 return false;
1968 }
1969
1970
1971 // Check template template parameters.
1972 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1973
1974 // Substitute into the template parameter list of the template
1975 // template parameter, since previously-supplied template arguments
1976 // may appear within the template template parameter.
1977 {
1978 // Set up a template instantiation context.
1979 LocalInstantiationScope Scope(*this);
1980 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1981 TempParm, Converted.getFlatArguments(),
1982 Converted.flatSize(),
1983 SourceRange(TemplateLoc, RAngleLoc));
1984
1985 TemplateArgumentList TemplateArgs(Context, Converted,
1986 /*TakeArgs=*/false);
1987 TempParm = cast_or_null<TemplateTemplateParmDecl>(
1988 SubstDecl(TempParm, CurContext,
1989 MultiLevelTemplateArgumentList(TemplateArgs)));
1990 if (!TempParm)
1991 return true;
1992
1993 // FIXME: TempParam is leaked.
1994 }
1995
1996 switch (Arg.getArgument().getKind()) {
1997 case TemplateArgument::Null:
1998 assert(false && "Should never see a NULL template argument here");
1999 return true;
2000
2001 case TemplateArgument::Template:
2002 if (CheckTemplateArgument(TempParm, Arg))
2003 return true;
2004
2005 Converted.Append(Arg.getArgument());
2006 break;
2007
2008 case TemplateArgument::Expression:
2009 case TemplateArgument::Type:
2010 // We have a template template parameter but the template
2011 // argument does not refer to a template.
2012 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2013 return true;
2014
2015 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002016 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002017 "Declaration argument with template template parameter");
2018 break;
2019 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002020 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002021 "Integral argument with template template parameter");
2022 break;
2023
2024 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002025 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002026 break;
2027 }
2028
2029 return false;
2030}
2031
Douglas Gregord32e0282009-02-09 23:23:08 +00002032/// \brief Check that the given template argument list is well-formed
2033/// for specializing the given template.
2034bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2035 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002036 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002037 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002038 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002039 TemplateParameterList *Params = Template->getTemplateParameters();
2040 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002041 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002042 bool Invalid = false;
2043
John McCall6b51f282009-11-23 01:53:49 +00002044 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2045
Mike Stump11289f42009-09-09 15:08:12 +00002046 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002047 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002048
Anders Carlsson15201f12009-06-13 02:08:00 +00002049 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002050 (NumArgs < Params->getMinRequiredArguments() &&
2051 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002052 // FIXME: point at either the first arg beyond what we can handle,
2053 // or the '>', depending on whether we have too many or too few
2054 // arguments.
2055 SourceRange Range;
2056 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002057 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002058 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2059 << (NumArgs > NumParams)
2060 << (isa<ClassTemplateDecl>(Template)? 0 :
2061 isa<FunctionTemplateDecl>(Template)? 1 :
2062 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2063 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002064 Diag(Template->getLocation(), diag::note_template_decl_here)
2065 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002066 Invalid = true;
2067 }
Mike Stump11289f42009-09-09 15:08:12 +00002068
2069 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002070 // [...] The type and form of each template-argument specified in
2071 // a template-id shall match the type and form specified for the
2072 // corresponding parameter declared by the template in its
2073 // template-parameter-list.
2074 unsigned ArgIdx = 0;
2075 for (TemplateParameterList::iterator Param = Params->begin(),
2076 ParamEnd = Params->end();
2077 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002078 if (ArgIdx > NumArgs && PartialTemplateArgs)
2079 break;
Mike Stump11289f42009-09-09 15:08:12 +00002080
Douglas Gregoreebed722009-11-11 19:41:09 +00002081 // If we have a template parameter pack, check every remaining template
2082 // argument against that template parameter pack.
2083 if ((*Param)->isTemplateParameterPack()) {
2084 Converted.BeginPack();
2085 for (; ArgIdx < NumArgs; ++ArgIdx) {
2086 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2087 TemplateLoc, RAngleLoc, Converted)) {
2088 Invalid = true;
2089 break;
2090 }
2091 }
2092 Converted.EndPack();
2093 continue;
2094 }
2095
Douglas Gregor84d49a22009-11-11 21:54:23 +00002096 if (ArgIdx < NumArgs) {
2097 // Check the template argument we were given.
2098 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2099 TemplateLoc, RAngleLoc, Converted))
2100 return true;
2101
2102 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002103 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002104
Douglas Gregor84d49a22009-11-11 21:54:23 +00002105 // We have a default template argument that we will use.
2106 TemplateArgumentLoc Arg;
2107
2108 // Retrieve the default template argument from the template
2109 // parameter. For each kind of template parameter, we substitute the
2110 // template arguments provided thus far and any "outer" template arguments
2111 // (when the template parameter was part of a nested template) into
2112 // the default argument.
2113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2114 if (!TTP->hasDefaultArgument()) {
2115 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2116 break;
2117 }
2118
John McCallbcd03502009-12-07 02:54:59 +00002119 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002120 Template,
2121 TemplateLoc,
2122 RAngleLoc,
2123 TTP,
2124 Converted);
2125 if (!ArgType)
2126 return true;
2127
2128 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2129 ArgType);
2130 } else if (NonTypeTemplateParmDecl *NTTP
2131 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2132 if (!NTTP->hasDefaultArgument()) {
2133 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2134 break;
2135 }
2136
2137 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2138 TemplateLoc,
2139 RAngleLoc,
2140 NTTP,
2141 Converted);
2142 if (E.isInvalid())
2143 return true;
2144
2145 Expr *Ex = E.takeAs<Expr>();
2146 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2147 } else {
2148 TemplateTemplateParmDecl *TempParm
2149 = cast<TemplateTemplateParmDecl>(*Param);
2150
2151 if (!TempParm->hasDefaultArgument()) {
2152 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2153 break;
2154 }
2155
2156 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2157 TemplateLoc,
2158 RAngleLoc,
2159 TempParm,
2160 Converted);
2161 if (Name.isNull())
2162 return true;
2163
2164 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2165 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2166 TempParm->getDefaultArgument().getTemplateNameLoc());
2167 }
2168
2169 // Introduce an instantiation record that describes where we are using
2170 // the default template argument.
2171 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2172 Converted.getFlatArguments(),
2173 Converted.flatSize(),
2174 SourceRange(TemplateLoc, RAngleLoc));
2175
2176 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002177 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002178 RAngleLoc, Converted))
2179 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002180 }
2181
2182 return Invalid;
2183}
2184
2185/// \brief Check a template argument against its corresponding
2186/// template type parameter.
2187///
2188/// This routine implements the semantics of C++ [temp.arg.type]. It
2189/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002190bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002191 TypeSourceInfo *ArgInfo) {
2192 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002193 QualType Arg = ArgInfo->getType();
2194
Douglas Gregord32e0282009-02-09 23:23:08 +00002195 // C++ [temp.arg.type]p2:
2196 // A local type, a type with no linkage, an unnamed type or a type
2197 // compounded from any of these types shall not be used as a
2198 // template-argument for a template type-parameter.
2199 //
2200 // FIXME: Perform the recursive and no-linkage type checks.
2201 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002202 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002203 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002204 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002205 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002206 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2207 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2208 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2209 << QualType(Tag, 0) << SR;
2210 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002211 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002212 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2213 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002214 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2215 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002216 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2217 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2218 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002219 }
2220
2221 return false;
2222}
2223
Douglas Gregorccb07762009-02-11 19:52:55 +00002224/// \brief Checks whether the given template argument is the address
2225/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002226bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2227 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002228 bool Invalid = false;
2229
2230 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002231 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002232 Arg = Cast->getSubExpr();
2233
Sebastian Redl576fd422009-05-10 18:38:11 +00002234 // C++0x allows nullptr, and there's no further checking to be done for that.
2235 if (Arg->getType()->isNullPtrType())
2236 return false;
2237
Douglas Gregorccb07762009-02-11 19:52:55 +00002238 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002239 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002240 // A template-argument for a non-type, non-template
2241 // template-parameter shall be one of: [...]
2242 //
2243 // -- the address of an object or function with external
2244 // linkage, including function templates and function
2245 // template-ids but excluding non-static class members,
2246 // expressed as & id-expression where the & is optional if
2247 // the name refers to a function or array, or if the
2248 // corresponding template-parameter is a reference; or
2249 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002250
Douglas Gregorccb07762009-02-11 19:52:55 +00002251 // Ignore (and complain about) any excess parentheses.
2252 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2253 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002254 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002255 diag::err_template_arg_extra_parens)
2256 << Arg->getSourceRange();
2257 Invalid = true;
2258 }
2259
2260 Arg = Parens->getSubExpr();
2261 }
2262
2263 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2264 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2265 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2266 } else
2267 DRE = dyn_cast<DeclRefExpr>(Arg);
2268
2269 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002270 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002271 diag::err_template_arg_not_object_or_func_form)
2272 << Arg->getSourceRange();
2273
2274 // Cannot refer to non-static data members
2275 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2276 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2277 << Field << Arg->getSourceRange();
2278
2279 // Cannot refer to non-static member functions
2280 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2281 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002282 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002283 diag::err_template_arg_method)
2284 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002285
Douglas Gregorccb07762009-02-11 19:52:55 +00002286 // Functions must have external linkage.
2287 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregorf73b2822009-11-25 22:24:25 +00002288 if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump11289f42009-09-09 15:08:12 +00002289 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002290 diag::err_template_arg_function_not_extern)
2291 << Func << Arg->getSourceRange();
2292 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2293 << true;
2294 return true;
2295 }
2296
2297 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002298 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002299 return Invalid;
2300 }
2301
2302 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregorf73b2822009-11-25 22:24:25 +00002303 if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump11289f42009-09-09 15:08:12 +00002304 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002305 diag::err_template_arg_object_not_extern)
2306 << Var << Arg->getSourceRange();
2307 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2308 << true;
2309 return true;
2310 }
2311
2312 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002313 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002314 return Invalid;
2315 }
Mike Stump11289f42009-09-09 15:08:12 +00002316
Douglas Gregorccb07762009-02-11 19:52:55 +00002317 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002318 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002319 diag::err_template_arg_not_object_or_func)
2320 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002321 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002322 diag::note_template_arg_refers_here);
2323 return true;
2324}
2325
2326/// \brief Checks whether the given template argument is a pointer to
2327/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002328bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2329 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002330 bool Invalid = false;
2331
2332 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002333 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002334 Arg = Cast->getSubExpr();
2335
Sebastian Redl576fd422009-05-10 18:38:11 +00002336 // C++0x allows nullptr, and there's no further checking to be done for that.
2337 if (Arg->getType()->isNullPtrType())
2338 return false;
2339
Douglas Gregorccb07762009-02-11 19:52:55 +00002340 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002341 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002342 // A template-argument for a non-type, non-template
2343 // template-parameter shall be one of: [...]
2344 //
2345 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002346 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002347
2348 // Ignore (and complain about) any excess parentheses.
2349 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2350 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002351 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002352 diag::err_template_arg_extra_parens)
2353 << Arg->getSourceRange();
2354 Invalid = true;
2355 }
2356
2357 Arg = Parens->getSubExpr();
2358 }
2359
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002360 // A pointer-to-member constant written &Class::member.
2361 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002362 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2363 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2364 if (DRE && !DRE->getQualifier())
2365 DRE = 0;
2366 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002367 }
2368 // A constant of pointer-to-member type.
2369 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2370 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2371 if (VD->getType()->isMemberPointerType()) {
2372 if (isa<NonTypeTemplateParmDecl>(VD) ||
2373 (isa<VarDecl>(VD) &&
2374 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2375 if (Arg->isTypeDependent() || Arg->isValueDependent())
2376 Converted = TemplateArgument(Arg->Retain());
2377 else
2378 Converted = TemplateArgument(VD->getCanonicalDecl());
2379 return Invalid;
2380 }
2381 }
2382 }
2383
2384 DRE = 0;
2385 }
2386
Douglas Gregorccb07762009-02-11 19:52:55 +00002387 if (!DRE)
2388 return Diag(Arg->getSourceRange().getBegin(),
2389 diag::err_template_arg_not_pointer_to_member_form)
2390 << Arg->getSourceRange();
2391
2392 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2393 assert((isa<FieldDecl>(DRE->getDecl()) ||
2394 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2395 "Only non-static member pointers can make it here");
2396
2397 // Okay: this is the address of a non-static member, and therefore
2398 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002399 if (Arg->isTypeDependent() || Arg->isValueDependent())
2400 Converted = TemplateArgument(Arg->Retain());
2401 else
2402 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002403 return Invalid;
2404 }
2405
2406 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002407 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002408 diag::err_template_arg_not_pointer_to_member_form)
2409 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002410 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002411 diag::note_template_arg_refers_here);
2412 return true;
2413}
2414
Douglas Gregord32e0282009-02-09 23:23:08 +00002415/// \brief Check a template argument against its corresponding
2416/// non-type template parameter.
2417///
Douglas Gregor463421d2009-03-03 04:44:36 +00002418/// This routine implements the semantics of C++ [temp.arg.nontype].
2419/// It returns true if an error occurred, and false otherwise. \p
2420/// InstantiatedParamType is the type of the non-type template
2421/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002422///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002423/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002424bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002425 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002426 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002427 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2428
Douglas Gregor86560402009-02-10 23:36:10 +00002429 // If either the parameter has a dependent type or the argument is
2430 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002431 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002432 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2433 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002434 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002435 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002436 }
Douglas Gregor86560402009-02-10 23:36:10 +00002437
2438 // C++ [temp.arg.nontype]p5:
2439 // The following conversions are performed on each expression used
2440 // as a non-type template-argument. If a non-type
2441 // template-argument cannot be converted to the type of the
2442 // corresponding template-parameter then the program is
2443 // ill-formed.
2444 //
2445 // -- for a non-type template-parameter of integral or
2446 // enumeration type, integral promotions (4.5) and integral
2447 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002448 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002449 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002450 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002451 // C++ [temp.arg.nontype]p1:
2452 // A template-argument for a non-type, non-template
2453 // template-parameter shall be one of:
2454 //
2455 // -- an integral constant-expression of integral or enumeration
2456 // type; or
2457 // -- the name of a non-type template-parameter; or
2458 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002459 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002460 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002461 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002462 diag::err_template_arg_not_integral_or_enumeral)
2463 << ArgType << Arg->getSourceRange();
2464 Diag(Param->getLocation(), diag::note_template_param_here);
2465 return true;
2466 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002467 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002468 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2469 << ArgType << Arg->getSourceRange();
2470 return true;
2471 }
2472
2473 // FIXME: We need some way to more easily get the unqualified form
2474 // of the types without going all the way to the
2475 // canonical type.
2476 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2477 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2478 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2479 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2480
2481 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002482 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002483 // Okay: no conversion necessary
2484 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2485 !ParamType->isEnumeralType()) {
2486 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002487 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002488 } else {
2489 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002490 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002491 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002492 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002493 Diag(Param->getLocation(), diag::note_template_param_here);
2494 return true;
2495 }
2496
Douglas Gregor52aba872009-03-14 00:20:21 +00002497 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002498 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002499 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002500
2501 if (!Arg->isValueDependent()) {
2502 // Check that an unsigned parameter does not receive a negative
2503 // value.
2504 if (IntegerType->isUnsignedIntegerType()
2505 && (Value.isSigned() && Value.isNegative())) {
2506 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2507 << Value.toString(10) << Param->getType()
2508 << Arg->getSourceRange();
2509 Diag(Param->getLocation(), diag::note_template_param_here);
2510 return true;
2511 }
2512
2513 // Check that we don't overflow the template parameter type.
2514 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Eli Friedman38b9ad82009-12-23 18:44:58 +00002515 unsigned RequiredBits;
2516 if (IntegerType->isUnsignedIntegerType())
2517 RequiredBits = Value.getActiveBits();
2518 else if (Value.isUnsigned())
2519 RequiredBits = Value.getActiveBits() + 1;
2520 else
2521 RequiredBits = Value.getMinSignedBits();
2522 if (RequiredBits > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002523 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002524 diag::err_template_arg_too_large)
2525 << Value.toString(10) << Param->getType()
2526 << Arg->getSourceRange();
2527 Diag(Param->getLocation(), diag::note_template_param_here);
2528 return true;
2529 }
2530
2531 if (Value.getBitWidth() != AllowedBits)
2532 Value.extOrTrunc(AllowedBits);
2533 Value.setIsSigned(IntegerType->isSignedIntegerType());
2534 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002535
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002536 // Add the value of this argument to the list of converted
2537 // arguments. We use the bitwidth and signedness of the template
2538 // parameter.
2539 if (Arg->isValueDependent()) {
2540 // The argument is value-dependent. Create a new
2541 // TemplateArgument with the converted expression.
2542 Converted = TemplateArgument(Arg);
2543 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002544 }
2545
John McCall0ad16662009-10-29 08:12:44 +00002546 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002547 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002548 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002549 return false;
2550 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002551
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002552 // Handle pointer-to-function, reference-to-function, and
2553 // pointer-to-member-function all in (roughly) the same way.
2554 if (// -- For a non-type template-parameter of type pointer to
2555 // function, only the function-to-pointer conversion (4.3) is
2556 // applied. If the template-argument represents a set of
2557 // overloaded functions (or a pointer to such), the matching
2558 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002559 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002560 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002561 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002562 // -- For a non-type template-parameter of type reference to
2563 // function, no conversions apply. If the template-argument
2564 // represents a set of overloaded functions, the matching
2565 // function is selected from the set (13.4).
2566 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002567 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002568 // -- For a non-type template-parameter of type pointer to
2569 // member function, no conversions apply. If the
2570 // template-argument represents a set of overloaded member
2571 // functions, the matching member function is selected from
2572 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002573 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002574 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002575 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002576 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002577 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002578 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002579 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002580 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2581 ParamType->isMemberPointerType())) {
2582 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002583 if (ParamType->isMemberPointerType())
2584 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2585 else
2586 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002587 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002588 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002589 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002590 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002591 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002592 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2593 return true;
2594
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002595 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002596 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002597 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002598 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002599 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002600 }
2601 }
2602
Mike Stump11289f42009-09-09 15:08:12 +00002603 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002604 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002605 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002606 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002607 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002608 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002609 Diag(Param->getLocation(), diag::note_template_param_here);
2610 return true;
2611 }
Mike Stump11289f42009-09-09 15:08:12 +00002612
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002613 if (ParamType->isMemberPointerType())
2614 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002615
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002616 NamedDecl *Entity = 0;
2617 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2618 return true;
2619
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002620 if (Entity)
2621 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002622 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002623 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002624 }
2625
Chris Lattner696197c2009-02-20 21:37:53 +00002626 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002627 // -- for a non-type template-parameter of type pointer to
2628 // object, qualification conversions (4.4) and the
2629 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002630 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002631 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002632 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002633
Sebastian Redl576fd422009-05-10 18:38:11 +00002634 if (ArgType->isNullPtrType()) {
2635 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002636 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002637 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002638 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002639 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002640 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002641
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002642 if (IsQualificationConversion(ArgType, ParamType)) {
2643 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002644 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002645 }
Mike Stump11289f42009-09-09 15:08:12 +00002646
Douglas Gregor1515f762009-02-11 18:22:40 +00002647 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002648 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002649 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002650 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002651 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002652 Diag(Param->getLocation(), diag::note_template_param_here);
2653 return true;
2654 }
Mike Stump11289f42009-09-09 15:08:12 +00002655
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002656 NamedDecl *Entity = 0;
2657 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2658 return true;
2659
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002660 if (Entity)
2661 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002662 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002663 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002664 }
Mike Stump11289f42009-09-09 15:08:12 +00002665
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002666 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002667 // -- For a non-type template-parameter of type reference to
2668 // object, no conversions apply. The type referred to by the
2669 // reference may be more cv-qualified than the (otherwise
2670 // identical) type of the template-argument. The
2671 // template-parameter is bound directly to the
2672 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002673 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002674 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002675
Douglas Gregor1515f762009-02-11 18:22:40 +00002676 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002677 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002678 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002679 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002680 << Arg->getSourceRange();
2681 Diag(Param->getLocation(), diag::note_template_param_here);
2682 return true;
2683 }
2684
Mike Stump11289f42009-09-09 15:08:12 +00002685 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002686 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2687 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002688
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002689 if ((ParamQuals | ArgQuals) != ParamQuals) {
2690 Diag(Arg->getSourceRange().getBegin(),
2691 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002692 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002693 << Arg->getSourceRange();
2694 Diag(Param->getLocation(), diag::note_template_param_here);
2695 return true;
2696 }
Mike Stump11289f42009-09-09 15:08:12 +00002697
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002698 NamedDecl *Entity = 0;
2699 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2700 return true;
2701
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002702 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002703 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002704 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002705 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002706
2707 // -- For a non-type template-parameter of type pointer to data
2708 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002709 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002710 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2711
Douglas Gregor1515f762009-02-11 18:22:40 +00002712 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002713 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002714 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002715 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002716 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002717 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002718 } else {
2719 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002720 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002721 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002722 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002723 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002724 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002725 }
2726
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002727 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002728}
2729
2730/// \brief Check a template argument against its corresponding
2731/// template template parameter.
2732///
2733/// This routine implements the semantics of C++ [temp.arg.template].
2734/// It returns true if an error occurred, and false otherwise.
2735bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002736 const TemplateArgumentLoc &Arg) {
2737 TemplateName Name = Arg.getArgument().getAsTemplate();
2738 TemplateDecl *Template = Name.getAsTemplateDecl();
2739 if (!Template) {
2740 // Any dependent template name is fine.
2741 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2742 return false;
2743 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002744
2745 // C++ [temp.arg.template]p1:
2746 // A template-argument for a template template-parameter shall be
2747 // the name of a class template, expressed as id-expression. Only
2748 // primary class templates are considered when matching the
2749 // template template argument with the corresponding parameter;
2750 // partial specializations are not considered even if their
2751 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002752 //
2753 // Note that we also allow template template parameters here, which
2754 // will happen when we are dealing with, e.g., class template
2755 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002756 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002757 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002758 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002759 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002760 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002761 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002762 << Template;
2763 }
2764
2765 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2766 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002767 true,
2768 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002769 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002770}
2771
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002772/// \brief Determine whether the given template parameter lists are
2773/// equivalent.
2774///
Mike Stump11289f42009-09-09 15:08:12 +00002775/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002776/// source code as part of a new template declaration.
2777///
2778/// \param Old The old template parameter list, typically found via
2779/// name lookup of the template declared with this template parameter
2780/// list.
2781///
2782/// \param Complain If true, this routine will produce a diagnostic if
2783/// the template parameter lists are not equivalent.
2784///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002785/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00002786///
2787/// \param TemplateArgLoc If this source location is valid, then we
2788/// are actually checking the template parameter list of a template
2789/// argument (New) against the template parameter list of its
2790/// corresponding template template parameter (Old). We produce
2791/// slightly different diagnostics in this scenario.
2792///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002793/// \returns True if the template parameter lists are equal, false
2794/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002795bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002796Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2797 TemplateParameterList *Old,
2798 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002799 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002800 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002801 if (Old->size() != New->size()) {
2802 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002803 unsigned NextDiag = diag::err_template_param_list_different_arity;
2804 if (TemplateArgLoc.isValid()) {
2805 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2806 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002807 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002808 Diag(New->getTemplateLoc(), NextDiag)
2809 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002810 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002811 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002812 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002813 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002814 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2815 }
2816
2817 return false;
2818 }
2819
2820 for (TemplateParameterList::iterator OldParm = Old->begin(),
2821 OldParmEnd = Old->end(), NewParm = New->begin();
2822 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2823 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002824 if (Complain) {
2825 unsigned NextDiag = diag::err_template_param_different_kind;
2826 if (TemplateArgLoc.isValid()) {
2827 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2828 NextDiag = diag::note_template_param_different_kind;
2829 }
2830 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002831 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00002832 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002833 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00002834 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002835 return false;
2836 }
2837
2838 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2839 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002840 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002841 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002842 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2843 // The types of non-type template parameters must agree.
2844 NonTypeTemplateParmDecl *NewNTTP
2845 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002846
2847 // If we are matching a template template argument to a template
2848 // template parameter and one of the non-type template parameter types
2849 // is dependent, then we must wait until template instantiation time
2850 // to actually compare the arguments.
2851 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2852 (OldNTTP->getType()->isDependentType() ||
2853 NewNTTP->getType()->isDependentType()))
2854 continue;
2855
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002856 if (Context.getCanonicalType(OldNTTP->getType()) !=
2857 Context.getCanonicalType(NewNTTP->getType())) {
2858 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002859 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2860 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002861 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002862 diag::err_template_arg_template_params_mismatch);
2863 NextDiag = diag::note_template_nontype_parm_different_type;
2864 }
2865 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002866 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002867 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00002868 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002869 diag::note_template_nontype_parm_prev_declaration)
2870 << OldNTTP->getType();
2871 }
2872 return false;
2873 }
2874 } else {
2875 // The template parameter lists of template template
2876 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002877 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002878 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002879 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002880 = cast<TemplateTemplateParmDecl>(*OldParm);
2881 TemplateTemplateParmDecl *NewTTP
2882 = cast<TemplateTemplateParmDecl>(*NewParm);
2883 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2884 OldTTP->getTemplateParameters(),
2885 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002886 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00002887 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002888 return false;
2889 }
2890 }
2891
2892 return true;
2893}
2894
2895/// \brief Check whether a template can be declared within this scope.
2896///
2897/// If the template declaration is valid in this scope, returns
2898/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002899bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002900Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002901 // Find the nearest enclosing declaration scope.
2902 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2903 (S->getFlags() & Scope::TemplateParamScope) != 0)
2904 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002905
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002906 // C++ [temp]p2:
2907 // A template-declaration can appear only as a namespace scope or
2908 // class scope declaration.
2909 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002910 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2911 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002912 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002913 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002914
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002915 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002916 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002917
2918 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2919 return false;
2920
Mike Stump11289f42009-09-09 15:08:12 +00002921 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002922 diag::err_template_outside_namespace_or_class_scope)
2923 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002924}
Douglas Gregor67a65642009-02-17 23:15:12 +00002925
Douglas Gregor54888652009-10-07 00:13:32 +00002926/// \brief Determine what kind of template specialization the given declaration
2927/// is.
2928static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2929 if (!D)
2930 return TSK_Undeclared;
2931
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002932 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2933 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002934 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2935 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002936 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2937 return Var->getTemplateSpecializationKind();
2938
Douglas Gregor54888652009-10-07 00:13:32 +00002939 return TSK_Undeclared;
2940}
2941
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002942/// \brief Check whether a specialization is well-formed in the current
2943/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002944///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002945/// This routine determines whether a template specialization can be declared
2946/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002947///
2948/// \param S the semantic analysis object for which this check is being
2949/// performed.
2950///
2951/// \param Specialized the entity being specialized or instantiated, which
2952/// may be a kind of template (class template, function template, etc.) or
2953/// a member of a class template (member function, static data member,
2954/// member class).
2955///
2956/// \param PrevDecl the previous declaration of this entity, if any.
2957///
2958/// \param Loc the location of the explicit specialization or instantiation of
2959/// this entity.
2960///
2961/// \param IsPartialSpecialization whether this is a partial specialization of
2962/// a class template.
2963///
Douglas Gregor54888652009-10-07 00:13:32 +00002964/// \returns true if there was an error that we cannot recover from, false
2965/// otherwise.
2966static bool CheckTemplateSpecializationScope(Sema &S,
2967 NamedDecl *Specialized,
2968 NamedDecl *PrevDecl,
2969 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002970 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002971 // Keep these "kind" numbers in sync with the %select statements in the
2972 // various diagnostics emitted by this routine.
2973 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002974 bool isTemplateSpecialization = false;
2975 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002976 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002977 isTemplateSpecialization = true;
2978 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002979 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002980 isTemplateSpecialization = true;
2981 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002982 EntityKind = 3;
2983 else if (isa<VarDecl>(Specialized))
2984 EntityKind = 4;
2985 else if (isa<RecordDecl>(Specialized))
2986 EntityKind = 5;
2987 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002988 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2989 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00002990 return true;
2991 }
2992
Douglas Gregorf47b9112009-02-25 22:02:03 +00002993 // C++ [temp.expl.spec]p2:
2994 // An explicit specialization shall be declared in the namespace
2995 // of which the template is a member, or, for member templates, in
2996 // the namespace of which the enclosing class or enclosing class
2997 // template is a member. An explicit specialization of a member
2998 // function, member class or static data member of a class
2999 // template shall be declared in the namespace of which the class
3000 // template is a member. Such a declaration may also be a
3001 // definition. If the declaration is not a definition, the
3002 // specialization may be defined later in the name- space in which
3003 // the explicit specialization was declared, or in a namespace
3004 // that encloses the one in which the explicit specialization was
3005 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003006 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3007 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003008 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003009 return true;
3010 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003011
Douglas Gregor40fb7442009-10-07 17:30:37 +00003012 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3013 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003014 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003015 return true;
3016 }
3017
Douglas Gregore4b05162009-10-07 17:21:34 +00003018 // C++ [temp.class.spec]p6:
3019 // A class template partial specialization may be declared or redeclared
3020 // in any namespace scope in which its definition may be defined (14.5.1
3021 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003022 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003023 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003024 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003025 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003026 if ((!PrevDecl ||
3027 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3028 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3029 // There is no prior declaration of this entity, so this
3030 // specialization must be in the same context as the template
3031 // itself.
3032 if (!DC->Equals(SpecializedContext)) {
3033 if (isa<TranslationUnitDecl>(SpecializedContext))
3034 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3035 << EntityKind << Specialized;
3036 else if (isa<NamespaceDecl>(SpecializedContext))
3037 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3038 << EntityKind << Specialized
3039 << cast<NamedDecl>(SpecializedContext);
3040
3041 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3042 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003043 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003044 }
Douglas Gregor54888652009-10-07 00:13:32 +00003045
3046 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003047 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003048 // Note that HandleDeclarator() performs this check for explicit
3049 // specializations of function templates, static data members, and member
3050 // functions, so we skip the check here for those kinds of entities.
3051 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003052 // Should we refactor that check, so that it occurs later?
3053 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003054 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3055 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003056 if (isa<TranslationUnitDecl>(SpecializedContext))
3057 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3058 << EntityKind << Specialized;
3059 else if (isa<NamespaceDecl>(SpecializedContext))
3060 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3061 << EntityKind << Specialized
3062 << cast<NamedDecl>(SpecializedContext);
3063
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003064 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003065 }
Douglas Gregor54888652009-10-07 00:13:32 +00003066
3067 // FIXME: check for specialization-after-instantiation errors and such.
3068
Douglas Gregorf47b9112009-02-25 22:02:03 +00003069 return false;
3070}
Douglas Gregor54888652009-10-07 00:13:32 +00003071
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003072/// \brief Check the non-type template arguments of a class template
3073/// partial specialization according to C++ [temp.class.spec]p9.
3074///
Douglas Gregor09a30232009-06-12 22:08:06 +00003075/// \param TemplateParams the template parameters of the primary class
3076/// template.
3077///
3078/// \param TemplateArg the template arguments of the class template
3079/// partial specialization.
3080///
3081/// \param MirrorsPrimaryTemplate will be set true if the class
3082/// template partial specialization arguments are identical to the
3083/// implicit template arguments of the primary template. This is not
3084/// necessarily an error (C++0x), and it is left to the caller to diagnose
3085/// this condition when it is an error.
3086///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003087/// \returns true if there was an error, false otherwise.
3088bool Sema::CheckClassTemplatePartialSpecializationArgs(
3089 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003090 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003091 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003092 // FIXME: the interface to this function will have to change to
3093 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003094 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003095
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003096 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003097
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003098 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003099 // Determine whether the template argument list of the partial
3100 // specialization is identical to the implicit argument list of
3101 // the primary template. The caller may need to diagnostic this as
3102 // an error per C++ [temp.class.spec]p9b3.
3103 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003104 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003105 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3106 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003107 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003108 MirrorsPrimaryTemplate = false;
3109 } else if (TemplateTemplateParmDecl *TTP
3110 = dyn_cast<TemplateTemplateParmDecl>(
3111 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003112 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003113 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003114 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003115 if (!ArgDecl ||
3116 ArgDecl->getIndex() != TTP->getIndex() ||
3117 ArgDecl->getDepth() != TTP->getDepth())
3118 MirrorsPrimaryTemplate = false;
3119 }
3120 }
3121
Mike Stump11289f42009-09-09 15:08:12 +00003122 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003123 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003124 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003125 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003126 }
3127
Anders Carlsson40c1d492009-06-13 18:20:51 +00003128 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003129 if (!ArgExpr) {
3130 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003131 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003132 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003133
3134 // C++ [temp.class.spec]p8:
3135 // A non-type argument is non-specialized if it is the name of a
3136 // non-type parameter. All other non-type arguments are
3137 // specialized.
3138 //
3139 // Below, we check the two conditions that only apply to
3140 // specialized non-type arguments, so skip any non-specialized
3141 // arguments.
3142 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003143 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003144 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003145 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003146 (Param->getIndex() != NTTP->getIndex() ||
3147 Param->getDepth() != NTTP->getDepth()))
3148 MirrorsPrimaryTemplate = false;
3149
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003150 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003151 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003152
3153 // C++ [temp.class.spec]p9:
3154 // Within the argument list of a class template partial
3155 // specialization, the following restrictions apply:
3156 // -- A partially specialized non-type argument expression
3157 // shall not involve a template parameter of the partial
3158 // specialization except when the argument expression is a
3159 // simple identifier.
3160 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003161 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003162 diag::err_dependent_non_type_arg_in_partial_spec)
3163 << ArgExpr->getSourceRange();
3164 return true;
3165 }
3166
3167 // -- The type of a template parameter corresponding to a
3168 // specialized non-type argument shall not be dependent on a
3169 // parameter of the specialization.
3170 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003171 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003172 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3173 << Param->getType()
3174 << ArgExpr->getSourceRange();
3175 Diag(Param->getLocation(), diag::note_template_param_here);
3176 return true;
3177 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003178
3179 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003180 }
3181
3182 return false;
3183}
3184
Douglas Gregorc08f4892009-03-25 00:13:59 +00003185Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003186Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3187 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003188 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00003189 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003190 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003191 SourceLocation TemplateNameLoc,
3192 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003193 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003194 SourceLocation RAngleLoc,
3195 AttributeList *Attr,
3196 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003197 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003198
Douglas Gregor67a65642009-02-17 23:15:12 +00003199 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003200 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003201 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003202 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3203
3204 if (!ClassTemplate) {
3205 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3206 << (Name.getAsTemplateDecl() &&
3207 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3208 return true;
3209 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003210
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003211 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003212 bool isPartialSpecialization = false;
3213
Douglas Gregorf47b9112009-02-25 22:02:03 +00003214 // Check the validity of the template headers that introduce this
3215 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003216 // FIXME: We probably shouldn't complain about these headers for
3217 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003218 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003219 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3220 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003221 TemplateParameterLists.size(),
3222 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003223 if (TemplateParams && TemplateParams->size() > 0) {
3224 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003225
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003226 // C++ [temp.class.spec]p10:
3227 // The template parameter list of a specialization shall not
3228 // contain default template argument values.
3229 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3230 Decl *Param = TemplateParams->getParam(I);
3231 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3232 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003233 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003234 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003235 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003236 }
3237 } else if (NonTypeTemplateParmDecl *NTTP
3238 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3239 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003240 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003241 diag::err_default_arg_in_partial_spec)
3242 << DefArg->getSourceRange();
3243 NTTP->setDefaultArgument(0);
3244 DefArg->Destroy(Context);
3245 }
3246 } else {
3247 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003248 if (TTP->hasDefaultArgument()) {
3249 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003250 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003251 << TTP->getDefaultArgument().getSourceRange();
3252 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003253 }
3254 }
3255 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003256 } else if (TemplateParams) {
3257 if (TUK == TUK_Friend)
3258 Diag(KWLoc, diag::err_template_spec_friend)
3259 << CodeModificationHint::CreateRemoval(
3260 SourceRange(TemplateParams->getTemplateLoc(),
3261 TemplateParams->getRAngleLoc()))
3262 << SourceRange(LAngleLoc, RAngleLoc);
3263 else
3264 isExplicitSpecialization = true;
3265 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003266 Diag(KWLoc, diag::err_template_spec_needs_header)
3267 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003268 isExplicitSpecialization = true;
3269 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003270
Douglas Gregor67a65642009-02-17 23:15:12 +00003271 // Check that the specialization uses the same tag kind as the
3272 // original template.
3273 TagDecl::TagKind Kind;
3274 switch (TagSpec) {
3275 default: assert(0 && "Unknown tag type!");
3276 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3277 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3278 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3279 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003280 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003281 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003282 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003283 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003284 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003285 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003286 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003287 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003288 diag::note_previous_use);
3289 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3290 }
3291
Douglas Gregorc40290e2009-03-09 23:48:35 +00003292 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003293 TemplateArgumentListInfo TemplateArgs;
3294 TemplateArgs.setLAngleLoc(LAngleLoc);
3295 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003296 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003297
Douglas Gregor67a65642009-02-17 23:15:12 +00003298 // Check that the template argument list is well-formed for this
3299 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003300 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3301 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003302 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3303 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003304 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003305
Mike Stump11289f42009-09-09 15:08:12 +00003306 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003307 ClassTemplate->getTemplateParameters()->size()) &&
3308 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003309
Douglas Gregor2373c592009-05-31 09:31:02 +00003310 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003311 // corresponds to these arguments.
3312 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003313 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003314 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003315 if (CheckClassTemplatePartialSpecializationArgs(
3316 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003317 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003318 return true;
3319
Douglas Gregor09a30232009-06-12 22:08:06 +00003320 if (MirrorsPrimaryTemplate) {
3321 // C++ [temp.class.spec]p9b3:
3322 //
Mike Stump11289f42009-09-09 15:08:12 +00003323 // -- The argument list of the specialization shall not be identical
3324 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003325 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003326 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003327 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003328 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003329 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003330 ClassTemplate->getIdentifier(),
3331 TemplateNameLoc,
3332 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003333 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003334 AS_none);
3335 }
3336
Douglas Gregor2208a292009-09-26 20:57:03 +00003337 // FIXME: Diagnose friend partial specializations
3338
Douglas Gregor2373c592009-05-31 09:31:02 +00003339 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00003340 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003341 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003342 Converted.flatSize(),
3343 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003344 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003345 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003346 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003347 Converted.flatSize(),
3348 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003349 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003350 ClassTemplateSpecializationDecl *PrevDecl = 0;
3351
3352 if (isPartialSpecialization)
3353 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003354 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003355 InsertPos);
3356 else
3357 PrevDecl
3358 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003359
3360 ClassTemplateSpecializationDecl *Specialization = 0;
3361
Douglas Gregorf47b9112009-02-25 22:02:03 +00003362 // Check whether we can declare a class template specialization in
3363 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003364 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003365 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003366 TemplateNameLoc,
3367 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003368 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003369
Douglas Gregor15301382009-07-30 17:40:51 +00003370 // The canonical type
3371 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003372 if (PrevDecl &&
3373 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3374 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003375 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003376 // arguments was referenced but not declared, or we're only
3377 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003378 // declaration node as our own, updating its source location to
3379 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003380 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003381 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003382 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003383 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003384 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003385 // Build the canonical type that describes the converted template
3386 // arguments of the class template partial specialization.
3387 CanonType = Context.getTemplateSpecializationType(
3388 TemplateName(ClassTemplate),
3389 Converted.getFlatArguments(),
3390 Converted.flatSize());
3391
Douglas Gregor2373c592009-05-31 09:31:02 +00003392 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003393 ClassTemplatePartialSpecializationDecl *PrevPartial
3394 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003395 ClassTemplatePartialSpecializationDecl *Partial
3396 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003397 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003398 TemplateNameLoc,
3399 TemplateParams,
3400 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003401 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003402 TemplateArgs,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003403 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003404
3405 if (PrevPartial) {
3406 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3407 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3408 } else {
3409 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3410 }
3411 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003412
Douglas Gregor21610382009-10-29 00:04:11 +00003413 // If we are providing an explicit specialization of a member class
3414 // template specialization, make a note of that.
3415 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3416 PrevPartial->setMemberSpecialization();
3417
Douglas Gregor91772d12009-06-13 00:26:55 +00003418 // Check that all of the template parameters of the class template
3419 // partial specialization are deducible from the template
3420 // arguments. If not, this class template partial specialization
3421 // will never be used.
3422 llvm::SmallVector<bool, 8> DeducibleParams;
3423 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003424 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003425 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003426 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003427 unsigned NumNonDeducible = 0;
3428 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3429 if (!DeducibleParams[I])
3430 ++NumNonDeducible;
3431
3432 if (NumNonDeducible) {
3433 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3434 << (NumNonDeducible > 1)
3435 << SourceRange(TemplateNameLoc, RAngleLoc);
3436 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3437 if (!DeducibleParams[I]) {
3438 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3439 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003440 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003441 diag::note_partial_spec_unused_parameter)
3442 << Param->getDeclName();
3443 else
Mike Stump11289f42009-09-09 15:08:12 +00003444 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003445 diag::note_partial_spec_unused_parameter)
3446 << std::string("<anonymous>");
3447 }
3448 }
3449 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003450 } else {
3451 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003452 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003453 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003454 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003455 ClassTemplate->getDeclContext(),
3456 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003457 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003458 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003459 PrevDecl);
3460
3461 if (PrevDecl) {
3462 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3463 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3464 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003465 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003466 InsertPos);
3467 }
Douglas Gregor15301382009-07-30 17:40:51 +00003468
3469 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003470 }
3471
Douglas Gregor06db9f52009-10-12 20:18:28 +00003472 // C++ [temp.expl.spec]p6:
3473 // If a template, a member template or the member of a class template is
3474 // explicitly specialized then that specialization shall be declared
3475 // before the first use of that specialization that would cause an implicit
3476 // instantiation to take place, in every translation unit in which such a
3477 // use occurs; no diagnostic is required.
3478 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3479 SourceRange Range(TemplateNameLoc, RAngleLoc);
3480 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3481 << Context.getTypeDeclType(Specialization) << Range;
3482
3483 Diag(PrevDecl->getPointOfInstantiation(),
3484 diag::note_instantiation_required_here)
3485 << (PrevDecl->getTemplateSpecializationKind()
3486 != TSK_ImplicitInstantiation);
3487 return true;
3488 }
3489
Douglas Gregor2208a292009-09-26 20:57:03 +00003490 // If this is not a friend, note that this is an explicit specialization.
3491 if (TUK != TUK_Friend)
3492 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003493
3494 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003495 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003496 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003497 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003498 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003499 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003500 Diag(Def->getLocation(), diag::note_previous_definition);
3501 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003502 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003503 }
3504 }
3505
Douglas Gregord56a91e2009-02-26 22:19:44 +00003506 // Build the fully-sugared type for this class template
3507 // specialization as the user wrote in the specialization
3508 // itself. This means that we'll pretty-print the type retrieved
3509 // from the specialization's declaration the way that the user
3510 // actually wrote the specialization, rather than formatting the
3511 // name based on the "canonical" representation used to store the
3512 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003513 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00003514 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003515 if (TUK != TUK_Friend)
3516 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003517 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003518
Douglas Gregor1e249f82009-02-25 22:18:32 +00003519 // C++ [temp.expl.spec]p9:
3520 // A template explicit specialization is in the scope of the
3521 // namespace in which the template was defined.
3522 //
3523 // We actually implement this paragraph where we set the semantic
3524 // context (in the creation of the ClassTemplateSpecializationDecl),
3525 // but we also maintain the lexical context where the actual
3526 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003527 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003528
Douglas Gregor67a65642009-02-17 23:15:12 +00003529 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003530 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003531 Specialization->startDefinition();
3532
Douglas Gregor2208a292009-09-26 20:57:03 +00003533 if (TUK == TUK_Friend) {
3534 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3535 TemplateNameLoc,
3536 WrittenTy.getTypePtr(),
3537 /*FIXME:*/KWLoc);
3538 Friend->setAccess(AS_public);
3539 CurContext->addDecl(Friend);
3540 } else {
3541 // Add the specialization into its lexical context, so that it can
3542 // be seen when iterating through the list of declarations in that
3543 // context. However, specializations are not found by name lookup.
3544 CurContext->addDecl(Specialization);
3545 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003546 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003547}
Douglas Gregor333489b2009-03-27 23:10:48 +00003548
Mike Stump11289f42009-09-09 15:08:12 +00003549Sema::DeclPtrTy
3550Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003551 MultiTemplateParamsArg TemplateParameterLists,
3552 Declarator &D) {
3553 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3554}
3555
Mike Stump11289f42009-09-09 15:08:12 +00003556Sema::DeclPtrTy
3557Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003558 MultiTemplateParamsArg TemplateParameterLists,
3559 Declarator &D) {
3560 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3561 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3562 "Not a function declarator!");
3563 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003564
Douglas Gregor17a7c122009-06-24 00:54:41 +00003565 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003566 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003567 }
Mike Stump11289f42009-09-09 15:08:12 +00003568
Douglas Gregor17a7c122009-06-24 00:54:41 +00003569 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003570
3571 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003572 move(TemplateParameterLists),
3573 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003574 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003575 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003576 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003577 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003578 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3579 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003580 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003581}
3582
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003583/// \brief Diagnose cases where we have an explicit template specialization
3584/// before/after an explicit template instantiation, producing diagnostics
3585/// for those cases where they are required and determining whether the
3586/// new specialization/instantiation will have any effect.
3587///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003588/// \param NewLoc the location of the new explicit specialization or
3589/// instantiation.
3590///
3591/// \param NewTSK the kind of the new explicit specialization or instantiation.
3592///
3593/// \param PrevDecl the previous declaration of the entity.
3594///
3595/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3596///
3597/// \param PrevPointOfInstantiation if valid, indicates where the previus
3598/// declaration was instantiated (either implicitly or explicitly).
3599///
3600/// \param SuppressNew will be set to true to indicate that the new
3601/// specialization or instantiation has no effect and should be ignored.
3602///
3603/// \returns true if there was an error that should prevent the introduction of
3604/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003605bool
3606Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3607 TemplateSpecializationKind NewTSK,
3608 NamedDecl *PrevDecl,
3609 TemplateSpecializationKind PrevTSK,
3610 SourceLocation PrevPointOfInstantiation,
3611 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003612 SuppressNew = false;
3613
3614 switch (NewTSK) {
3615 case TSK_Undeclared:
3616 case TSK_ImplicitInstantiation:
3617 assert(false && "Don't check implicit instantiations here");
3618 return false;
3619
3620 case TSK_ExplicitSpecialization:
3621 switch (PrevTSK) {
3622 case TSK_Undeclared:
3623 case TSK_ExplicitSpecialization:
3624 // Okay, we're just specializing something that is either already
3625 // explicitly specialized or has merely been mentioned without any
3626 // instantiation.
3627 return false;
3628
3629 case TSK_ImplicitInstantiation:
3630 if (PrevPointOfInstantiation.isInvalid()) {
3631 // The declaration itself has not actually been instantiated, so it is
3632 // still okay to specialize it.
3633 return false;
3634 }
3635 // Fall through
3636
3637 case TSK_ExplicitInstantiationDeclaration:
3638 case TSK_ExplicitInstantiationDefinition:
3639 assert((PrevTSK == TSK_ImplicitInstantiation ||
3640 PrevPointOfInstantiation.isValid()) &&
3641 "Explicit instantiation without point of instantiation?");
3642
3643 // C++ [temp.expl.spec]p6:
3644 // If a template, a member template or the member of a class template
3645 // is explicitly specialized then that specialization shall be declared
3646 // before the first use of that specialization that would cause an
3647 // implicit instantiation to take place, in every translation unit in
3648 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003649 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003650 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003651 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003652 << (PrevTSK != TSK_ImplicitInstantiation);
3653
3654 return true;
3655 }
3656 break;
3657
3658 case TSK_ExplicitInstantiationDeclaration:
3659 switch (PrevTSK) {
3660 case TSK_ExplicitInstantiationDeclaration:
3661 // This explicit instantiation declaration is redundant (that's okay).
3662 SuppressNew = true;
3663 return false;
3664
3665 case TSK_Undeclared:
3666 case TSK_ImplicitInstantiation:
3667 // We're explicitly instantiating something that may have already been
3668 // implicitly instantiated; that's fine.
3669 return false;
3670
3671 case TSK_ExplicitSpecialization:
3672 // C++0x [temp.explicit]p4:
3673 // For a given set of template parameters, if an explicit instantiation
3674 // of a template appears after a declaration of an explicit
3675 // specialization for that template, the explicit instantiation has no
3676 // effect.
3677 return false;
3678
3679 case TSK_ExplicitInstantiationDefinition:
3680 // C++0x [temp.explicit]p10:
3681 // If an entity is the subject of both an explicit instantiation
3682 // declaration and an explicit instantiation definition in the same
3683 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003684 Diag(NewLoc,
3685 diag::err_explicit_instantiation_declaration_after_definition);
3686 Diag(PrevPointOfInstantiation,
3687 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003688 assert(PrevPointOfInstantiation.isValid() &&
3689 "Explicit instantiation without point of instantiation?");
3690 SuppressNew = true;
3691 return false;
3692 }
3693 break;
3694
3695 case TSK_ExplicitInstantiationDefinition:
3696 switch (PrevTSK) {
3697 case TSK_Undeclared:
3698 case TSK_ImplicitInstantiation:
3699 // We're explicitly instantiating something that may have already been
3700 // implicitly instantiated; that's fine.
3701 return false;
3702
3703 case TSK_ExplicitSpecialization:
3704 // C++ DR 259, C++0x [temp.explicit]p4:
3705 // For a given set of template parameters, if an explicit
3706 // instantiation of a template appears after a declaration of
3707 // an explicit specialization for that template, the explicit
3708 // instantiation has no effect.
3709 //
3710 // In C++98/03 mode, we only give an extension warning here, because it
3711 // is not not harmful to try to explicitly instantiate something that
3712 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003713 if (!getLangOptions().CPlusPlus0x) {
3714 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003715 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003716 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003717 diag::note_previous_template_specialization);
3718 }
3719 SuppressNew = true;
3720 return false;
3721
3722 case TSK_ExplicitInstantiationDeclaration:
3723 // We're explicity instantiating a definition for something for which we
3724 // were previously asked to suppress instantiations. That's fine.
3725 return false;
3726
3727 case TSK_ExplicitInstantiationDefinition:
3728 // C++0x [temp.spec]p5:
3729 // For a given template and a given set of template-arguments,
3730 // - an explicit instantiation definition shall appear at most once
3731 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003732 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003733 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003734 Diag(PrevPointOfInstantiation,
3735 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003736 SuppressNew = true;
3737 return false;
3738 }
3739 break;
3740 }
3741
3742 assert(false && "Missing specialization/instantiation case?");
3743
3744 return false;
3745}
3746
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003747/// \brief Perform semantic analysis for the given function template
3748/// specialization.
3749///
3750/// This routine performs all of the semantic analysis required for an
3751/// explicit function template specialization. On successful completion,
3752/// the function declaration \p FD will become a function template
3753/// specialization.
3754///
3755/// \param FD the function declaration, which will be updated to become a
3756/// function template specialization.
3757///
3758/// \param HasExplicitTemplateArgs whether any template arguments were
3759/// explicitly provided.
3760///
3761/// \param LAngleLoc the location of the left angle bracket ('<'), if
3762/// template arguments were explicitly provided.
3763///
3764/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3765/// if any.
3766///
3767/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3768/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3769/// true as in, e.g., \c void sort<>(char*, char*);
3770///
3771/// \param RAngleLoc the location of the right angle bracket ('>'), if
3772/// template arguments were explicitly provided.
3773///
3774/// \param PrevDecl the set of declarations that
3775bool
3776Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00003777 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00003778 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003779 // The set of function template specializations that could match this
3780 // explicit function template specialization.
3781 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3782 CandidateSet Candidates;
3783
3784 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00003785 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3786 I != E; ++I) {
3787 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3788 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003789 // Only consider templates found within the same semantic lookup scope as
3790 // FD.
3791 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3792 continue;
3793
3794 // C++ [temp.expl.spec]p11:
3795 // A trailing template-argument can be left unspecified in the
3796 // template-id naming an explicit function template specialization
3797 // provided it can be deduced from the function argument type.
3798 // Perform template argument deduction to determine whether we may be
3799 // specializing this template.
3800 // FIXME: It is somewhat wasteful to build
3801 TemplateDeductionInfo Info(Context);
3802 FunctionDecl *Specialization = 0;
3803 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00003804 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003805 FD->getType(),
3806 Specialization,
3807 Info)) {
3808 // FIXME: Template argument deduction failed; record why it failed, so
3809 // that we can provide nifty diagnostics.
3810 (void)TDK;
3811 continue;
3812 }
3813
3814 // Record this candidate.
3815 Candidates.push_back(Specialization);
3816 }
3817 }
3818
Douglas Gregor5de279c2009-09-26 03:41:46 +00003819 // Find the most specialized function template.
3820 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3821 Candidates.size(),
3822 TPOC_Other,
3823 FD->getLocation(),
3824 PartialDiagnostic(diag::err_function_template_spec_no_match)
3825 << FD->getDeclName(),
3826 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00003827 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor5de279c2009-09-26 03:41:46 +00003828 PartialDiagnostic(diag::note_function_template_spec_matched));
3829 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003830 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003831
3832 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003833 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003834
Douglas Gregor54888652009-10-07 00:13:32 +00003835 // Check the scope of this explicit specialization.
3836 if (CheckTemplateSpecializationScope(*this,
3837 Specialization->getPrimaryTemplate(),
3838 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003839 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003840 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003841
3842 // C++ [temp.expl.spec]p6:
3843 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003844 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003845 // before the first use of that specialization that would cause an implicit
3846 // instantiation to take place, in every translation unit in which such a
3847 // use occurs; no diagnostic is required.
3848 FunctionTemplateSpecializationInfo *SpecInfo
3849 = Specialization->getTemplateSpecializationInfo();
3850 assert(SpecInfo && "Function template specialization info missing?");
3851 if (SpecInfo->getPointOfInstantiation().isValid()) {
3852 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3853 << FD;
3854 Diag(SpecInfo->getPointOfInstantiation(),
3855 diag::note_instantiation_required_here)
3856 << (Specialization->getTemplateSpecializationKind()
3857 != TSK_ImplicitInstantiation);
3858 return true;
3859 }
Douglas Gregor54888652009-10-07 00:13:32 +00003860
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003861 // Mark the prior declaration as an explicit specialization, so that later
3862 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003863 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003864
3865 // Turn the given function declaration into a function template
3866 // specialization, with the template arguments from the previous
3867 // specialization.
3868 FD->setFunctionTemplateSpecialization(Context,
3869 Specialization->getPrimaryTemplate(),
3870 new (Context) TemplateArgumentList(
3871 *Specialization->getTemplateSpecializationArgs()),
3872 /*InsertPos=*/0,
3873 TSK_ExplicitSpecialization);
3874
3875 // The "previous declaration" for this function template specialization is
3876 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00003877 Previous.clear();
3878 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003879 return false;
3880}
3881
Douglas Gregor86d142a2009-10-08 07:24:58 +00003882/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003883/// specialization.
3884///
3885/// This routine performs all of the semantic analysis required for an
3886/// explicit member function specialization. On successful completion,
3887/// the function declaration \p FD will become a member function
3888/// specialization.
3889///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003890/// \param Member the member declaration, which will be updated to become a
3891/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003892///
John McCall1f82f242009-11-18 22:49:29 +00003893/// \param Previous the set of declarations, one of which may be specialized
3894/// by this function specialization; the set will be modified to contain the
3895/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003896bool
John McCall1f82f242009-11-18 22:49:29 +00003897Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003898 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3899
3900 // Try to find the member we are instantiating.
3901 NamedDecl *Instantiation = 0;
3902 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003903 MemberSpecializationInfo *MSInfo = 0;
3904
John McCall1f82f242009-11-18 22:49:29 +00003905 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003906 // Nowhere to look anyway.
3907 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003908 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3909 I != E; ++I) {
3910 NamedDecl *D = (*I)->getUnderlyingDecl();
3911 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003912 if (Context.hasSameType(Function->getType(), Method->getType())) {
3913 Instantiation = Method;
3914 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003915 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003916 break;
3917 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003918 }
3919 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003920 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003921 VarDecl *PrevVar;
3922 if (Previous.isSingleResult() &&
3923 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00003924 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00003925 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003926 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003927 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003928 }
3929 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003930 CXXRecordDecl *PrevRecord;
3931 if (Previous.isSingleResult() &&
3932 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3933 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003934 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003935 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003936 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003937 }
3938
3939 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003940 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003941 // specializations are always out-of-line, the caller will complain about
3942 // this mismatch later.
3943 return false;
3944 }
3945
Douglas Gregor86d142a2009-10-08 07:24:58 +00003946 // Make sure that this is a specialization of a member.
3947 if (!InstantiatedFrom) {
3948 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3949 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003950 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3951 return true;
3952 }
3953
Douglas Gregor06db9f52009-10-12 20:18:28 +00003954 // C++ [temp.expl.spec]p6:
3955 // If a template, a member template or the member of a class template is
3956 // explicitly specialized then that spe- cialization shall be declared
3957 // before the first use of that specialization that would cause an implicit
3958 // instantiation to take place, in every translation unit in which such a
3959 // use occurs; no diagnostic is required.
3960 assert(MSInfo && "Member specialization info missing?");
3961 if (MSInfo->getPointOfInstantiation().isValid()) {
3962 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3963 << Member;
3964 Diag(MSInfo->getPointOfInstantiation(),
3965 diag::note_instantiation_required_here)
3966 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3967 return true;
3968 }
3969
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003970 // Check the scope of this explicit specialization.
3971 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003972 InstantiatedFrom,
3973 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003974 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003975 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003976
Douglas Gregor86d142a2009-10-08 07:24:58 +00003977 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003978 // the original declaration to note that it is an explicit specialization
3979 // (if it was previously an implicit instantiation). This latter step
3980 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003981 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003982 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3983 if (InstantiationFunction->getTemplateSpecializationKind() ==
3984 TSK_ImplicitInstantiation) {
3985 InstantiationFunction->setTemplateSpecializationKind(
3986 TSK_ExplicitSpecialization);
3987 InstantiationFunction->setLocation(Member->getLocation());
3988 }
3989
Douglas Gregor86d142a2009-10-08 07:24:58 +00003990 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3991 cast<CXXMethodDecl>(InstantiatedFrom),
3992 TSK_ExplicitSpecialization);
3993 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003994 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3995 if (InstantiationVar->getTemplateSpecializationKind() ==
3996 TSK_ImplicitInstantiation) {
3997 InstantiationVar->setTemplateSpecializationKind(
3998 TSK_ExplicitSpecialization);
3999 InstantiationVar->setLocation(Member->getLocation());
4000 }
4001
Douglas Gregor86d142a2009-10-08 07:24:58 +00004002 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4003 cast<VarDecl>(InstantiatedFrom),
4004 TSK_ExplicitSpecialization);
4005 } else {
4006 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004007 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4008 if (InstantiationClass->getTemplateSpecializationKind() ==
4009 TSK_ImplicitInstantiation) {
4010 InstantiationClass->setTemplateSpecializationKind(
4011 TSK_ExplicitSpecialization);
4012 InstantiationClass->setLocation(Member->getLocation());
4013 }
4014
Douglas Gregor86d142a2009-10-08 07:24:58 +00004015 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004016 cast<CXXRecordDecl>(InstantiatedFrom),
4017 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004018 }
4019
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004020 // Save the caller the trouble of having to figure out which declaration
4021 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004022 Previous.clear();
4023 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004024 return false;
4025}
4026
Douglas Gregore47f5a72009-10-14 23:41:34 +00004027/// \brief Check the scope of an explicit instantiation.
4028static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4029 SourceLocation InstLoc,
4030 bool WasQualifiedName) {
4031 DeclContext *ExpectedContext
4032 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4033 DeclContext *CurContext = S.CurContext->getLookupContext();
4034
4035 // C++0x [temp.explicit]p2:
4036 // An explicit instantiation shall appear in an enclosing namespace of its
4037 // template.
4038 //
4039 // This is DR275, which we do not retroactively apply to C++98/03.
4040 if (S.getLangOptions().CPlusPlus0x &&
4041 !CurContext->Encloses(ExpectedContext)) {
4042 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4043 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4044 << D << NS;
4045 else
4046 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4047 << D;
4048 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4049 return;
4050 }
4051
4052 // C++0x [temp.explicit]p2:
4053 // If the name declared in the explicit instantiation is an unqualified
4054 // name, the explicit instantiation shall appear in the namespace where
4055 // its template is declared or, if that namespace is inline (7.3.1), any
4056 // namespace from its enclosing namespace set.
4057 if (WasQualifiedName)
4058 return;
4059
4060 if (CurContext->Equals(ExpectedContext))
4061 return;
4062
4063 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4064 << D << ExpectedContext;
4065 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4066}
4067
4068/// \brief Determine whether the given scope specifier has a template-id in it.
4069static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4070 if (!SS.isSet())
4071 return false;
4072
4073 // C++0x [temp.explicit]p2:
4074 // If the explicit instantiation is for a member function, a member class
4075 // or a static data member of a class template specialization, the name of
4076 // the class template specialization in the qualified-id for the member
4077 // name shall be a simple-template-id.
4078 //
4079 // C++98 has the same restriction, just worded differently.
4080 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4081 NNS; NNS = NNS->getPrefix())
4082 if (Type *T = NNS->getAsType())
4083 if (isa<TemplateSpecializationType>(T))
4084 return true;
4085
4086 return false;
4087}
4088
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004089// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004090// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004091Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004092Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004093 SourceLocation ExternLoc,
4094 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004095 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004096 SourceLocation KWLoc,
4097 const CXXScopeSpec &SS,
4098 TemplateTy TemplateD,
4099 SourceLocation TemplateNameLoc,
4100 SourceLocation LAngleLoc,
4101 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004102 SourceLocation RAngleLoc,
4103 AttributeList *Attr) {
4104 // Find the class template we're specializing
4105 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004106 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004107 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4108
4109 // Check that the specialization uses the same tag kind as the
4110 // original template.
4111 TagDecl::TagKind Kind;
4112 switch (TagSpec) {
4113 default: assert(0 && "Unknown tag type!");
4114 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4115 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4116 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4117 }
Douglas Gregord9034f02009-05-14 16:41:31 +00004118 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004119 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004120 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004121 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004122 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00004123 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004124 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004125 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004126 diag::note_previous_use);
4127 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4128 }
4129
Douglas Gregore47f5a72009-10-14 23:41:34 +00004130 // C++0x [temp.explicit]p2:
4131 // There are two forms of explicit instantiation: an explicit instantiation
4132 // definition and an explicit instantiation declaration. An explicit
4133 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004134 TemplateSpecializationKind TSK
4135 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4136 : TSK_ExplicitInstantiationDeclaration;
4137
Douglas Gregora1f49972009-05-13 00:25:59 +00004138 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004139 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004140 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004141
4142 // Check that the template argument list is well-formed for this
4143 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004144 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4145 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004146 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4147 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004148 return true;
4149
Mike Stump11289f42009-09-09 15:08:12 +00004150 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004151 ClassTemplate->getTemplateParameters()->size()) &&
4152 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004153
Douglas Gregora1f49972009-05-13 00:25:59 +00004154 // Find the class template specialization declaration that
4155 // corresponds to these arguments.
4156 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004157 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004158 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004159 Converted.flatSize(),
4160 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004161 void *InsertPos = 0;
4162 ClassTemplateSpecializationDecl *PrevDecl
4163 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4164
Douglas Gregor54888652009-10-07 00:13:32 +00004165 // C++0x [temp.explicit]p2:
4166 // [...] An explicit instantiation shall appear in an enclosing
4167 // namespace of its template. [...]
4168 //
4169 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004170 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4171 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004172
Douglas Gregora1f49972009-05-13 00:25:59 +00004173 ClassTemplateSpecializationDecl *Specialization = 0;
4174
Douglas Gregor0681a352009-11-25 06:01:46 +00004175 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004176 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004177 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004178 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004179 PrevDecl,
4180 PrevDecl->getSpecializationKind(),
4181 PrevDecl->getPointOfInstantiation(),
4182 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004183 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004184
Douglas Gregor12e49d32009-10-15 22:53:21 +00004185 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004186 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004187
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004188 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4189 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4190 // Since the only prior class template specialization with these
4191 // arguments was referenced but not declared, reuse that
4192 // declaration node as our own, updating its source location to
4193 // reflect our new declaration.
4194 Specialization = PrevDecl;
4195 Specialization->setLocation(TemplateNameLoc);
4196 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004197 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004198 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004199 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004200
4201 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004202 // Create a new class template specialization declaration node for
4203 // this explicit specialization.
4204 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00004205 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00004206 ClassTemplate->getDeclContext(),
4207 TemplateNameLoc,
4208 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004209 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004210
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004211 if (PrevDecl) {
4212 // Remove the previous declaration from the folding set, since we want
4213 // to introduce a new declaration.
4214 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4215 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4216 }
4217
4218 // Insert the new specialization.
4219 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004220 }
4221
4222 // Build the fully-sugared type for this explicit instantiation as
4223 // the user wrote in the explicit instantiation itself. This means
4224 // that we'll pretty-print the type retrieved from the
4225 // specialization's declaration the way that the user actually wrote
4226 // the explicit instantiation, rather than formatting the name based
4227 // on the "canonical" representation used to store the template
4228 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004229 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00004230 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004231 Context.getTypeDeclType(Specialization));
4232 Specialization->setTypeAsWritten(WrittenTy);
4233 TemplateArgsIn.release();
4234
Douglas Gregor0681a352009-11-25 06:01:46 +00004235 if (!ReusedDecl) {
4236 // Add the explicit instantiation into its lexical context. However,
4237 // since explicit instantiations are never found by name lookup, we
4238 // just put it into the declaration context directly.
4239 Specialization->setLexicalDeclContext(CurContext);
4240 CurContext->addDecl(Specialization);
4241 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004242
4243 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004244 // A definition of a class template or class member template
4245 // shall be in scope at the point of the explicit instantiation of
4246 // the class template or class member template.
4247 //
4248 // This check comes when we actually try to perform the
4249 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004250 ClassTemplateSpecializationDecl *Def
4251 = cast_or_null<ClassTemplateSpecializationDecl>(
4252 Specialization->getDefinition(Context));
4253 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004254 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004255
4256 // Instantiate the members of this class template specialization.
4257 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4258 Specialization->getDefinition(Context));
4259 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00004260 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004261
4262 return DeclPtrTy::make(Specialization);
4263}
4264
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004265// Explicit instantiation of a member class of a class template.
4266Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004267Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004268 SourceLocation ExternLoc,
4269 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004270 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004271 SourceLocation KWLoc,
4272 const CXXScopeSpec &SS,
4273 IdentifierInfo *Name,
4274 SourceLocation NameLoc,
4275 AttributeList *Attr) {
4276
Douglas Gregord6ab8742009-05-28 23:31:59 +00004277 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004278 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004279 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004280 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004281 MultiTemplateParamsArg(*this, 0, 0),
4282 Owned, IsDependent);
4283 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4284
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004285 if (!TagD)
4286 return true;
4287
4288 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4289 if (Tag->isEnum()) {
4290 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4291 << Context.getTypeDeclType(Tag);
4292 return true;
4293 }
4294
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004295 if (Tag->isInvalidDecl())
4296 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004297
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004298 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4299 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4300 if (!Pattern) {
4301 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4302 << Context.getTypeDeclType(Record);
4303 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4304 return true;
4305 }
4306
Douglas Gregore47f5a72009-10-14 23:41:34 +00004307 // C++0x [temp.explicit]p2:
4308 // If the explicit instantiation is for a class or member class, the
4309 // elaborated-type-specifier in the declaration shall include a
4310 // simple-template-id.
4311 //
4312 // C++98 has the same restriction, just worded differently.
4313 if (!ScopeSpecifierHasTemplateId(SS))
4314 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4315 << Record << SS.getRange();
4316
4317 // C++0x [temp.explicit]p2:
4318 // There are two forms of explicit instantiation: an explicit instantiation
4319 // definition and an explicit instantiation declaration. An explicit
4320 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004321 TemplateSpecializationKind TSK
4322 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4323 : TSK_ExplicitInstantiationDeclaration;
4324
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004325 // C++0x [temp.explicit]p2:
4326 // [...] An explicit instantiation shall appear in an enclosing
4327 // namespace of its template. [...]
4328 //
4329 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004330 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004331
4332 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004333 CXXRecordDecl *PrevDecl
4334 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4335 if (!PrevDecl && Record->getDefinition(Context))
4336 PrevDecl = Record;
4337 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004338 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4339 bool SuppressNew = false;
4340 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004341 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004342 PrevDecl,
4343 MSInfo->getTemplateSpecializationKind(),
4344 MSInfo->getPointOfInstantiation(),
4345 SuppressNew))
4346 return true;
4347 if (SuppressNew)
4348 return TagD;
4349 }
4350
Douglas Gregor12e49d32009-10-15 22:53:21 +00004351 CXXRecordDecl *RecordDef
4352 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4353 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004354 // C++ [temp.explicit]p3:
4355 // A definition of a member class of a class template shall be in scope
4356 // at the point of an explicit instantiation of the member class.
4357 CXXRecordDecl *Def
4358 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4359 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004360 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4361 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004362 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4363 << Pattern;
4364 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004365 } else {
4366 if (InstantiateClass(NameLoc, Record, Def,
4367 getTemplateInstantiationArgs(Record),
4368 TSK))
4369 return true;
4370
4371 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4372 if (!RecordDef)
4373 return true;
4374 }
4375 }
4376
4377 // Instantiate all of the members of the class.
4378 InstantiateClassMembers(NameLoc, RecordDef,
4379 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004380
Mike Stump87c57ac2009-05-16 07:39:55 +00004381 // FIXME: We don't have any representation for explicit instantiations of
4382 // member classes. Such a representation is not needed for compilation, but it
4383 // should be available for clients that want to see all of the declarations in
4384 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004385 return TagD;
4386}
4387
Douglas Gregor450f00842009-09-25 18:43:00 +00004388Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4389 SourceLocation ExternLoc,
4390 SourceLocation TemplateLoc,
4391 Declarator &D) {
4392 // Explicit instantiations always require a name.
4393 DeclarationName Name = GetNameForDeclarator(D);
4394 if (!Name) {
4395 if (!D.isInvalidType())
4396 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4397 diag::err_explicit_instantiation_requires_name)
4398 << D.getDeclSpec().getSourceRange()
4399 << D.getSourceRange();
4400
4401 return true;
4402 }
4403
4404 // The scope passed in may not be a decl scope. Zip up the scope tree until
4405 // we find one that is.
4406 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4407 (S->getFlags() & Scope::TemplateParamScope) != 0)
4408 S = S->getParent();
4409
4410 // Determine the type of the declaration.
4411 QualType R = GetTypeForDeclarator(D, S, 0);
4412 if (R.isNull())
4413 return true;
4414
4415 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4416 // Cannot explicitly instantiate a typedef.
4417 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4418 << Name;
4419 return true;
4420 }
4421
Douglas Gregor3c74d412009-10-14 20:14:33 +00004422 // C++0x [temp.explicit]p1:
4423 // [...] An explicit instantiation of a function template shall not use the
4424 // inline or constexpr specifiers.
4425 // Presumably, this also applies to member functions of class templates as
4426 // well.
4427 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4428 Diag(D.getDeclSpec().getInlineSpecLoc(),
4429 diag::err_explicit_instantiation_inline)
Chris Lattner3c7b86f2009-12-06 17:36:05 +00004430 <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004431
4432 // FIXME: check for constexpr specifier.
4433
Douglas Gregore47f5a72009-10-14 23:41:34 +00004434 // C++0x [temp.explicit]p2:
4435 // There are two forms of explicit instantiation: an explicit instantiation
4436 // definition and an explicit instantiation declaration. An explicit
4437 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004438 TemplateSpecializationKind TSK
4439 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4440 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004441
John McCall27b18f82009-11-17 02:14:36 +00004442 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4443 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004444
4445 if (!R->isFunctionType()) {
4446 // C++ [temp.explicit]p1:
4447 // A [...] static data member of a class template can be explicitly
4448 // instantiated from the member definition associated with its class
4449 // template.
John McCall27b18f82009-11-17 02:14:36 +00004450 if (Previous.isAmbiguous())
4451 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004452
John McCall67c00872009-12-02 08:25:40 +00004453 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00004454 if (!Prev || !Prev->isStaticDataMember()) {
4455 // We expect to see a data data member here.
4456 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4457 << Name;
4458 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4459 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004460 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004461 return true;
4462 }
4463
4464 if (!Prev->getInstantiatedFromStaticDataMember()) {
4465 // FIXME: Check for explicit specialization?
4466 Diag(D.getIdentifierLoc(),
4467 diag::err_explicit_instantiation_data_member_not_instantiated)
4468 << Prev;
4469 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4470 // FIXME: Can we provide a note showing where this was declared?
4471 return true;
4472 }
4473
Douglas Gregore47f5a72009-10-14 23:41:34 +00004474 // C++0x [temp.explicit]p2:
4475 // If the explicit instantiation is for a member function, a member class
4476 // or a static data member of a class template specialization, the name of
4477 // the class template specialization in the qualified-id for the member
4478 // name shall be a simple-template-id.
4479 //
4480 // C++98 has the same restriction, just worded differently.
4481 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4482 Diag(D.getIdentifierLoc(),
4483 diag::err_explicit_instantiation_without_qualified_id)
4484 << Prev << D.getCXXScopeSpec().getRange();
4485
4486 // Check the scope of this explicit instantiation.
4487 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4488
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004489 // Verify that it is okay to explicitly instantiate here.
4490 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4491 assert(MSInfo && "Missing static data member specialization info?");
4492 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004493 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004494 MSInfo->getTemplateSpecializationKind(),
4495 MSInfo->getPointOfInstantiation(),
4496 SuppressNew))
4497 return true;
4498 if (SuppressNew)
4499 return DeclPtrTy();
4500
Douglas Gregor450f00842009-09-25 18:43:00 +00004501 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004502 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004503 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004504 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4505 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004506
4507 // FIXME: Create an ExplicitInstantiation node?
4508 return DeclPtrTy();
4509 }
4510
Douglas Gregor0e876e02009-09-25 23:53:26 +00004511 // If the declarator is a template-id, translate the parser's template
4512 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004513 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004514 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004515 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4516 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004517 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4518 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004519 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4520 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004521 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004522 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004523 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004524 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004525 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004526
Douglas Gregor450f00842009-09-25 18:43:00 +00004527 // C++ [temp.explicit]p1:
4528 // A [...] function [...] can be explicitly instantiated from its template.
4529 // A member function [...] of a class template can be explicitly
4530 // instantiated from the member definition associated with its class
4531 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004532 llvm::SmallVector<FunctionDecl *, 8> Matches;
4533 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4534 P != PEnd; ++P) {
4535 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004536 if (!HasExplicitTemplateArgs) {
4537 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4538 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4539 Matches.clear();
4540 Matches.push_back(Method);
4541 break;
4542 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004543 }
4544 }
4545
4546 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4547 if (!FunTmpl)
4548 continue;
4549
4550 TemplateDeductionInfo Info(Context);
4551 FunctionDecl *Specialization = 0;
4552 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004553 = DeduceTemplateArguments(FunTmpl,
4554 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004555 R, Specialization, Info)) {
4556 // FIXME: Keep track of almost-matches?
4557 (void)TDK;
4558 continue;
4559 }
4560
4561 Matches.push_back(Specialization);
4562 }
4563
4564 // Find the most specialized function template specialization.
4565 FunctionDecl *Specialization
4566 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4567 D.getIdentifierLoc(),
4568 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4569 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4570 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4571
4572 if (!Specialization)
4573 return true;
4574
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004575 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004576 Diag(D.getIdentifierLoc(),
4577 diag::err_explicit_instantiation_member_function_not_instantiated)
4578 << Specialization
4579 << (Specialization->getTemplateSpecializationKind() ==
4580 TSK_ExplicitSpecialization);
4581 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4582 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004583 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004584
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004585 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004586 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4587 PrevDecl = Specialization;
4588
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004589 if (PrevDecl) {
4590 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004591 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004592 PrevDecl,
4593 PrevDecl->getTemplateSpecializationKind(),
4594 PrevDecl->getPointOfInstantiation(),
4595 SuppressNew))
4596 return true;
4597
4598 // FIXME: We may still want to build some representation of this
4599 // explicit specialization.
4600 if (SuppressNew)
4601 return DeclPtrTy();
4602 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00004603
4604 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004605
4606 if (TSK == TSK_ExplicitInstantiationDefinition)
4607 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4608 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004609
Douglas Gregore47f5a72009-10-14 23:41:34 +00004610 // C++0x [temp.explicit]p2:
4611 // If the explicit instantiation is for a member function, a member class
4612 // or a static data member of a class template specialization, the name of
4613 // the class template specialization in the qualified-id for the member
4614 // name shall be a simple-template-id.
4615 //
4616 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004617 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004618 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004619 D.getCXXScopeSpec().isSet() &&
4620 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4621 Diag(D.getIdentifierLoc(),
4622 diag::err_explicit_instantiation_without_qualified_id)
4623 << Specialization << D.getCXXScopeSpec().getRange();
4624
4625 CheckExplicitInstantiationScope(*this,
4626 FunTmpl? (NamedDecl *)FunTmpl
4627 : Specialization->getInstantiatedFromMemberFunction(),
4628 D.getIdentifierLoc(),
4629 D.getCXXScopeSpec().isSet());
4630
Douglas Gregor450f00842009-09-25 18:43:00 +00004631 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4632 return DeclPtrTy();
4633}
4634
Douglas Gregor333489b2009-03-27 23:10:48 +00004635Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004636Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4637 const CXXScopeSpec &SS, IdentifierInfo *Name,
4638 SourceLocation TagLoc, SourceLocation NameLoc) {
4639 // This has to hold, because SS is expected to be defined.
4640 assert(Name && "Expected a name in a dependent tag");
4641
4642 NestedNameSpecifier *NNS
4643 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4644 if (!NNS)
4645 return true;
4646
4647 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4648 if (T.isNull())
4649 return true;
4650
4651 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4652 QualType ElabType = Context.getElaboratedType(T, TagKind);
4653
4654 return ElabType.getAsOpaquePtr();
4655}
4656
4657Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004658Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4659 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004660 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004661 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4662 if (!NNS)
4663 return true;
4664
4665 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004666 if (T.isNull())
4667 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004668 return T.getAsOpaquePtr();
4669}
4670
Douglas Gregordce2b622009-04-01 00:28:59 +00004671Sema::TypeResult
4672Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4673 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004674 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004675 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004676 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004677 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004678 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004679 assert(TemplateId && "Expected a template specialization type");
4680
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004681 if (computeDeclContext(SS, false)) {
4682 // If we can compute a declaration context, then the "typename"
4683 // keyword was superfluous. Just build a QualifiedNameType to keep
4684 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004685
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004686 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4687 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4688 }
Mike Stump11289f42009-09-09 15:08:12 +00004689
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004690 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004691}
4692
Douglas Gregor333489b2009-03-27 23:10:48 +00004693/// \brief Build the type that describes a C++ typename specifier,
4694/// e.g., "typename T::type".
4695QualType
4696Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4697 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004698 CXXRecordDecl *CurrentInstantiation = 0;
4699 if (NNS->isDependent()) {
4700 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004701
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004702 // If the nested-name-specifier does not refer to the current
4703 // instantiation, then build a typename type.
4704 if (!CurrentInstantiation)
4705 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004706
Douglas Gregorc707da62009-09-02 13:12:51 +00004707 // The nested-name-specifier refers to the current instantiation, so the
4708 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004709 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004710 // extraneous "typename" keywords, and we retroactively apply this DR to
4711 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004712 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004713
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004714 DeclContext *Ctx = 0;
4715
4716 if (CurrentInstantiation)
4717 Ctx = CurrentInstantiation;
4718 else {
4719 CXXScopeSpec SS;
4720 SS.setScopeRep(NNS);
4721 SS.setRange(Range);
4722 if (RequireCompleteDeclContext(SS))
4723 return QualType();
4724
4725 Ctx = computeDeclContext(SS);
4726 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004727 assert(Ctx && "No declaration context?");
4728
4729 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00004730 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4731 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00004732 unsigned DiagID = 0;
4733 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00004734 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004735 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004736 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004737 break;
4738
4739 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004740 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004741 // We found a type. Build a QualifiedNameType, since the
4742 // typename-specifier was just sugar. FIXME: Tell
4743 // QualifiedNameType that it has a "typename" prefix.
4744 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4745 }
4746
4747 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004748 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004749 break;
4750
John McCalle61f2ba2009-11-18 02:36:19 +00004751 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004752 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00004753 return QualType();
4754
Douglas Gregor333489b2009-03-27 23:10:48 +00004755 case LookupResult::FoundOverloaded:
4756 DiagID = diag::err_typename_nested_not_type;
4757 Referenced = *Result.begin();
4758 break;
4759
John McCall6538c932009-10-10 05:48:19 +00004760 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004761 return QualType();
4762 }
4763
4764 // If we get here, it's because name lookup did not find a
4765 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004766 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004767 if (Referenced)
4768 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4769 << Name;
4770 return QualType();
4771}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004772
4773namespace {
4774 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00004775 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00004776 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004777 SourceLocation Loc;
4778 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004779
Douglas Gregor15acfb92009-08-06 16:20:37 +00004780 public:
Mike Stump11289f42009-09-09 15:08:12 +00004781 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004782 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004783 DeclarationName Entity)
4784 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004785 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004786
4787 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004788 /// transformed.
4789 ///
4790 /// For the purposes of type reconstruction, a type has already been
4791 /// transformed if it is NULL or if it is not dependent.
4792 bool AlreadyTransformed(QualType T) {
4793 return T.isNull() || !T->isDependentType();
4794 }
Mike Stump11289f42009-09-09 15:08:12 +00004795
4796 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004797 /// rebuilt.
4798 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004799
Douglas Gregor15acfb92009-08-06 16:20:37 +00004800 /// \brief Returns the name of the entity whose type is being rebuilt.
4801 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004802
Douglas Gregoref6ab412009-10-27 06:26:26 +00004803 /// \brief Sets the "base" location and entity when that
4804 /// information is known based on another transformation.
4805 void setBase(SourceLocation Loc, DeclarationName Entity) {
4806 this->Loc = Loc;
4807 this->Entity = Entity;
4808 }
4809
Douglas Gregor15acfb92009-08-06 16:20:37 +00004810 /// \brief Transforms an expression by returning the expression itself
4811 /// (an identity function).
4812 ///
4813 /// FIXME: This is completely unsafe; we will need to actually clone the
4814 /// expressions.
4815 Sema::OwningExprResult TransformExpr(Expr *E) {
4816 return getSema().Owned(E);
4817 }
Mike Stump11289f42009-09-09 15:08:12 +00004818
Douglas Gregor15acfb92009-08-06 16:20:37 +00004819 /// \brief Transforms a typename type by determining whether the type now
4820 /// refers to a member of the current instantiation, and then
4821 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004822 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004823 };
4824}
4825
Mike Stump11289f42009-09-09 15:08:12 +00004826QualType
John McCall550e0c22009-10-21 00:40:46 +00004827CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4828 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004829 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004830
Douglas Gregor15acfb92009-08-06 16:20:37 +00004831 NestedNameSpecifier *NNS
4832 = TransformNestedNameSpecifier(T->getQualifier(),
4833 /*FIXME:*/SourceRange(getBaseLocation()));
4834 if (!NNS)
4835 return QualType();
4836
4837 // If the nested-name-specifier did not change, and we cannot compute the
4838 // context corresponding to the nested-name-specifier, then this
4839 // typename type will not change; exit early.
4840 CXXScopeSpec SS;
4841 SS.setRange(SourceRange(getBaseLocation()));
4842 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004843
4844 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004845 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004846 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004847
4848 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004849 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004850 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004851 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004852 = TransformType(QualType(TemplateId, 0));
4853 if (NewTemplateId.isNull())
4854 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004855
Douglas Gregor15acfb92009-08-06 16:20:37 +00004856 if (NNS == T->getQualifier() &&
4857 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004858 Result = QualType(T, 0);
4859 else
4860 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4861 } else
4862 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4863 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004864
John McCall0ad16662009-10-29 08:12:44 +00004865 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4866 NewTL.setNameLoc(TL.getNameLoc());
4867 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004868}
4869
4870/// \brief Rebuilds a type within the context of the current instantiation.
4871///
Mike Stump11289f42009-09-09 15:08:12 +00004872/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004873/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004874/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004875/// partial specialization thereof). This routine will rebuild that type now
4876/// that we have entered the declarator's scope, which may produce different
4877/// canonical types, e.g.,
4878///
4879/// \code
4880/// template<typename T>
4881/// struct X {
4882/// typedef T* pointer;
4883/// pointer data();
4884/// };
4885///
4886/// template<typename T>
4887/// typename X<T>::pointer X<T>::data() { ... }
4888/// \endcode
4889///
4890/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4891/// since we do not know that we can look into X<T> when we parsed the type.
4892/// This function will rebuild the type, performing the lookup of "pointer"
4893/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4894/// as the canonical type of T*, allowing the return types of the out-of-line
4895/// definition and the declaration to match.
4896QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4897 DeclarationName Name) {
4898 if (T.isNull() || !T->isDependentType())
4899 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004900
Douglas Gregor15acfb92009-08-06 16:20:37 +00004901 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4902 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004903}
Douglas Gregorbe999392009-09-15 16:23:51 +00004904
4905/// \brief Produces a formatted string that describes the binding of
4906/// template parameters to template arguments.
4907std::string
4908Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4909 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004910 // FIXME: For variadic templates, we'll need to get the structured list.
4911 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4912 Args.flat_size());
4913}
4914
4915std::string
4916Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4917 const TemplateArgument *Args,
4918 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004919 std::string Result;
4920
Douglas Gregore62e6a02009-11-11 19:13:48 +00004921 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00004922 return Result;
4923
4924 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004925 if (I >= NumArgs)
4926 break;
4927
Douglas Gregorbe999392009-09-15 16:23:51 +00004928 if (I == 0)
4929 Result += "[with ";
4930 else
4931 Result += ", ";
4932
4933 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4934 Result += Id->getName();
4935 } else {
4936 Result += '$';
4937 Result += llvm::utostr(I);
4938 }
4939
4940 Result += " = ";
4941
4942 switch (Args[I].getKind()) {
4943 case TemplateArgument::Null:
4944 Result += "<no value>";
4945 break;
4946
4947 case TemplateArgument::Type: {
4948 std::string TypeStr;
4949 Args[I].getAsType().getAsStringInternal(TypeStr,
4950 Context.PrintingPolicy);
4951 Result += TypeStr;
4952 break;
4953 }
4954
4955 case TemplateArgument::Declaration: {
4956 bool Unnamed = true;
4957 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4958 if (ND->getDeclName()) {
4959 Unnamed = false;
4960 Result += ND->getNameAsString();
4961 }
4962 }
4963
4964 if (Unnamed) {
4965 Result += "<anonymous>";
4966 }
4967 break;
4968 }
4969
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004970 case TemplateArgument::Template: {
4971 std::string Str;
4972 llvm::raw_string_ostream OS(Str);
4973 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4974 Result += OS.str();
4975 break;
4976 }
4977
Douglas Gregorbe999392009-09-15 16:23:51 +00004978 case TemplateArgument::Integral: {
4979 Result += Args[I].getAsIntegral()->toString(10);
4980 break;
4981 }
4982
4983 case TemplateArgument::Expression: {
4984 assert(false && "No expressions in deduced template arguments!");
4985 Result += "<expression>";
4986 break;
4987 }
4988
4989 case TemplateArgument::Pack:
4990 // FIXME: Format template argument packs
4991 Result += "<template argument pack>";
4992 break;
4993 }
4994 }
4995
4996 Result += ']';
4997 return Result;
4998}