blob: 5f5d891a2264df49db4b7b71568b1326d4ff9b0e [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000020#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000023#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000024using namespace clang;
25
Douglas Gregorb7bfe792009-09-02 22:59:36 +000026/// \brief Determine whether the declaration found is acceptable as the name
27/// of a template and, if so, return that template declaration. Otherwise,
28/// returns NULL.
29static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
30 if (!D)
31 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000032
Douglas Gregorb7bfe792009-09-02 22:59:36 +000033 if (isa<TemplateDecl>(D))
34 return D;
Mike Stump11289f42009-09-09 15:08:12 +000035
Douglas Gregorb7bfe792009-09-02 22:59:36 +000036 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
37 // C++ [temp.local]p1:
38 // Like normal (non-template) classes, class templates have an
39 // injected-class-name (Clause 9). The injected-class-name
40 // can be used with or without a template-argument-list. When
41 // it is used without a template-argument-list, it is
42 // equivalent to the injected-class-name followed by the
43 // template-parameters of the class template enclosed in
44 // <>. When it is used with a template-argument-list, it
45 // refers to the specified class template specialization,
46 // which could be the current specialization or another
47 // specialization.
48 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000049 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000050 if (Record->getDescribedClassTemplate())
51 return Record->getDescribedClassTemplate();
52
53 if (ClassTemplateSpecializationDecl *Spec
54 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
55 return Spec->getSpecializedTemplate();
56 }
Mike Stump11289f42009-09-09 15:08:12 +000057
Douglas Gregorb7bfe792009-09-02 22:59:36 +000058 return 0;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Douglas Gregorb7bfe792009-09-02 22:59:36 +000061 return 0;
62}
63
John McCalle66edc12009-11-24 19:00:30 +000064static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
65 LookupResult::Filter filter = R.makeFilter();
66 while (filter.hasNext()) {
67 NamedDecl *Orig = filter.next();
68 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
69 if (!Repl)
70 filter.erase();
71 else if (Repl != Orig)
72 filter.replace(Repl);
73 }
74 filter.done();
75}
76
Douglas Gregorb7bfe792009-09-02 22:59:36 +000077TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor3cf81312009-11-03 23:16:33 +000078 const CXXScopeSpec &SS,
79 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +000080 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +000081 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +000082 TemplateTy &TemplateResult) {
Douglas Gregor3cf81312009-11-03 23:16:33 +000083 DeclarationName TName;
84
85 switch (Name.getKind()) {
86 case UnqualifiedId::IK_Identifier:
87 TName = DeclarationName(Name.Identifier);
88 break;
89
90 case UnqualifiedId::IK_OperatorFunctionId:
91 TName = Context.DeclarationNames.getCXXOperatorName(
92 Name.OperatorFunctionId.Operator);
93 break;
94
Alexis Hunted0530f2009-11-28 08:58:14 +000095 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +000096 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
97 break;
Alexis Hunted0530f2009-11-28 08:58:14 +000098
Douglas Gregor3cf81312009-11-03 23:16:33 +000099 default:
100 return TNK_Non_template;
101 }
Mike Stump11289f42009-09-09 15:08:12 +0000102
John McCalle66edc12009-11-24 19:00:30 +0000103 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000104
John McCalle66edc12009-11-24 19:00:30 +0000105 LookupResult R(*this, TName, SourceLocation(), LookupOrdinaryName);
106 R.suppressDiagnostics();
107 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
108 if (R.empty())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000109 return TNK_Non_template;
110
John McCalle66edc12009-11-24 19:00:30 +0000111 NamedDecl *Template = R.getAsSingleDecl(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000112
Douglas Gregor3cf81312009-11-03 23:16:33 +0000113 if (SS.isSet() && !SS.isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000114 NestedNameSpecifier *Qualifier
Douglas Gregor3cf81312009-11-03 23:16:33 +0000115 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000116 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000117 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000118 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000119 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
120 Ovl));
121 else
Mike Stump11289f42009-09-09 15:08:12 +0000122 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000123 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000124 cast<TemplateDecl>(Template)));
125 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000126 = dyn_cast<OverloadedFunctionDecl>(Template)) {
127 TemplateResult = TemplateTy::make(TemplateName(Ovl));
128 } else {
129 TemplateResult = TemplateTy::make(
130 TemplateName(cast<TemplateDecl>(Template)));
131 }
Mike Stump11289f42009-09-09 15:08:12 +0000132
133 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000134 isa<TemplateTemplateParmDecl>(Template))
135 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000136
137 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000138 isa<OverloadedFunctionDecl>(Template)) &&
139 "Unhandled template kind in Sema::isTemplateName");
John McCalle66edc12009-11-24 19:00:30 +0000140 return TNK_Function_template;
141}
142
143void Sema::LookupTemplateName(LookupResult &Found,
144 Scope *S, const CXXScopeSpec &SS,
145 QualType ObjectType,
146 bool EnteringContext) {
147 // Determine where to perform name lookup
148 DeclContext *LookupCtx = 0;
149 bool isDependent = false;
150 if (!ObjectType.isNull()) {
151 // This nested-name-specifier occurs in a member access expression, e.g.,
152 // x->B::f, and we are looking into the type of the object.
153 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
154 LookupCtx = computeDeclContext(ObjectType);
155 isDependent = ObjectType->isDependentType();
156 assert((isDependent || !ObjectType->isIncompleteType()) &&
157 "Caller should have completed object type");
158 } else if (SS.isSet()) {
159 // This nested-name-specifier occurs after another nested-name-specifier,
160 // so long into the context associated with the prior nested-name-specifier.
161 LookupCtx = computeDeclContext(SS, EnteringContext);
162 isDependent = isDependentScopeSpecifier(SS);
163
164 // The declaration context must be complete.
165 if (LookupCtx && RequireCompleteDeclContext(SS))
166 return;
167 }
168
169 bool ObjectTypeSearchedInScope = false;
170 if (LookupCtx) {
171 // Perform "qualified" name lookup into the declaration context we
172 // computed, which is either the type of the base of a member access
173 // expression or the declaration context associated with a prior
174 // nested-name-specifier.
175 LookupQualifiedName(Found, LookupCtx);
176
177 if (!ObjectType.isNull() && Found.empty()) {
178 // C++ [basic.lookup.classref]p1:
179 // In a class member access expression (5.2.5), if the . or -> token is
180 // immediately followed by an identifier followed by a <, the
181 // identifier must be looked up to determine whether the < is the
182 // beginning of a template argument list (14.2) or a less-than operator.
183 // The identifier is first looked up in the class of the object
184 // expression. If the identifier is not found, it is then looked up in
185 // the context of the entire postfix-expression and shall name a class
186 // or function template.
187 //
188 // FIXME: When we're instantiating a template, do we actually have to
189 // look in the scope of the template? Seems fishy...
190 if (S) LookupName(Found, S);
191 ObjectTypeSearchedInScope = true;
192 }
193 } else if (isDependent) {
194 // We cannot look into a dependent object type or
195 return;
196 } else {
197 // Perform unqualified name lookup in the current scope.
198 LookupName(Found, S);
199 }
200
201 // FIXME: Cope with ambiguous name-lookup results.
202 assert(!Found.isAmbiguous() &&
203 "Cannot handle template name-lookup ambiguities");
204
205 FilterAcceptableTemplateNames(Context, Found);
206 if (Found.empty())
207 return;
208
209 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
210 // C++ [basic.lookup.classref]p1:
211 // [...] If the lookup in the class of the object expression finds a
212 // template, the name is also looked up in the context of the entire
213 // postfix-expression and [...]
214 //
215 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
216 LookupOrdinaryName);
217 LookupName(FoundOuter, S);
218 FilterAcceptableTemplateNames(Context, FoundOuter);
219 // FIXME: Handle ambiguities in this lookup better
220
221 if (FoundOuter.empty()) {
222 // - if the name is not found, the name found in the class of the
223 // object expression is used, otherwise
224 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
225 // - if the name is found in the context of the entire
226 // postfix-expression and does not name a class template, the name
227 // found in the class of the object expression is used, otherwise
228 } else {
229 // - if the name found is a class template, it must refer to the same
230 // entity as the one found in the class of the object expression,
231 // otherwise the program is ill-formed.
232 if (!Found.isSingleResult() ||
233 Found.getFoundDecl()->getCanonicalDecl()
234 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
235 Diag(Found.getNameLoc(),
236 diag::err_nested_name_member_ref_lookup_ambiguous)
237 << Found.getLookupName();
238 Diag(Found.getRepresentativeDecl()->getLocation(),
239 diag::note_ambig_member_ref_object_type)
240 << ObjectType;
241 Diag(FoundOuter.getFoundDecl()->getLocation(),
242 diag::note_ambig_member_ref_scope);
243
244 // Recover by taking the template that we found in the object
245 // expression's type.
246 }
247 }
248 }
249}
250
251/// Constructs a full type for the given nested-name-specifier.
252static QualType GetTypeForQualifier(ASTContext &Context,
253 NestedNameSpecifier *Qualifier) {
254 // Three possibilities:
255
256 // 1. A namespace (global or not).
257 assert(!Qualifier->getAsNamespace() && "can't construct type for namespace");
258
259 // 2. A type (templated or not).
260 Type *Ty = Qualifier->getAsType();
261 if (Ty) return QualType(Ty, 0);
262
263 // 3. A dependent identifier.
264 assert(Qualifier->getAsIdentifier());
265 return Context.getTypenameType(Qualifier->getPrefix(),
266 Qualifier->getAsIdentifier());
267}
268
269static bool HasDependentTypeAsBase(ASTContext &Context,
270 CXXRecordDecl *Record,
271 CanQualType T) {
272 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
273 E = Record->bases_end(); I != E; ++I) {
274 CanQualType BaseT = Context.getCanonicalType((*I).getType());
275 if (BaseT == T)
276 return true;
277
278 // We have to recurse here to cover some really bizarre cases.
279 // Obviously, we can only have the dependent type as an indirect
280 // base class through a dependent base class, and usually it's
281 // impossible to know which instantiation a dependent base class
282 // will have. But! If we're actually *inside* the dependent base
283 // class, then we know its instantiation and can therefore be
284 // reasonably expected to look into it.
285
286 // template <class T> class A : Base<T> {
287 // class Inner : A<T> {
288 // void foo() {
289 // Base<T>::foo(); // statically known to be an implicit member
290 // reference
291 // }
292 // };
293 // };
294
295 CanQual<RecordType> RT = BaseT->getAs<RecordType>();
John McCall45b1a472009-11-24 20:33:45 +0000296
297 // Base might be a dependent member type, in which case we
298 // obviously can't look into it.
299 if (!RT) continue;
300
John McCalle66edc12009-11-24 19:00:30 +0000301 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(RT->getDecl());
302 if (BaseRecord->isDefinition() &&
303 HasDependentTypeAsBase(Context, BaseRecord, T))
304 return true;
305 }
306
307 return false;
308}
309
310/// Checks whether the given dependent nested-name specifier
311/// introduces an implicit member reference. This is only true if the
312/// nested-name specifier names a type identical to one of the current
313/// instance method's context's (possibly indirect) base classes.
314static bool IsImplicitDependentMemberReference(Sema &SemaRef,
315 NestedNameSpecifier *Qualifier,
316 QualType &ThisType) {
317 // If the context isn't a C++ method, then it isn't an implicit
318 // member reference.
319 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext);
320 if (!MD || MD->isStatic())
321 return false;
322
323 ASTContext &Context = SemaRef.Context;
324
325 // We want to check whether the method's context is known to inherit
326 // from the type named by the nested name specifier. The trivial
327 // case here is:
328 // template <class T> class Base { ... };
329 // template <class T> class Derived : Base<T> {
330 // void foo() {
331 // Base<T>::foo();
332 // }
333 // };
334
335 QualType QT = GetTypeForQualifier(Context, Qualifier);
336 CanQualType T = Context.getCanonicalType(QT);
John McCall45b1a472009-11-24 20:33:45 +0000337
John McCalle66edc12009-11-24 19:00:30 +0000338 // And now, just walk the non-dependent type hierarchy, trying to
339 // find the given type as a literal base class.
340 CXXRecordDecl *Record = cast<CXXRecordDecl>(MD->getParent());
John McCall45b1a472009-11-24 20:33:45 +0000341 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T ||
342 HasDependentTypeAsBase(Context, Record, T)) {
343 ThisType = MD->getThisType(Context);
John McCalle66edc12009-11-24 19:00:30 +0000344 return true;
John McCall45b1a472009-11-24 20:33:45 +0000345 }
John McCalle66edc12009-11-24 19:00:30 +0000346
John McCall45b1a472009-11-24 20:33:45 +0000347 return false;
John McCalle66edc12009-11-24 19:00:30 +0000348}
349
350/// ActOnDependentIdExpression - Handle a dependent declaration name
351/// that was just parsed.
352Sema::OwningExprResult
353Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
354 DeclarationName Name,
355 SourceLocation NameLoc,
356 bool CheckForImplicitMember,
357 const TemplateArgumentListInfo *TemplateArgs) {
358 NestedNameSpecifier *Qualifier
359 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
360
361 QualType ThisType;
362 if (CheckForImplicitMember &&
363 IsImplicitDependentMemberReference(*this, Qualifier, ThisType)) {
John McCalle66edc12009-11-24 19:00:30 +0000364 // Since the 'this' expression is synthesized, we don't need to
365 // perform the double-lookup check.
366 NamedDecl *FirstQualifierInScope = 0;
367
John McCall2d74de92009-12-01 22:10:20 +0000368 return Owned(CXXDependentScopeMemberExpr::Create(Context,
369 /*This*/ 0, ThisType,
370 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000371 /*Op*/ SourceLocation(),
372 Qualifier, SS.getRange(),
373 FirstQualifierInScope,
374 Name, NameLoc,
375 TemplateArgs));
376 }
377
378 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
379}
380
381Sema::OwningExprResult
382Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
383 DeclarationName Name,
384 SourceLocation NameLoc,
385 const TemplateArgumentListInfo *TemplateArgs) {
386 return Owned(DependentScopeDeclRefExpr::Create(Context,
387 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
388 SS.getRange(),
389 Name, NameLoc,
390 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000391}
392
Douglas Gregor5101c242008-12-05 18:15:24 +0000393/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
394/// that the template parameter 'PrevDecl' is being shadowed by a new
395/// declaration at location Loc. Returns true to indicate that this is
396/// an error, and false otherwise.
397bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000398 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000399
400 // Microsoft Visual C++ permits template parameters to be shadowed.
401 if (getLangOptions().Microsoft)
402 return false;
403
404 // C++ [temp.local]p4:
405 // A template-parameter shall not be redeclared within its
406 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000407 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000408 << cast<NamedDecl>(PrevDecl)->getDeclName();
409 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
410 return true;
411}
412
Douglas Gregor463421d2009-03-03 04:44:36 +0000413/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000414/// the parameter D to reference the templated declaration and return a pointer
415/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000416TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000417 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000418 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000419 return Temp;
420 }
421 return 0;
422}
423
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000424static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
425 const ParsedTemplateArgument &Arg) {
426
427 switch (Arg.getKind()) {
428 case ParsedTemplateArgument::Type: {
429 DeclaratorInfo *DI;
430 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
431 if (!DI)
432 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation());
433 return TemplateArgumentLoc(TemplateArgument(T), DI);
434 }
435
436 case ParsedTemplateArgument::NonType: {
437 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
438 return TemplateArgumentLoc(TemplateArgument(E), E);
439 }
440
441 case ParsedTemplateArgument::Template: {
442 TemplateName Template
443 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
444 return TemplateArgumentLoc(TemplateArgument(Template),
445 Arg.getScopeSpec().getRange(),
446 Arg.getLocation());
447 }
448 }
449
450 llvm::llvm_unreachable("Unhandled parsed template argument");
451 return TemplateArgumentLoc();
452}
453
454/// \brief Translates template arguments as provided by the parser
455/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000456void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
457 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000458 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000459 TemplateArgs.addArgument(translateTemplateArgument(*this,
460 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000461}
462
Douglas Gregor5101c242008-12-05 18:15:24 +0000463/// ActOnTypeParameter - Called when a C++ template type parameter
464/// (e.g., "typename T") has been parsed. Typename specifies whether
465/// the keyword "typename" was used to declare the type parameter
466/// (otherwise, "class" was used), and KeyLoc is the location of the
467/// "class" or "typename" keyword. ParamName is the name of the
468/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000469/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000470/// If the type parameter has a default argument, it will be added
471/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000472Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000473 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000474 SourceLocation KeyLoc,
475 IdentifierInfo *ParamName,
476 SourceLocation ParamNameLoc,
477 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000478 assert(S->isTemplateParamScope() &&
479 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000480 bool Invalid = false;
481
482 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000483 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000484 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000485 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000486 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000487 }
488
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000489 SourceLocation Loc = ParamNameLoc;
490 if (!ParamName)
491 Loc = KeyLoc;
492
Douglas Gregor5101c242008-12-05 18:15:24 +0000493 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000494 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
495 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000496 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000497 if (Invalid)
498 Param->setInvalidDecl();
499
500 if (ParamName) {
501 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000502 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000503 IdResolver.AddDecl(Param);
504 }
505
Chris Lattner83f095c2009-03-28 19:18:32 +0000506 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000507}
508
Douglas Gregordba32632009-02-10 19:49:53 +0000509/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000510/// Default) to the given template type parameter (TypeParam).
511void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000512 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000513 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000514 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000515 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000516 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000517
518 DeclaratorInfo *DefaultDInfo;
519 GetTypeFromParser(DefaultT, &DefaultDInfo);
520
521 assert(DefaultDInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000522
Anders Carlssond3824352009-06-12 22:30:13 +0000523 // C++0x [temp.param]p9:
524 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000525 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000526 if (Parm->isParameterPack()) {
527 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000528 return;
529 }
Mike Stump11289f42009-09-09 15:08:12 +0000530
Douglas Gregordba32632009-02-10 19:49:53 +0000531 // C++ [temp.param]p14:
532 // A template-parameter shall not be used in its own default argument.
533 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000534
Douglas Gregordba32632009-02-10 19:49:53 +0000535 // Check the template argument itself.
John McCall0ad16662009-10-29 08:12:44 +0000536 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000537 Parm->setInvalidDecl();
538 return;
539 }
540
John McCall0ad16662009-10-29 08:12:44 +0000541 Parm->setDefaultArgument(DefaultDInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000542}
543
Douglas Gregor463421d2009-03-03 04:44:36 +0000544/// \brief Check that the type of a non-type template parameter is
545/// well-formed.
546///
547/// \returns the (possibly-promoted) parameter type if valid;
548/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000549QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000550Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
551 // C++ [temp.param]p4:
552 //
553 // A non-type template-parameter shall have one of the following
554 // (optionally cv-qualified) types:
555 //
556 // -- integral or enumeration type,
557 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000558 // -- pointer to object or pointer to function,
559 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000560 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
561 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000562 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000563 T->isReferenceType() ||
564 // -- pointer to member.
565 T->isMemberPointerType() ||
566 // If T is a dependent type, we can't do the check now, so we
567 // assume that it is well-formed.
568 T->isDependentType())
569 return T;
570 // C++ [temp.param]p8:
571 //
572 // A non-type template-parameter of type "array of T" or
573 // "function returning T" is adjusted to be of type "pointer to
574 // T" or "pointer to function returning T", respectively.
575 else if (T->isArrayType())
576 // FIXME: Keep the type prior to promotion?
577 return Context.getArrayDecayedType(T);
578 else if (T->isFunctionType())
579 // FIXME: Keep the type prior to promotion?
580 return Context.getPointerType(T);
581
582 Diag(Loc, diag::err_template_nontype_parm_bad_type)
583 << T;
584
585 return QualType();
586}
587
Douglas Gregor5101c242008-12-05 18:15:24 +0000588/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
589/// template parameter (e.g., "int Size" in "template<int Size>
590/// class Array") has been parsed. S is the current scope and D is
591/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000592Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000593 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000594 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000595 DeclaratorInfo *DInfo = 0;
596 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000597
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000598 assert(S->isTemplateParamScope() &&
599 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000600 bool Invalid = false;
601
602 IdentifierInfo *ParamName = D.getIdentifier();
603 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000604 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000605 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000606 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000607 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000608 }
609
Douglas Gregor463421d2009-03-03 04:44:36 +0000610 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000611 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000612 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000613 Invalid = true;
614 }
Douglas Gregor81338792009-02-10 17:43:50 +0000615
Douglas Gregor5101c242008-12-05 18:15:24 +0000616 NonTypeTemplateParmDecl *Param
617 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000618 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000619 if (Invalid)
620 Param->setInvalidDecl();
621
622 if (D.getIdentifier()) {
623 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000624 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000625 IdResolver.AddDecl(Param);
626 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000627 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000628}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000629
Douglas Gregordba32632009-02-10 19:49:53 +0000630/// \brief Adds a default argument to the given non-type template
631/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000632void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000633 SourceLocation EqualLoc,
634 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000635 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000636 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000637 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000638
Douglas Gregordba32632009-02-10 19:49:53 +0000639 // C++ [temp.param]p14:
640 // A template-parameter shall not be used in its own default argument.
641 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000642
Douglas Gregordba32632009-02-10 19:49:53 +0000643 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000644 TemplateArgument Converted;
645 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
646 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000647 TemplateParm->setInvalidDecl();
648 return;
649 }
650
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000651 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000652}
653
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000654
655/// ActOnTemplateTemplateParameter - Called when a C++ template template
656/// parameter (e.g. T in template <template <typename> class T> class array)
657/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000658Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
659 SourceLocation TmpLoc,
660 TemplateParamsTy *Params,
661 IdentifierInfo *Name,
662 SourceLocation NameLoc,
663 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000664 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000665 assert(S->isTemplateParamScope() &&
666 "Template template parameter not in template parameter scope!");
667
668 // Construct the parameter object.
669 TemplateTemplateParmDecl *Param =
670 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
671 Position, Name,
672 (TemplateParameterList*)Params);
673
674 // Make sure the parameter is valid.
675 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
676 // do anything yet. However, if the template parameter list or (eventual)
677 // default value is ever invalidated, that will propagate here.
678 bool Invalid = false;
679 if (Invalid) {
680 Param->setInvalidDecl();
681 }
682
683 // If the tt-param has a name, then link the identifier into the scope
684 // and lookup mechanisms.
685 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000686 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000687 IdResolver.AddDecl(Param);
688 }
689
Chris Lattner83f095c2009-03-28 19:18:32 +0000690 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000691}
692
Douglas Gregordba32632009-02-10 19:49:53 +0000693/// \brief Adds a default argument to the given template template
694/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000695void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000696 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000697 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000698 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000699 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000700
Douglas Gregordba32632009-02-10 19:49:53 +0000701 // C++ [temp.param]p14:
702 // A template-parameter shall not be used in its own default argument.
703 // FIXME: Implement this check! Needs a recursive walk over the types.
704
Douglas Gregore62e6a02009-11-11 19:13:48 +0000705 // Check only that we have a template template argument. We don't want to
706 // try to check well-formedness now, because our template template parameter
707 // might have dependent types in its template parameters, which we wouldn't
708 // be able to match now.
709 //
710 // If none of the template template parameter's template arguments mention
711 // other template parameters, we could actually perform more checking here.
712 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000713 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000714 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
715 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
716 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000717 return;
718 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000719
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000720 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000721}
722
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000723/// ActOnTemplateParameterList - Builds a TemplateParameterList that
724/// contains the template parameters in Params/NumParams.
725Sema::TemplateParamsTy *
726Sema::ActOnTemplateParameterList(unsigned Depth,
727 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000728 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000729 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000730 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000731 SourceLocation RAngleLoc) {
732 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000733 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000734
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000735 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000736 (NamedDecl**)Params, NumParams,
737 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000738}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000739
Douglas Gregorc08f4892009-03-25 00:13:59 +0000740Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000741Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000742 SourceLocation KWLoc, const CXXScopeSpec &SS,
743 IdentifierInfo *Name, SourceLocation NameLoc,
744 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000745 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000746 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000747 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000748 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000749 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000750 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000751
752 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000753 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000754 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000755
John McCall27b5c252009-09-14 21:59:20 +0000756 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
757 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000758
759 // There is no such thing as an unnamed class template.
760 if (!Name) {
761 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000762 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000763 }
764
765 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000766 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000767 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000768 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000769 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000770 if (RequireCompleteDeclContext(SS))
771 return true;
772
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000773 SemanticContext = computeDeclContext(SS, true);
774 if (!SemanticContext) {
775 // FIXME: Produce a reasonable diagnostic here
776 return true;
777 }
Mike Stump11289f42009-09-09 15:08:12 +0000778
John McCall27b18f82009-11-17 02:14:36 +0000779 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000780 } else {
781 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000782 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000783 }
Mike Stump11289f42009-09-09 15:08:12 +0000784
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000785 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
786 NamedDecl *PrevDecl = 0;
787 if (Previous.begin() != Previous.end())
788 PrevDecl = *Previous.begin();
789
Douglas Gregor9acb6902009-09-26 07:05:09 +0000790 if (PrevDecl && TUK == TUK_Friend) {
791 // C++ [namespace.memdef]p3:
792 // [...] When looking for a prior declaration of a class or a function
793 // declared as a friend, and when the name of the friend class or
794 // function is neither a qualified name nor a template-id, scopes outside
795 // the innermost enclosing namespace scope are not considered.
796 DeclContext *OutermostContext = CurContext;
797 while (!OutermostContext->isFileContext())
798 OutermostContext = OutermostContext->getLookupParent();
799
800 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
801 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
802 SemanticContext = PrevDecl->getDeclContext();
803 } else {
804 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000805 // context we computed is the semantic context for our new
Douglas Gregor9acb6902009-09-26 07:05:09 +0000806 // declaration.
807 PrevDecl = 0;
808 SemanticContext = OutermostContext;
809 }
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000810
811 if (CurContext->isDependentContext()) {
812 // If this is a dependent context, we don't want to link the friend
813 // class template to the template in scope, because that would perform
814 // checking of the template parameter lists that can't be performed
815 // until the outer context is instantiated.
816 PrevDecl = 0;
817 }
Douglas Gregor9acb6902009-09-26 07:05:09 +0000818 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000819 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000820
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000821 // If there is a previous declaration with the same name, check
822 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000823 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000824 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000825
826 // We may have found the injected-class-name of a class template,
827 // class template partial specialization, or class template specialization.
828 // In these cases, grab the template that is being defined or specialized.
829 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
830 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
831 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
832 PrevClassTemplate
833 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
834 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
835 PrevClassTemplate
836 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
837 ->getSpecializedTemplate();
838 }
839 }
840
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000841 if (PrevClassTemplate) {
842 // Ensure that the template parameter lists are compatible.
843 if (!TemplateParameterListsAreEqual(TemplateParams,
844 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000845 /*Complain=*/true,
846 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000847 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000848
849 // C++ [temp.class]p4:
850 // In a redeclaration, partial specialization, explicit
851 // specialization or explicit instantiation of a class template,
852 // the class-key shall agree in kind with the original class
853 // template declaration (7.1.5.3).
854 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000855 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000856 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000857 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000858 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000859 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000860 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000861 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000862 }
863
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000864 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000865 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000866 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
867 Diag(NameLoc, diag::err_redefinition) << Name;
868 Diag(Def->getLocation(), diag::note_previous_definition);
869 // FIXME: Would it make sense to try to "forget" the previous
870 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000871 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000872 }
873 }
874 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
875 // Maybe we will complain about the shadowed template parameter.
876 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
877 // Just pretend that we didn't see the previous declaration.
878 PrevDecl = 0;
879 } else if (PrevDecl) {
880 // C++ [temp]p5:
881 // A class template shall not have the same name as any other
882 // template, class, function, object, enumeration, enumerator,
883 // namespace, or type in the same scope (3.3), except as specified
884 // in (14.5.4).
885 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
886 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000887 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000888 }
889
Douglas Gregordba32632009-02-10 19:49:53 +0000890 // Check the template parameter list of this declaration, possibly
891 // merging in the template parameter list from the previous class
892 // template declaration.
893 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000894 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
895 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000896 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000897
Douglas Gregore362cea2009-05-10 22:57:19 +0000898 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000899 // declaration!
900
Mike Stump11289f42009-09-09 15:08:12 +0000901 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000902 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000903 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000904 PrevClassTemplate->getTemplatedDecl() : 0,
905 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000906
907 ClassTemplateDecl *NewTemplate
908 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
909 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000910 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000911 NewClass->setDescribedClassTemplate(NewTemplate);
912
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000913 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000914 QualType T =
915 Context.getTypeDeclType(NewClass,
916 PrevClassTemplate?
917 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000918 assert(T->isDependentType() && "Class template type is not dependent?");
919 (void)T;
920
Douglas Gregorcf915552009-10-13 16:30:37 +0000921 // If we are providing an explicit specialization of a member that is a
922 // class template, make a note of that.
923 if (PrevClassTemplate &&
924 PrevClassTemplate->getInstantiatedFromMemberTemplate())
925 PrevClassTemplate->setMemberSpecialization();
926
Anders Carlsson137108d2009-03-26 01:24:28 +0000927 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000928 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000929 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000930
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000931 // Set the lexical context of these templates
932 NewClass->setLexicalDeclContext(CurContext);
933 NewTemplate->setLexicalDeclContext(CurContext);
934
John McCall9bb74a52009-07-31 02:45:11 +0000935 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000936 NewClass->startDefinition();
937
938 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000939 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000940
John McCall27b5c252009-09-14 21:59:20 +0000941 if (TUK != TUK_Friend)
942 PushOnScopeChains(NewTemplate, S);
943 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000944 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000945 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000946 NewClass->setAccess(PrevClassTemplate->getAccess());
947 }
John McCall27b5c252009-09-14 21:59:20 +0000948
Douglas Gregor3dad8422009-09-26 06:47:28 +0000949 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
950 PrevClassTemplate != NULL);
951
John McCall27b5c252009-09-14 21:59:20 +0000952 // Friend templates are visible in fairly strange ways.
953 if (!CurContext->isDependentContext()) {
954 DeclContext *DC = SemanticContext->getLookupContext();
955 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
956 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
957 PushOnScopeChains(NewTemplate, EnclosingScope,
958 /* AddToContext = */ false);
959 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000960
961 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
962 NewClass->getLocation(),
963 NewTemplate,
964 /*FIXME:*/NewClass->getLocation());
965 Friend->setAccess(AS_public);
966 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000967 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000968
Douglas Gregordba32632009-02-10 19:49:53 +0000969 if (Invalid) {
970 NewTemplate->setInvalidDecl();
971 NewClass->setInvalidDecl();
972 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000973 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000974}
975
Douglas Gregored5731f2009-11-25 17:50:39 +0000976/// \brief Diagnose the presence of a default template argument on a
977/// template parameter, which is ill-formed in certain contexts.
978///
979/// \returns true if the default template argument should be dropped.
980static bool DiagnoseDefaultTemplateArgument(Sema &S,
981 Sema::TemplateParamListContext TPC,
982 SourceLocation ParamLoc,
983 SourceRange DefArgRange) {
984 switch (TPC) {
985 case Sema::TPC_ClassTemplate:
986 return false;
987
988 case Sema::TPC_FunctionTemplate:
989 // C++ [temp.param]p9:
990 // A default template-argument shall not be specified in a
991 // function template declaration or a function template
992 // definition [...]
993 // (This sentence is not in C++0x, per DR226).
994 if (!S.getLangOptions().CPlusPlus0x)
995 S.Diag(ParamLoc,
996 diag::err_template_parameter_default_in_function_template)
997 << DefArgRange;
998 return false;
999
1000 case Sema::TPC_ClassTemplateMember:
1001 // C++0x [temp.param]p9:
1002 // A default template-argument shall not be specified in the
1003 // template-parameter-lists of the definition of a member of a
1004 // class template that appears outside of the member's class.
1005 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1006 << DefArgRange;
1007 return true;
1008
1009 case Sema::TPC_FriendFunctionTemplate:
1010 // C++ [temp.param]p9:
1011 // A default template-argument shall not be specified in a
1012 // friend template declaration.
1013 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1014 << DefArgRange;
1015 return true;
1016
1017 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1018 // for friend function templates if there is only a single
1019 // declaration (and it is a definition). Strange!
1020 }
1021
1022 return false;
1023}
1024
Douglas Gregordba32632009-02-10 19:49:53 +00001025/// \brief Checks the validity of a template parameter list, possibly
1026/// considering the template parameter list from a previous
1027/// declaration.
1028///
1029/// If an "old" template parameter list is provided, it must be
1030/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1031/// template parameter list.
1032///
1033/// \param NewParams Template parameter list for a new template
1034/// declaration. This template parameter list will be updated with any
1035/// default arguments that are carried through from the previous
1036/// template parameter list.
1037///
1038/// \param OldParams If provided, template parameter list from a
1039/// previous declaration of the same template. Default template
1040/// arguments will be merged from the old template parameter list to
1041/// the new template parameter list.
1042///
Douglas Gregored5731f2009-11-25 17:50:39 +00001043/// \param TPC Describes the context in which we are checking the given
1044/// template parameter list.
1045///
Douglas Gregordba32632009-02-10 19:49:53 +00001046/// \returns true if an error occurred, false otherwise.
1047bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001048 TemplateParameterList *OldParams,
1049 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001050 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001051
Douglas Gregordba32632009-02-10 19:49:53 +00001052 // C++ [temp.param]p10:
1053 // The set of default template-arguments available for use with a
1054 // template declaration or definition is obtained by merging the
1055 // default arguments from the definition (if in scope) and all
1056 // declarations in scope in the same way default function
1057 // arguments are (8.3.6).
1058 bool SawDefaultArgument = false;
1059 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001060
Anders Carlsson327865d2009-06-12 23:20:15 +00001061 bool SawParameterPack = false;
1062 SourceLocation ParameterPackLoc;
1063
Mike Stumpc89c8e32009-02-11 23:03:27 +00001064 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001065 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001066 if (OldParams)
1067 OldParam = OldParams->begin();
1068
1069 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1070 NewParamEnd = NewParams->end();
1071 NewParam != NewParamEnd; ++NewParam) {
1072 // Variables used to diagnose redundant default arguments
1073 bool RedundantDefaultArg = false;
1074 SourceLocation OldDefaultLoc;
1075 SourceLocation NewDefaultLoc;
1076
1077 // Variables used to diagnose missing default arguments
1078 bool MissingDefaultArg = false;
1079
Anders Carlsson327865d2009-06-12 23:20:15 +00001080 // C++0x [temp.param]p11:
1081 // If a template parameter of a class template is a template parameter pack,
1082 // it must be the last template parameter.
1083 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001084 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001085 diag::err_template_param_pack_must_be_last_template_parameter);
1086 Invalid = true;
1087 }
1088
Douglas Gregordba32632009-02-10 19:49:53 +00001089 if (TemplateTypeParmDecl *NewTypeParm
1090 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001091 // Check the presence of a default argument here.
1092 if (NewTypeParm->hasDefaultArgument() &&
1093 DiagnoseDefaultTemplateArgument(*this, TPC,
1094 NewTypeParm->getLocation(),
1095 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1096 .getFullSourceRange()))
1097 NewTypeParm->removeDefaultArgument();
1098
1099 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001100 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001101 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001102
Anders Carlsson327865d2009-06-12 23:20:15 +00001103 if (NewTypeParm->isParameterPack()) {
1104 assert(!NewTypeParm->hasDefaultArgument() &&
1105 "Parameter packs can't have a default argument!");
1106 SawParameterPack = true;
1107 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001108 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001109 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001110 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1111 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1112 SawDefaultArgument = true;
1113 RedundantDefaultArg = true;
1114 PreviousDefaultArgLoc = NewDefaultLoc;
1115 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1116 // Merge the default argument from the old declaration to the
1117 // new declaration.
1118 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001119 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001120 true);
1121 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1122 } else if (NewTypeParm->hasDefaultArgument()) {
1123 SawDefaultArgument = true;
1124 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1125 } else if (SawDefaultArgument)
1126 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001127 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001128 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001129 // Check the presence of a default argument here.
1130 if (NewNonTypeParm->hasDefaultArgument() &&
1131 DiagnoseDefaultTemplateArgument(*this, TPC,
1132 NewNonTypeParm->getLocation(),
1133 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1134 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1135 NewNonTypeParm->setDefaultArgument(0);
1136 }
1137
Mike Stump12b8ce12009-08-04 21:02:39 +00001138 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001139 NonTypeTemplateParmDecl *OldNonTypeParm
1140 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001141 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001142 NewNonTypeParm->hasDefaultArgument()) {
1143 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1144 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1145 SawDefaultArgument = true;
1146 RedundantDefaultArg = true;
1147 PreviousDefaultArgLoc = NewDefaultLoc;
1148 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1149 // Merge the default argument from the old declaration to the
1150 // new declaration.
1151 SawDefaultArgument = true;
1152 // FIXME: We need to create a new kind of "default argument"
1153 // expression that points to a previous template template
1154 // parameter.
1155 NewNonTypeParm->setDefaultArgument(
1156 OldNonTypeParm->getDefaultArgument());
1157 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1158 } else if (NewNonTypeParm->hasDefaultArgument()) {
1159 SawDefaultArgument = true;
1160 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1161 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001162 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001163 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001164 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001165 TemplateTemplateParmDecl *NewTemplateParm
1166 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001167 if (NewTemplateParm->hasDefaultArgument() &&
1168 DiagnoseDefaultTemplateArgument(*this, TPC,
1169 NewTemplateParm->getLocation(),
1170 NewTemplateParm->getDefaultArgument().getSourceRange()))
1171 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1172
1173 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001174 TemplateTemplateParmDecl *OldTemplateParm
1175 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001176 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001177 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001178 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1179 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001180 SawDefaultArgument = true;
1181 RedundantDefaultArg = true;
1182 PreviousDefaultArgLoc = NewDefaultLoc;
1183 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1184 // Merge the default argument from the old declaration to the
1185 // new declaration.
1186 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001187 // FIXME: We need to create a new kind of "default argument" expression
1188 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001189 NewTemplateParm->setDefaultArgument(
1190 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001191 PreviousDefaultArgLoc
1192 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001193 } else if (NewTemplateParm->hasDefaultArgument()) {
1194 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001195 PreviousDefaultArgLoc
1196 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001197 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001198 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001199 }
1200
1201 if (RedundantDefaultArg) {
1202 // C++ [temp.param]p12:
1203 // A template-parameter shall not be given default arguments
1204 // by two different declarations in the same scope.
1205 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1206 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1207 Invalid = true;
1208 } else if (MissingDefaultArg) {
1209 // C++ [temp.param]p11:
1210 // If a template-parameter has a default template-argument,
1211 // all subsequent template-parameters shall have a default
1212 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001213 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001214 diag::err_template_param_default_arg_missing);
1215 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1216 Invalid = true;
1217 }
1218
1219 // If we have an old template parameter list that we're merging
1220 // in, move on to the next parameter.
1221 if (OldParams)
1222 ++OldParam;
1223 }
1224
1225 return Invalid;
1226}
Douglas Gregord32e0282009-02-09 23:23:08 +00001227
Mike Stump11289f42009-09-09 15:08:12 +00001228/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001229/// specifier, returning the template parameter list that applies to the
1230/// name.
1231///
1232/// \param DeclStartLoc the start of the declaration that has a scope
1233/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001234///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001235/// \param SS the scope specifier that will be matched to the given template
1236/// parameter lists. This scope specifier precedes a qualified name that is
1237/// being declared.
1238///
1239/// \param ParamLists the template parameter lists, from the outermost to the
1240/// innermost template parameter lists.
1241///
1242/// \param NumParamLists the number of template parameter lists in ParamLists.
1243///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001244/// \param IsExplicitSpecialization will be set true if the entity being
1245/// declared is an explicit specialization, false otherwise.
1246///
Mike Stump11289f42009-09-09 15:08:12 +00001247/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001248/// name that is preceded by the scope specifier @p SS. This template
1249/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001250/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001251/// template specialization), or may be NULL (if we were's declaring isn't
1252/// itself a template).
1253TemplateParameterList *
1254Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1255 const CXXScopeSpec &SS,
1256 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001257 unsigned NumParamLists,
1258 bool &IsExplicitSpecialization) {
1259 IsExplicitSpecialization = false;
1260
Douglas Gregord8d297c2009-07-21 23:53:31 +00001261 // Find the template-ids that occur within the nested-name-specifier. These
1262 // template-ids will match up with the template parameter lists.
1263 llvm::SmallVector<const TemplateSpecializationType *, 4>
1264 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001265 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1266 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001267 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1268 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +00001269 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +00001270 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1271 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1272 if (!Template)
1273 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001274
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001275 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001276 ClassTemplateSpecializationDecl *SpecDecl
1277 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1278 // If the nested name specifier refers to an explicit specialization,
1279 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001280 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1281 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001282 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001283 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001284 }
Mike Stump11289f42009-09-09 15:08:12 +00001285
Douglas Gregord8d297c2009-07-21 23:53:31 +00001286 TemplateIdsInSpecifier.push_back(SpecType);
1287 }
1288 }
Mike Stump11289f42009-09-09 15:08:12 +00001289
Douglas Gregord8d297c2009-07-21 23:53:31 +00001290 // Reverse the list of template-ids in the scope specifier, so that we can
1291 // more easily match up the template-ids and the template parameter lists.
1292 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001293
Douglas Gregord8d297c2009-07-21 23:53:31 +00001294 SourceLocation FirstTemplateLoc = DeclStartLoc;
1295 if (NumParamLists)
1296 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001297
Douglas Gregord8d297c2009-07-21 23:53:31 +00001298 // Match the template-ids found in the specifier to the template parameter
1299 // lists.
1300 unsigned Idx = 0;
1301 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1302 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001303 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1304 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001305 if (Idx >= NumParamLists) {
1306 // We have a template-id without a corresponding template parameter
1307 // list.
1308 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001309 // FIXME: the location information here isn't great.
1310 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001311 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001312 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001313 << SS.getRange();
1314 } else {
1315 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1316 << SS.getRange()
1317 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1318 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001319 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001320 }
1321 return 0;
1322 }
Mike Stump11289f42009-09-09 15:08:12 +00001323
Douglas Gregord8d297c2009-07-21 23:53:31 +00001324 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001325 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001326 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001327 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1328
Mike Stump11289f42009-09-09 15:08:12 +00001329 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001330 = dyn_cast<ClassTemplateDecl>(Template)) {
1331 TemplateParameterList *ExpectedTemplateParams = 0;
1332 // Is this template-id naming the primary template?
1333 if (Context.hasSameType(TemplateId,
1334 ClassTemplate->getInjectedClassNameType(Context)))
1335 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1336 // ... or a partial specialization?
1337 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1338 = ClassTemplate->findPartialSpecialization(TemplateId))
1339 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1340
1341 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001342 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001343 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001344 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001345 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001346
1347 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001348 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001349 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001350 diag::err_template_param_list_matches_nontemplate)
1351 << TemplateId
1352 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001353 else
1354 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001355 }
Mike Stump11289f42009-09-09 15:08:12 +00001356
Douglas Gregord8d297c2009-07-21 23:53:31 +00001357 // If there were at least as many template-ids as there were template
1358 // parameter lists, then there are no template parameter lists remaining for
1359 // the declaration itself.
1360 if (Idx >= NumParamLists)
1361 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001362
Douglas Gregord8d297c2009-07-21 23:53:31 +00001363 // If there were too many template parameter lists, complain about that now.
1364 if (Idx != NumParamLists - 1) {
1365 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001366 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001367 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001368 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1369 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001370 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1371 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001372
1373 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1374 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1375 diag::note_explicit_template_spec_does_not_need_header)
1376 << ExplicitSpecializationsInSpecifier.back();
1377 ExplicitSpecializationsInSpecifier.pop_back();
1378 }
1379
Douglas Gregord8d297c2009-07-21 23:53:31 +00001380 ++Idx;
1381 }
1382 }
Mike Stump11289f42009-09-09 15:08:12 +00001383
Douglas Gregord8d297c2009-07-21 23:53:31 +00001384 // Return the last template parameter list, which corresponds to the
1385 // entity being declared.
1386 return ParamLists[NumParamLists - 1];
1387}
1388
Douglas Gregordc572a32009-03-30 22:58:21 +00001389QualType Sema::CheckTemplateIdType(TemplateName Name,
1390 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001391 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001392 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001393 if (!Template) {
1394 // The template name does not resolve to a template, so we just
1395 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001396 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001397 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001398
Douglas Gregorc40290e2009-03-09 23:48:35 +00001399 // Check that the template argument list is well-formed for this
1400 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001401 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001402 TemplateArgs.size());
1403 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001404 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001405 return QualType();
1406
Mike Stump11289f42009-09-09 15:08:12 +00001407 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001408 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001409 "Converted template argument list is too short!");
1410
1411 QualType CanonType;
1412
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001413 if (Name.isDependent() ||
1414 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001415 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001416 // This class template specialization is a dependent
1417 // type. Therefore, its canonical type is another class template
1418 // specialization type that contains all of the converted
1419 // arguments in canonical form. This ensures that, e.g., A<T> and
1420 // A<T, T> have identical types when A is declared as:
1421 //
1422 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001423 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001424 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001425 Converted.getFlatArguments(),
1426 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001427
Douglas Gregora8e02e72009-07-28 23:00:59 +00001428 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001429 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001430 // In the future, we need to teach getTemplateSpecializationType to only
1431 // build the canonical type and return that to us.
1432 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001433 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001434 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001435 // Find the class template specialization declaration that
1436 // corresponds to these arguments.
1437 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001438 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001439 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001440 Converted.flatSize(),
1441 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001442 void *InsertPos = 0;
1443 ClassTemplateSpecializationDecl *Decl
1444 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1445 if (!Decl) {
1446 // This is the first time we have referenced this class template
1447 // specialization. Create the canonical declaration and add it to
1448 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001449 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001450 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001451 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001452 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001453 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001454 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1455 Decl->setLexicalDeclContext(CurContext);
1456 }
1457
1458 CanonType = Context.getTypeDeclType(Decl);
1459 }
Mike Stump11289f42009-09-09 15:08:12 +00001460
Douglas Gregorc40290e2009-03-09 23:48:35 +00001461 // Build the fully-sugared type for this class template
1462 // specialization, which refers back to the class template
1463 // specialization we created or found.
John McCall6b51f282009-11-23 01:53:49 +00001464 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001465}
1466
Douglas Gregor67a65642009-02-17 23:15:12 +00001467Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001468Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001469 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001470 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001471 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001472 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001473
Douglas Gregorc40290e2009-03-09 23:48:35 +00001474 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001475 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001476 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001477
John McCall6b51f282009-11-23 01:53:49 +00001478 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001479 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001480
1481 if (Result.isNull())
1482 return true;
1483
John McCall0ad16662009-10-29 08:12:44 +00001484 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1485 TemplateSpecializationTypeLoc TL
1486 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1487 TL.setTemplateNameLoc(TemplateLoc);
1488 TL.setLAngleLoc(LAngleLoc);
1489 TL.setRAngleLoc(RAngleLoc);
1490 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1491 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1492
1493 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001494}
John McCall06f6fe8d2009-09-04 01:14:41 +00001495
John McCalld8fe9af2009-09-08 17:47:29 +00001496Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1497 TagUseKind TUK,
1498 DeclSpec::TST TagSpec,
1499 SourceLocation TagLoc) {
1500 if (TypeResult.isInvalid())
1501 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001502
John McCall0ad16662009-10-29 08:12:44 +00001503 // FIXME: preserve source info, ideally without copying the DI.
1504 DeclaratorInfo *DI;
1505 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001506
John McCalld8fe9af2009-09-08 17:47:29 +00001507 // Verify the tag specifier.
1508 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001509
John McCalld8fe9af2009-09-08 17:47:29 +00001510 if (const RecordType *RT = Type->getAs<RecordType>()) {
1511 RecordDecl *D = RT->getDecl();
1512
1513 IdentifierInfo *Id = D->getIdentifier();
1514 assert(Id && "templated class must have an identifier");
1515
1516 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1517 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001518 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001519 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1520 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001521 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001522 }
1523 }
1524
John McCalld8fe9af2009-09-08 17:47:29 +00001525 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1526
1527 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001528}
1529
John McCalle66edc12009-11-24 19:00:30 +00001530Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1531 LookupResult &R,
1532 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001533 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001534 // FIXME: Can we do any checking at this point? I guess we could check the
1535 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001536 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001537 // though.
John McCalle66edc12009-11-24 19:00:30 +00001538
1539 // These should be filtered out by our callers.
1540 assert(!R.empty() && "empty lookup results when building templateid");
1541 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1542
1543 NestedNameSpecifier *Qualifier = 0;
1544 SourceRange QualifierRange;
1545 if (SS.isSet()) {
1546 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1547 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001548 }
1549
John McCalle66edc12009-11-24 19:00:30 +00001550 bool Dependent
1551 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1552 &TemplateArgs);
1553 UnresolvedLookupExpr *ULE
1554 = UnresolvedLookupExpr::Create(Context, Dependent,
1555 Qualifier, QualifierRange,
1556 R.getLookupName(), R.getNameLoc(),
1557 RequiresADL, TemplateArgs);
1558 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1559 ULE->addDecl(*I);
1560
1561 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001562}
1563
John McCalle66edc12009-11-24 19:00:30 +00001564// We actually only call this from template instantiation.
1565Sema::OwningExprResult
1566Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1567 DeclarationName Name,
1568 SourceLocation NameLoc,
1569 const TemplateArgumentListInfo &TemplateArgs) {
1570 DeclContext *DC;
1571 if (!(DC = computeDeclContext(SS, false)) ||
1572 DC->isDependentContext() ||
1573 RequireCompleteDeclContext(SS))
1574 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001575
John McCalle66edc12009-11-24 19:00:30 +00001576 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1577 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00001578
John McCalle66edc12009-11-24 19:00:30 +00001579 if (R.isAmbiguous())
1580 return ExprError();
1581
1582 if (R.empty()) {
1583 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1584 << Name << SS.getRange();
1585 return ExprError();
1586 }
1587
1588 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1589 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1590 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1591 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1592 return ExprError();
1593 }
1594
1595 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001596}
1597
Douglas Gregorb67535d2009-03-31 00:43:58 +00001598/// \brief Form a dependent template name.
1599///
1600/// This action forms a dependent template name given the template
1601/// name and its (presumably dependent) scope specifier. For
1602/// example, given "MetaFun::template apply", the scope specifier \p
1603/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1604/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001605Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001606Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001607 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001608 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001609 TypeTy *ObjectType,
1610 bool EnteringContext) {
Mike Stump11289f42009-09-09 15:08:12 +00001611 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001612 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001613 (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001614 // C++0x [temp.names]p5:
1615 // If a name prefixed by the keyword template is not the name of
1616 // a template, the program is ill-formed. [Note: the keyword
1617 // template may not be applied to non-template members of class
1618 // templates. -end note ] [ Note: as is the case with the
1619 // typename prefix, the template prefix is allowed in cases
1620 // where it is not strictly necessary; i.e., when the
1621 // nested-name-specifier or the expression on the left of the ->
1622 // or . is not dependent on a template-parameter, or the use
1623 // does not appear in the scope of a template. -end note]
1624 //
1625 // Note: C++03 was more strict here, because it banned the use of
1626 // the "template" keyword prior to a template-name that was not a
1627 // dependent name. C++ DR468 relaxed this requirement (the
1628 // "template" keyword is now permitted). We follow the C++0x
1629 // rules, even in C++03 mode, retroactively applying the DR.
1630 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001631 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001632 EnteringContext, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001633 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001634 Diag(Name.getSourceRange().getBegin(),
1635 diag::err_template_kw_refers_to_non_template)
1636 << GetNameFromUnqualifiedId(Name)
1637 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001638 return TemplateTy();
1639 }
1640
1641 return Template;
1642 }
1643
Mike Stump11289f42009-09-09 15:08:12 +00001644 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001645 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001646
1647 switch (Name.getKind()) {
1648 case UnqualifiedId::IK_Identifier:
1649 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1650 Name.Identifier));
1651
Douglas Gregor71395fa2009-11-04 00:56:37 +00001652 case UnqualifiedId::IK_OperatorFunctionId:
1653 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1654 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001655
1656 case UnqualifiedId::IK_LiteralOperatorId:
1657 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1658
Douglas Gregor3cf81312009-11-03 23:16:33 +00001659 default:
1660 break;
1661 }
1662
1663 Diag(Name.getSourceRange().getBegin(),
1664 diag::err_template_kw_refers_to_non_template)
1665 << GetNameFromUnqualifiedId(Name)
1666 << Name.getSourceRange();
1667 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001668}
1669
Mike Stump11289f42009-09-09 15:08:12 +00001670bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001671 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001672 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001673 const TemplateArgument &Arg = AL.getArgument();
1674
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001675 // Check template type parameter.
1676 if (Arg.getKind() != TemplateArgument::Type) {
1677 // C++ [temp.arg.type]p1:
1678 // A template-argument for a template-parameter which is a
1679 // type shall be a type-id.
1680
1681 // We have a template type parameter but the template argument
1682 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001683 SourceRange SR = AL.getSourceRange();
1684 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001685 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001686
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001687 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001688 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001689
John McCall0ad16662009-10-29 08:12:44 +00001690 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001691 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001692
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001693 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001694 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001695 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001696 return false;
1697}
1698
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001699/// \brief Substitute template arguments into the default template argument for
1700/// the given template type parameter.
1701///
1702/// \param SemaRef the semantic analysis object for which we are performing
1703/// the substitution.
1704///
1705/// \param Template the template that we are synthesizing template arguments
1706/// for.
1707///
1708/// \param TemplateLoc the location of the template name that started the
1709/// template-id we are checking.
1710///
1711/// \param RAngleLoc the location of the right angle bracket ('>') that
1712/// terminates the template-id.
1713///
1714/// \param Param the template template parameter whose default we are
1715/// substituting into.
1716///
1717/// \param Converted the list of template arguments provided for template
1718/// parameters that precede \p Param in the template parameter list.
1719///
1720/// \returns the substituted template argument, or NULL if an error occurred.
1721static DeclaratorInfo *
1722SubstDefaultTemplateArgument(Sema &SemaRef,
1723 TemplateDecl *Template,
1724 SourceLocation TemplateLoc,
1725 SourceLocation RAngleLoc,
1726 TemplateTypeParmDecl *Param,
1727 TemplateArgumentListBuilder &Converted) {
1728 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1729
1730 // If the argument type is dependent, instantiate it now based
1731 // on the previously-computed template arguments.
1732 if (ArgType->getType()->isDependentType()) {
1733 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1734 /*TakeArgs=*/false);
1735
1736 MultiLevelTemplateArgumentList AllTemplateArgs
1737 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1738
1739 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1740 Template, Converted.getFlatArguments(),
1741 Converted.flatSize(),
1742 SourceRange(TemplateLoc, RAngleLoc));
1743
1744 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1745 Param->getDefaultArgumentLoc(),
1746 Param->getDeclName());
1747 }
1748
1749 return ArgType;
1750}
1751
1752/// \brief Substitute template arguments into the default template argument for
1753/// the given non-type template parameter.
1754///
1755/// \param SemaRef the semantic analysis object for which we are performing
1756/// the substitution.
1757///
1758/// \param Template the template that we are synthesizing template arguments
1759/// for.
1760///
1761/// \param TemplateLoc the location of the template name that started the
1762/// template-id we are checking.
1763///
1764/// \param RAngleLoc the location of the right angle bracket ('>') that
1765/// terminates the template-id.
1766///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001767/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001768/// substituting into.
1769///
1770/// \param Converted the list of template arguments provided for template
1771/// parameters that precede \p Param in the template parameter list.
1772///
1773/// \returns the substituted template argument, or NULL if an error occurred.
1774static Sema::OwningExprResult
1775SubstDefaultTemplateArgument(Sema &SemaRef,
1776 TemplateDecl *Template,
1777 SourceLocation TemplateLoc,
1778 SourceLocation RAngleLoc,
1779 NonTypeTemplateParmDecl *Param,
1780 TemplateArgumentListBuilder &Converted) {
1781 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1782 /*TakeArgs=*/false);
1783
1784 MultiLevelTemplateArgumentList AllTemplateArgs
1785 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1786
1787 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1788 Template, Converted.getFlatArguments(),
1789 Converted.flatSize(),
1790 SourceRange(TemplateLoc, RAngleLoc));
1791
1792 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1793}
1794
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001795/// \brief Substitute template arguments into the default template argument for
1796/// the given template template parameter.
1797///
1798/// \param SemaRef the semantic analysis object for which we are performing
1799/// the substitution.
1800///
1801/// \param Template the template that we are synthesizing template arguments
1802/// for.
1803///
1804/// \param TemplateLoc the location of the template name that started the
1805/// template-id we are checking.
1806///
1807/// \param RAngleLoc the location of the right angle bracket ('>') that
1808/// terminates the template-id.
1809///
1810/// \param Param the template template parameter whose default we are
1811/// substituting into.
1812///
1813/// \param Converted the list of template arguments provided for template
1814/// parameters that precede \p Param in the template parameter list.
1815///
1816/// \returns the substituted template argument, or NULL if an error occurred.
1817static TemplateName
1818SubstDefaultTemplateArgument(Sema &SemaRef,
1819 TemplateDecl *Template,
1820 SourceLocation TemplateLoc,
1821 SourceLocation RAngleLoc,
1822 TemplateTemplateParmDecl *Param,
1823 TemplateArgumentListBuilder &Converted) {
1824 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1825 /*TakeArgs=*/false);
1826
1827 MultiLevelTemplateArgumentList AllTemplateArgs
1828 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1829
1830 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1831 Template, Converted.getFlatArguments(),
1832 Converted.flatSize(),
1833 SourceRange(TemplateLoc, RAngleLoc));
1834
1835 return SemaRef.SubstTemplateName(
1836 Param->getDefaultArgument().getArgument().getAsTemplate(),
1837 Param->getDefaultArgument().getTemplateNameLoc(),
1838 AllTemplateArgs);
1839}
1840
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001841/// \brief If the given template parameter has a default template
1842/// argument, substitute into that default template argument and
1843/// return the corresponding template argument.
1844TemplateArgumentLoc
1845Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1846 SourceLocation TemplateLoc,
1847 SourceLocation RAngleLoc,
1848 Decl *Param,
1849 TemplateArgumentListBuilder &Converted) {
1850 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1851 if (!TypeParm->hasDefaultArgument())
1852 return TemplateArgumentLoc();
1853
1854 DeclaratorInfo *DI = SubstDefaultTemplateArgument(*this, Template,
1855 TemplateLoc,
1856 RAngleLoc,
1857 TypeParm,
1858 Converted);
1859 if (DI)
1860 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1861
1862 return TemplateArgumentLoc();
1863 }
1864
1865 if (NonTypeTemplateParmDecl *NonTypeParm
1866 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1867 if (!NonTypeParm->hasDefaultArgument())
1868 return TemplateArgumentLoc();
1869
1870 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1871 TemplateLoc,
1872 RAngleLoc,
1873 NonTypeParm,
1874 Converted);
1875 if (Arg.isInvalid())
1876 return TemplateArgumentLoc();
1877
1878 Expr *ArgE = Arg.takeAs<Expr>();
1879 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1880 }
1881
1882 TemplateTemplateParmDecl *TempTempParm
1883 = cast<TemplateTemplateParmDecl>(Param);
1884 if (!TempTempParm->hasDefaultArgument())
1885 return TemplateArgumentLoc();
1886
1887 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1888 TemplateLoc,
1889 RAngleLoc,
1890 TempTempParm,
1891 Converted);
1892 if (TName.isNull())
1893 return TemplateArgumentLoc();
1894
1895 return TemplateArgumentLoc(TemplateArgument(TName),
1896 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1897 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1898}
1899
Douglas Gregorda0fb532009-11-11 19:31:23 +00001900/// \brief Check that the given template argument corresponds to the given
1901/// template parameter.
1902bool Sema::CheckTemplateArgument(NamedDecl *Param,
1903 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001904 TemplateDecl *Template,
1905 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001906 SourceLocation RAngleLoc,
1907 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001908 // Check template type parameters.
1909 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001910 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001911
Douglas Gregoreebed722009-11-11 19:41:09 +00001912 // Check non-type template parameters.
1913 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001914 // Do substitution on the type of the non-type template parameter
1915 // with the template arguments we've seen thus far.
1916 QualType NTTPType = NTTP->getType();
1917 if (NTTPType->isDependentType()) {
1918 // Do substitution on the type of the non-type template parameter.
1919 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1920 NTTP, Converted.getFlatArguments(),
1921 Converted.flatSize(),
1922 SourceRange(TemplateLoc, RAngleLoc));
1923
1924 TemplateArgumentList TemplateArgs(Context, Converted,
1925 /*TakeArgs=*/false);
1926 NTTPType = SubstType(NTTPType,
1927 MultiLevelTemplateArgumentList(TemplateArgs),
1928 NTTP->getLocation(),
1929 NTTP->getDeclName());
1930 // If that worked, check the non-type template parameter type
1931 // for validity.
1932 if (!NTTPType.isNull())
1933 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1934 NTTP->getLocation());
1935 if (NTTPType.isNull())
1936 return true;
1937 }
1938
1939 switch (Arg.getArgument().getKind()) {
1940 case TemplateArgument::Null:
1941 assert(false && "Should never see a NULL template argument here");
1942 return true;
1943
1944 case TemplateArgument::Expression: {
1945 Expr *E = Arg.getArgument().getAsExpr();
1946 TemplateArgument Result;
1947 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1948 return true;
1949
1950 Converted.Append(Result);
1951 break;
1952 }
1953
1954 case TemplateArgument::Declaration:
1955 case TemplateArgument::Integral:
1956 // We've already checked this template argument, so just copy
1957 // it to the list of converted arguments.
1958 Converted.Append(Arg.getArgument());
1959 break;
1960
1961 case TemplateArgument::Template:
1962 // We were given a template template argument. It may not be ill-formed;
1963 // see below.
1964 if (DependentTemplateName *DTN
1965 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1966 // We have a template argument such as \c T::template X, which we
1967 // parsed as a template template argument. However, since we now
1968 // know that we need a non-type template argument, convert this
1969 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00001970 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1971 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00001972 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00001973 DTN->getIdentifier(),
1974 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00001975
1976 TemplateArgument Result;
1977 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1978 return true;
1979
1980 Converted.Append(Result);
1981 break;
1982 }
1983
1984 // We have a template argument that actually does refer to a class
1985 // template, template alias, or template template parameter, and
1986 // therefore cannot be a non-type template argument.
1987 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1988 << Arg.getSourceRange();
1989
1990 Diag(Param->getLocation(), diag::note_template_param_here);
1991 return true;
1992
1993 case TemplateArgument::Type: {
1994 // We have a non-type template parameter but the template
1995 // argument is a type.
1996
1997 // C++ [temp.arg]p2:
1998 // In a template-argument, an ambiguity between a type-id and
1999 // an expression is resolved to a type-id, regardless of the
2000 // form of the corresponding template-parameter.
2001 //
2002 // We warn specifically about this case, since it can be rather
2003 // confusing for users.
2004 QualType T = Arg.getArgument().getAsType();
2005 SourceRange SR = Arg.getSourceRange();
2006 if (T->isFunctionType())
2007 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2008 else
2009 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2010 Diag(Param->getLocation(), diag::note_template_param_here);
2011 return true;
2012 }
2013
2014 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00002015 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002016 break;
2017 }
2018
2019 return false;
2020 }
2021
2022
2023 // Check template template parameters.
2024 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2025
2026 // Substitute into the template parameter list of the template
2027 // template parameter, since previously-supplied template arguments
2028 // may appear within the template template parameter.
2029 {
2030 // Set up a template instantiation context.
2031 LocalInstantiationScope Scope(*this);
2032 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2033 TempParm, Converted.getFlatArguments(),
2034 Converted.flatSize(),
2035 SourceRange(TemplateLoc, RAngleLoc));
2036
2037 TemplateArgumentList TemplateArgs(Context, Converted,
2038 /*TakeArgs=*/false);
2039 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2040 SubstDecl(TempParm, CurContext,
2041 MultiLevelTemplateArgumentList(TemplateArgs)));
2042 if (!TempParm)
2043 return true;
2044
2045 // FIXME: TempParam is leaked.
2046 }
2047
2048 switch (Arg.getArgument().getKind()) {
2049 case TemplateArgument::Null:
2050 assert(false && "Should never see a NULL template argument here");
2051 return true;
2052
2053 case TemplateArgument::Template:
2054 if (CheckTemplateArgument(TempParm, Arg))
2055 return true;
2056
2057 Converted.Append(Arg.getArgument());
2058 break;
2059
2060 case TemplateArgument::Expression:
2061 case TemplateArgument::Type:
2062 // We have a template template parameter but the template
2063 // argument does not refer to a template.
2064 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2065 return true;
2066
2067 case TemplateArgument::Declaration:
2068 llvm::llvm_unreachable(
2069 "Declaration argument with template template parameter");
2070 break;
2071 case TemplateArgument::Integral:
2072 llvm::llvm_unreachable(
2073 "Integral argument with template template parameter");
2074 break;
2075
2076 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00002077 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002078 break;
2079 }
2080
2081 return false;
2082}
2083
Douglas Gregord32e0282009-02-09 23:23:08 +00002084/// \brief Check that the given template argument list is well-formed
2085/// for specializing the given template.
2086bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2087 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002088 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002089 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002090 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002091 TemplateParameterList *Params = Template->getTemplateParameters();
2092 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002093 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002094 bool Invalid = false;
2095
John McCall6b51f282009-11-23 01:53:49 +00002096 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2097
Mike Stump11289f42009-09-09 15:08:12 +00002098 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002099 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002100
Anders Carlsson15201f12009-06-13 02:08:00 +00002101 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002102 (NumArgs < Params->getMinRequiredArguments() &&
2103 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002104 // FIXME: point at either the first arg beyond what we can handle,
2105 // or the '>', depending on whether we have too many or too few
2106 // arguments.
2107 SourceRange Range;
2108 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002109 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002110 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2111 << (NumArgs > NumParams)
2112 << (isa<ClassTemplateDecl>(Template)? 0 :
2113 isa<FunctionTemplateDecl>(Template)? 1 :
2114 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2115 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002116 Diag(Template->getLocation(), diag::note_template_decl_here)
2117 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002118 Invalid = true;
2119 }
Mike Stump11289f42009-09-09 15:08:12 +00002120
2121 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002122 // [...] The type and form of each template-argument specified in
2123 // a template-id shall match the type and form specified for the
2124 // corresponding parameter declared by the template in its
2125 // template-parameter-list.
2126 unsigned ArgIdx = 0;
2127 for (TemplateParameterList::iterator Param = Params->begin(),
2128 ParamEnd = Params->end();
2129 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002130 if (ArgIdx > NumArgs && PartialTemplateArgs)
2131 break;
Mike Stump11289f42009-09-09 15:08:12 +00002132
Douglas Gregoreebed722009-11-11 19:41:09 +00002133 // If we have a template parameter pack, check every remaining template
2134 // argument against that template parameter pack.
2135 if ((*Param)->isTemplateParameterPack()) {
2136 Converted.BeginPack();
2137 for (; ArgIdx < NumArgs; ++ArgIdx) {
2138 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2139 TemplateLoc, RAngleLoc, Converted)) {
2140 Invalid = true;
2141 break;
2142 }
2143 }
2144 Converted.EndPack();
2145 continue;
2146 }
2147
Douglas Gregor84d49a22009-11-11 21:54:23 +00002148 if (ArgIdx < NumArgs) {
2149 // Check the template argument we were given.
2150 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2151 TemplateLoc, RAngleLoc, Converted))
2152 return true;
2153
2154 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002155 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002156
Douglas Gregor84d49a22009-11-11 21:54:23 +00002157 // We have a default template argument that we will use.
2158 TemplateArgumentLoc Arg;
2159
2160 // Retrieve the default template argument from the template
2161 // parameter. For each kind of template parameter, we substitute the
2162 // template arguments provided thus far and any "outer" template arguments
2163 // (when the template parameter was part of a nested template) into
2164 // the default argument.
2165 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2166 if (!TTP->hasDefaultArgument()) {
2167 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2168 break;
2169 }
2170
2171 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
2172 Template,
2173 TemplateLoc,
2174 RAngleLoc,
2175 TTP,
2176 Converted);
2177 if (!ArgType)
2178 return true;
2179
2180 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2181 ArgType);
2182 } else if (NonTypeTemplateParmDecl *NTTP
2183 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2184 if (!NTTP->hasDefaultArgument()) {
2185 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2186 break;
2187 }
2188
2189 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2190 TemplateLoc,
2191 RAngleLoc,
2192 NTTP,
2193 Converted);
2194 if (E.isInvalid())
2195 return true;
2196
2197 Expr *Ex = E.takeAs<Expr>();
2198 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2199 } else {
2200 TemplateTemplateParmDecl *TempParm
2201 = cast<TemplateTemplateParmDecl>(*Param);
2202
2203 if (!TempParm->hasDefaultArgument()) {
2204 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2205 break;
2206 }
2207
2208 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2209 TemplateLoc,
2210 RAngleLoc,
2211 TempParm,
2212 Converted);
2213 if (Name.isNull())
2214 return true;
2215
2216 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2217 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2218 TempParm->getDefaultArgument().getTemplateNameLoc());
2219 }
2220
2221 // Introduce an instantiation record that describes where we are using
2222 // the default template argument.
2223 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2224 Converted.getFlatArguments(),
2225 Converted.flatSize(),
2226 SourceRange(TemplateLoc, RAngleLoc));
2227
2228 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002229 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002230 RAngleLoc, Converted))
2231 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002232 }
2233
2234 return Invalid;
2235}
2236
2237/// \brief Check a template argument against its corresponding
2238/// template type parameter.
2239///
2240/// This routine implements the semantics of C++ [temp.arg.type]. It
2241/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002242bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00002243 DeclaratorInfo *ArgInfo) {
2244 assert(ArgInfo && "invalid DeclaratorInfo");
2245 QualType Arg = ArgInfo->getType();
2246
Douglas Gregord32e0282009-02-09 23:23:08 +00002247 // C++ [temp.arg.type]p2:
2248 // A local type, a type with no linkage, an unnamed type or a type
2249 // compounded from any of these types shall not be used as a
2250 // template-argument for a template type-parameter.
2251 //
2252 // FIXME: Perform the recursive and no-linkage type checks.
2253 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002254 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002255 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002256 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002257 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002258 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2259 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2260 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2261 << QualType(Tag, 0) << SR;
2262 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002263 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002264 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2265 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002266 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2267 return true;
2268 }
2269
2270 return false;
2271}
2272
Douglas Gregorccb07762009-02-11 19:52:55 +00002273/// \brief Checks whether the given template argument is the address
2274/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002275bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2276 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002277 bool Invalid = false;
2278
2279 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002280 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002281 Arg = Cast->getSubExpr();
2282
Sebastian Redl576fd422009-05-10 18:38:11 +00002283 // C++0x allows nullptr, and there's no further checking to be done for that.
2284 if (Arg->getType()->isNullPtrType())
2285 return false;
2286
Douglas Gregorccb07762009-02-11 19:52:55 +00002287 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002288 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002289 // A template-argument for a non-type, non-template
2290 // template-parameter shall be one of: [...]
2291 //
2292 // -- the address of an object or function with external
2293 // linkage, including function templates and function
2294 // template-ids but excluding non-static class members,
2295 // expressed as & id-expression where the & is optional if
2296 // the name refers to a function or array, or if the
2297 // corresponding template-parameter is a reference; or
2298 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002299
Douglas Gregorccb07762009-02-11 19:52:55 +00002300 // Ignore (and complain about) any excess parentheses.
2301 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2302 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002303 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002304 diag::err_template_arg_extra_parens)
2305 << Arg->getSourceRange();
2306 Invalid = true;
2307 }
2308
2309 Arg = Parens->getSubExpr();
2310 }
2311
2312 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2313 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2314 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2315 } else
2316 DRE = dyn_cast<DeclRefExpr>(Arg);
2317
2318 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002319 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002320 diag::err_template_arg_not_object_or_func_form)
2321 << Arg->getSourceRange();
2322
2323 // Cannot refer to non-static data members
2324 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2325 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2326 << Field << Arg->getSourceRange();
2327
2328 // Cannot refer to non-static member functions
2329 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2330 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002331 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002332 diag::err_template_arg_method)
2333 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002334
Douglas Gregorccb07762009-02-11 19:52:55 +00002335 // Functions must have external linkage.
2336 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregorf73b2822009-11-25 22:24:25 +00002337 if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump11289f42009-09-09 15:08:12 +00002338 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002339 diag::err_template_arg_function_not_extern)
2340 << Func << Arg->getSourceRange();
2341 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2342 << true;
2343 return true;
2344 }
2345
2346 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002347 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002348 return Invalid;
2349 }
2350
2351 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregorf73b2822009-11-25 22:24:25 +00002352 if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump11289f42009-09-09 15:08:12 +00002353 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002354 diag::err_template_arg_object_not_extern)
2355 << Var << Arg->getSourceRange();
2356 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2357 << true;
2358 return true;
2359 }
2360
2361 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002362 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002363 return Invalid;
2364 }
Mike Stump11289f42009-09-09 15:08:12 +00002365
Douglas Gregorccb07762009-02-11 19:52:55 +00002366 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002367 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002368 diag::err_template_arg_not_object_or_func)
2369 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002370 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002371 diag::note_template_arg_refers_here);
2372 return true;
2373}
2374
2375/// \brief Checks whether the given template argument is a pointer to
2376/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002377bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2378 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002379 bool Invalid = false;
2380
2381 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002382 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002383 Arg = Cast->getSubExpr();
2384
Sebastian Redl576fd422009-05-10 18:38:11 +00002385 // C++0x allows nullptr, and there's no further checking to be done for that.
2386 if (Arg->getType()->isNullPtrType())
2387 return false;
2388
Douglas Gregorccb07762009-02-11 19:52:55 +00002389 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002390 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002391 // A template-argument for a non-type, non-template
2392 // template-parameter shall be one of: [...]
2393 //
2394 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002395 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002396
2397 // Ignore (and complain about) any excess parentheses.
2398 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2399 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002400 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002401 diag::err_template_arg_extra_parens)
2402 << Arg->getSourceRange();
2403 Invalid = true;
2404 }
2405
2406 Arg = Parens->getSubExpr();
2407 }
2408
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002409 // A pointer-to-member constant written &Class::member.
2410 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002411 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2412 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2413 if (DRE && !DRE->getQualifier())
2414 DRE = 0;
2415 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002416 }
2417 // A constant of pointer-to-member type.
2418 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2419 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2420 if (VD->getType()->isMemberPointerType()) {
2421 if (isa<NonTypeTemplateParmDecl>(VD) ||
2422 (isa<VarDecl>(VD) &&
2423 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2424 if (Arg->isTypeDependent() || Arg->isValueDependent())
2425 Converted = TemplateArgument(Arg->Retain());
2426 else
2427 Converted = TemplateArgument(VD->getCanonicalDecl());
2428 return Invalid;
2429 }
2430 }
2431 }
2432
2433 DRE = 0;
2434 }
2435
Douglas Gregorccb07762009-02-11 19:52:55 +00002436 if (!DRE)
2437 return Diag(Arg->getSourceRange().getBegin(),
2438 diag::err_template_arg_not_pointer_to_member_form)
2439 << Arg->getSourceRange();
2440
2441 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2442 assert((isa<FieldDecl>(DRE->getDecl()) ||
2443 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2444 "Only non-static member pointers can make it here");
2445
2446 // Okay: this is the address of a non-static member, and therefore
2447 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002448 if (Arg->isTypeDependent() || Arg->isValueDependent())
2449 Converted = TemplateArgument(Arg->Retain());
2450 else
2451 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002452 return Invalid;
2453 }
2454
2455 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002456 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002457 diag::err_template_arg_not_pointer_to_member_form)
2458 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002459 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002460 diag::note_template_arg_refers_here);
2461 return true;
2462}
2463
Douglas Gregord32e0282009-02-09 23:23:08 +00002464/// \brief Check a template argument against its corresponding
2465/// non-type template parameter.
2466///
Douglas Gregor463421d2009-03-03 04:44:36 +00002467/// This routine implements the semantics of C++ [temp.arg.nontype].
2468/// It returns true if an error occurred, and false otherwise. \p
2469/// InstantiatedParamType is the type of the non-type template
2470/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002471///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002472/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002473bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002474 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002475 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002476 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2477
Douglas Gregor86560402009-02-10 23:36:10 +00002478 // If either the parameter has a dependent type or the argument is
2479 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002480 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002481 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2482 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002483 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002484 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002485 }
Douglas Gregor86560402009-02-10 23:36:10 +00002486
2487 // C++ [temp.arg.nontype]p5:
2488 // The following conversions are performed on each expression used
2489 // as a non-type template-argument. If a non-type
2490 // template-argument cannot be converted to the type of the
2491 // corresponding template-parameter then the program is
2492 // ill-formed.
2493 //
2494 // -- for a non-type template-parameter of integral or
2495 // enumeration type, integral promotions (4.5) and integral
2496 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002497 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002498 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002499 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002500 // C++ [temp.arg.nontype]p1:
2501 // A template-argument for a non-type, non-template
2502 // template-parameter shall be one of:
2503 //
2504 // -- an integral constant-expression of integral or enumeration
2505 // type; or
2506 // -- the name of a non-type template-parameter; or
2507 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002508 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002509 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002510 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002511 diag::err_template_arg_not_integral_or_enumeral)
2512 << ArgType << Arg->getSourceRange();
2513 Diag(Param->getLocation(), diag::note_template_param_here);
2514 return true;
2515 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002516 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002517 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2518 << ArgType << Arg->getSourceRange();
2519 return true;
2520 }
2521
2522 // FIXME: We need some way to more easily get the unqualified form
2523 // of the types without going all the way to the
2524 // canonical type.
2525 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2526 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2527 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2528 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2529
2530 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002531 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002532 // Okay: no conversion necessary
2533 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2534 !ParamType->isEnumeralType()) {
2535 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002536 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002537 } else {
2538 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002539 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002540 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002541 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002542 Diag(Param->getLocation(), diag::note_template_param_here);
2543 return true;
2544 }
2545
Douglas Gregor52aba872009-03-14 00:20:21 +00002546 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002547 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002548 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002549
2550 if (!Arg->isValueDependent()) {
2551 // Check that an unsigned parameter does not receive a negative
2552 // value.
2553 if (IntegerType->isUnsignedIntegerType()
2554 && (Value.isSigned() && Value.isNegative())) {
2555 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2556 << Value.toString(10) << Param->getType()
2557 << Arg->getSourceRange();
2558 Diag(Param->getLocation(), diag::note_template_param_here);
2559 return true;
2560 }
2561
2562 // Check that we don't overflow the template parameter type.
2563 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2564 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002565 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002566 diag::err_template_arg_too_large)
2567 << Value.toString(10) << Param->getType()
2568 << Arg->getSourceRange();
2569 Diag(Param->getLocation(), diag::note_template_param_here);
2570 return true;
2571 }
2572
2573 if (Value.getBitWidth() != AllowedBits)
2574 Value.extOrTrunc(AllowedBits);
2575 Value.setIsSigned(IntegerType->isSignedIntegerType());
2576 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002577
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002578 // Add the value of this argument to the list of converted
2579 // arguments. We use the bitwidth and signedness of the template
2580 // parameter.
2581 if (Arg->isValueDependent()) {
2582 // The argument is value-dependent. Create a new
2583 // TemplateArgument with the converted expression.
2584 Converted = TemplateArgument(Arg);
2585 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002586 }
2587
John McCall0ad16662009-10-29 08:12:44 +00002588 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002589 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002590 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002591 return false;
2592 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002593
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002594 // Handle pointer-to-function, reference-to-function, and
2595 // pointer-to-member-function all in (roughly) the same way.
2596 if (// -- For a non-type template-parameter of type pointer to
2597 // function, only the function-to-pointer conversion (4.3) is
2598 // applied. If the template-argument represents a set of
2599 // overloaded functions (or a pointer to such), the matching
2600 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002601 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002602 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002603 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002604 // -- For a non-type template-parameter of type reference to
2605 // function, no conversions apply. If the template-argument
2606 // represents a set of overloaded functions, the matching
2607 // function is selected from the set (13.4).
2608 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002609 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002610 // -- For a non-type template-parameter of type pointer to
2611 // member function, no conversions apply. If the
2612 // template-argument represents a set of overloaded member
2613 // functions, the matching member function is selected from
2614 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002615 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002616 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002617 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002618 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002619 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002620 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002621 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002622 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2623 ParamType->isMemberPointerType())) {
2624 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002625 if (ParamType->isMemberPointerType())
2626 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2627 else
2628 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002629 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002630 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002631 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002632 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002633 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002634 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2635 return true;
2636
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002637 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002638 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002639 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002640 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002641 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002642 }
2643 }
2644
Mike Stump11289f42009-09-09 15:08:12 +00002645 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002646 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002647 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002648 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002649 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002650 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002651 Diag(Param->getLocation(), diag::note_template_param_here);
2652 return true;
2653 }
Mike Stump11289f42009-09-09 15:08:12 +00002654
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002655 if (ParamType->isMemberPointerType())
2656 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002657
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002658 NamedDecl *Entity = 0;
2659 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2660 return true;
2661
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002662 if (Entity)
2663 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002664 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002665 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002666 }
2667
Chris Lattner696197c2009-02-20 21:37:53 +00002668 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002669 // -- for a non-type template-parameter of type pointer to
2670 // object, qualification conversions (4.4) and the
2671 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002672 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002673 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002674 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002675
Sebastian Redl576fd422009-05-10 18:38:11 +00002676 if (ArgType->isNullPtrType()) {
2677 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002678 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002679 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002680 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002681 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002682 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002683
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002684 if (IsQualificationConversion(ArgType, ParamType)) {
2685 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002686 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002687 }
Mike Stump11289f42009-09-09 15:08:12 +00002688
Douglas Gregor1515f762009-02-11 18:22:40 +00002689 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002690 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002691 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002692 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002693 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002694 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 if (Entity)
2703 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002704 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002705 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002706 }
Mike Stump11289f42009-09-09 15:08:12 +00002707
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002708 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002709 // -- For a non-type template-parameter of type reference to
2710 // object, no conversions apply. The type referred to by the
2711 // reference may be more cv-qualified than the (otherwise
2712 // identical) type of the template-argument. The
2713 // template-parameter is bound directly to the
2714 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002715 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002716 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002717
Douglas Gregor1515f762009-02-11 18:22:40 +00002718 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002719 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002720 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002721 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002722 << Arg->getSourceRange();
2723 Diag(Param->getLocation(), diag::note_template_param_here);
2724 return true;
2725 }
2726
Mike Stump11289f42009-09-09 15:08:12 +00002727 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002728 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2729 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002730
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002731 if ((ParamQuals | ArgQuals) != ParamQuals) {
2732 Diag(Arg->getSourceRange().getBegin(),
2733 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002734 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002735 << Arg->getSourceRange();
2736 Diag(Param->getLocation(), diag::note_template_param_here);
2737 return true;
2738 }
Mike Stump11289f42009-09-09 15:08:12 +00002739
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002740 NamedDecl *Entity = 0;
2741 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2742 return true;
2743
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002744 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002745 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002746 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002747 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002748
2749 // -- For a non-type template-parameter of type pointer to data
2750 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002751 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002752 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2753
Douglas Gregor1515f762009-02-11 18:22:40 +00002754 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002755 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002756 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002757 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002758 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002759 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002760 } else {
2761 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002762 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002763 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002764 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002765 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002766 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002767 }
2768
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002769 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002770}
2771
2772/// \brief Check a template argument against its corresponding
2773/// template template parameter.
2774///
2775/// This routine implements the semantics of C++ [temp.arg.template].
2776/// It returns true if an error occurred, and false otherwise.
2777bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002778 const TemplateArgumentLoc &Arg) {
2779 TemplateName Name = Arg.getArgument().getAsTemplate();
2780 TemplateDecl *Template = Name.getAsTemplateDecl();
2781 if (!Template) {
2782 // Any dependent template name is fine.
2783 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2784 return false;
2785 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002786
2787 // C++ [temp.arg.template]p1:
2788 // A template-argument for a template template-parameter shall be
2789 // the name of a class template, expressed as id-expression. Only
2790 // primary class templates are considered when matching the
2791 // template template argument with the corresponding parameter;
2792 // partial specializations are not considered even if their
2793 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002794 //
2795 // Note that we also allow template template parameters here, which
2796 // will happen when we are dealing with, e.g., class template
2797 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002798 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002799 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002800 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002801 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002802 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002803 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002804 << Template;
2805 }
2806
2807 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2808 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002809 true,
2810 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002811 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002812}
2813
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002814/// \brief Determine whether the given template parameter lists are
2815/// equivalent.
2816///
Mike Stump11289f42009-09-09 15:08:12 +00002817/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002818/// source code as part of a new template declaration.
2819///
2820/// \param Old The old template parameter list, typically found via
2821/// name lookup of the template declared with this template parameter
2822/// list.
2823///
2824/// \param Complain If true, this routine will produce a diagnostic if
2825/// the template parameter lists are not equivalent.
2826///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002827/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00002828///
2829/// \param TemplateArgLoc If this source location is valid, then we
2830/// are actually checking the template parameter list of a template
2831/// argument (New) against the template parameter list of its
2832/// corresponding template template parameter (Old). We produce
2833/// slightly different diagnostics in this scenario.
2834///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002835/// \returns True if the template parameter lists are equal, false
2836/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002837bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002838Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2839 TemplateParameterList *Old,
2840 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002841 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002842 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002843 if (Old->size() != New->size()) {
2844 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002845 unsigned NextDiag = diag::err_template_param_list_different_arity;
2846 if (TemplateArgLoc.isValid()) {
2847 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2848 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002849 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002850 Diag(New->getTemplateLoc(), NextDiag)
2851 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002852 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002853 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002854 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002855 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002856 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2857 }
2858
2859 return false;
2860 }
2861
2862 for (TemplateParameterList::iterator OldParm = Old->begin(),
2863 OldParmEnd = Old->end(), NewParm = New->begin();
2864 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2865 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002866 if (Complain) {
2867 unsigned NextDiag = diag::err_template_param_different_kind;
2868 if (TemplateArgLoc.isValid()) {
2869 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2870 NextDiag = diag::note_template_param_different_kind;
2871 }
2872 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002873 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00002874 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002875 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00002876 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002877 return false;
2878 }
2879
2880 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2881 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002882 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002883 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002884 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2885 // The types of non-type template parameters must agree.
2886 NonTypeTemplateParmDecl *NewNTTP
2887 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002888
2889 // If we are matching a template template argument to a template
2890 // template parameter and one of the non-type template parameter types
2891 // is dependent, then we must wait until template instantiation time
2892 // to actually compare the arguments.
2893 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2894 (OldNTTP->getType()->isDependentType() ||
2895 NewNTTP->getType()->isDependentType()))
2896 continue;
2897
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002898 if (Context.getCanonicalType(OldNTTP->getType()) !=
2899 Context.getCanonicalType(NewNTTP->getType())) {
2900 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002901 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2902 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002903 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002904 diag::err_template_arg_template_params_mismatch);
2905 NextDiag = diag::note_template_nontype_parm_different_type;
2906 }
2907 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002908 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002909 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00002910 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002911 diag::note_template_nontype_parm_prev_declaration)
2912 << OldNTTP->getType();
2913 }
2914 return false;
2915 }
2916 } else {
2917 // The template parameter lists of template template
2918 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002919 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002920 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002921 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002922 = cast<TemplateTemplateParmDecl>(*OldParm);
2923 TemplateTemplateParmDecl *NewTTP
2924 = cast<TemplateTemplateParmDecl>(*NewParm);
2925 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2926 OldTTP->getTemplateParameters(),
2927 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002928 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00002929 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002930 return false;
2931 }
2932 }
2933
2934 return true;
2935}
2936
2937/// \brief Check whether a template can be declared within this scope.
2938///
2939/// If the template declaration is valid in this scope, returns
2940/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002941bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002942Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002943 // Find the nearest enclosing declaration scope.
2944 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2945 (S->getFlags() & Scope::TemplateParamScope) != 0)
2946 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002947
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002948 // C++ [temp]p2:
2949 // A template-declaration can appear only as a namespace scope or
2950 // class scope declaration.
2951 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002952 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2953 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002954 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002955 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002956
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002957 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002958 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002959
2960 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2961 return false;
2962
Mike Stump11289f42009-09-09 15:08:12 +00002963 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002964 diag::err_template_outside_namespace_or_class_scope)
2965 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002966}
Douglas Gregor67a65642009-02-17 23:15:12 +00002967
Douglas Gregor54888652009-10-07 00:13:32 +00002968/// \brief Determine what kind of template specialization the given declaration
2969/// is.
2970static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2971 if (!D)
2972 return TSK_Undeclared;
2973
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002974 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2975 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002976 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2977 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002978 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2979 return Var->getTemplateSpecializationKind();
2980
Douglas Gregor54888652009-10-07 00:13:32 +00002981 return TSK_Undeclared;
2982}
2983
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002984/// \brief Check whether a specialization is well-formed in the current
2985/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002986///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002987/// This routine determines whether a template specialization can be declared
2988/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002989///
2990/// \param S the semantic analysis object for which this check is being
2991/// performed.
2992///
2993/// \param Specialized the entity being specialized or instantiated, which
2994/// may be a kind of template (class template, function template, etc.) or
2995/// a member of a class template (member function, static data member,
2996/// member class).
2997///
2998/// \param PrevDecl the previous declaration of this entity, if any.
2999///
3000/// \param Loc the location of the explicit specialization or instantiation of
3001/// this entity.
3002///
3003/// \param IsPartialSpecialization whether this is a partial specialization of
3004/// a class template.
3005///
Douglas Gregor54888652009-10-07 00:13:32 +00003006/// \returns true if there was an error that we cannot recover from, false
3007/// otherwise.
3008static bool CheckTemplateSpecializationScope(Sema &S,
3009 NamedDecl *Specialized,
3010 NamedDecl *PrevDecl,
3011 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003012 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003013 // Keep these "kind" numbers in sync with the %select statements in the
3014 // various diagnostics emitted by this routine.
3015 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003016 bool isTemplateSpecialization = false;
3017 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003018 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003019 isTemplateSpecialization = true;
3020 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003021 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003022 isTemplateSpecialization = true;
3023 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003024 EntityKind = 3;
3025 else if (isa<VarDecl>(Specialized))
3026 EntityKind = 4;
3027 else if (isa<RecordDecl>(Specialized))
3028 EntityKind = 5;
3029 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003030 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3031 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003032 return true;
3033 }
3034
Douglas Gregorf47b9112009-02-25 22:02:03 +00003035 // C++ [temp.expl.spec]p2:
3036 // An explicit specialization shall be declared in the namespace
3037 // of which the template is a member, or, for member templates, in
3038 // the namespace of which the enclosing class or enclosing class
3039 // template is a member. An explicit specialization of a member
3040 // function, member class or static data member of a class
3041 // template shall be declared in the namespace of which the class
3042 // template is a member. Such a declaration may also be a
3043 // definition. If the declaration is not a definition, the
3044 // specialization may be defined later in the name- space in which
3045 // the explicit specialization was declared, or in a namespace
3046 // that encloses the one in which the explicit specialization was
3047 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003048 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3049 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003050 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003051 return true;
3052 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003053
Douglas Gregor40fb7442009-10-07 17:30:37 +00003054 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3055 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003056 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003057 return true;
3058 }
3059
Douglas Gregore4b05162009-10-07 17:21:34 +00003060 // C++ [temp.class.spec]p6:
3061 // A class template partial specialization may be declared or redeclared
3062 // in any namespace scope in which its definition may be defined (14.5.1
3063 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003064 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003065 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003066 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003067 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003068 if ((!PrevDecl ||
3069 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3070 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3071 // There is no prior declaration of this entity, so this
3072 // specialization must be in the same context as the template
3073 // itself.
3074 if (!DC->Equals(SpecializedContext)) {
3075 if (isa<TranslationUnitDecl>(SpecializedContext))
3076 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3077 << EntityKind << Specialized;
3078 else if (isa<NamespaceDecl>(SpecializedContext))
3079 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3080 << EntityKind << Specialized
3081 << cast<NamedDecl>(SpecializedContext);
3082
3083 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3084 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003085 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003086 }
Douglas Gregor54888652009-10-07 00:13:32 +00003087
3088 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003089 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003090 // Note that HandleDeclarator() performs this check for explicit
3091 // specializations of function templates, static data members, and member
3092 // functions, so we skip the check here for those kinds of entities.
3093 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003094 // Should we refactor that check, so that it occurs later?
3095 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003096 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3097 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003098 if (isa<TranslationUnitDecl>(SpecializedContext))
3099 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3100 << EntityKind << Specialized;
3101 else if (isa<NamespaceDecl>(SpecializedContext))
3102 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3103 << EntityKind << Specialized
3104 << cast<NamedDecl>(SpecializedContext);
3105
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003106 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003107 }
Douglas Gregor54888652009-10-07 00:13:32 +00003108
3109 // FIXME: check for specialization-after-instantiation errors and such.
3110
Douglas Gregorf47b9112009-02-25 22:02:03 +00003111 return false;
3112}
Douglas Gregor54888652009-10-07 00:13:32 +00003113
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003114/// \brief Check the non-type template arguments of a class template
3115/// partial specialization according to C++ [temp.class.spec]p9.
3116///
Douglas Gregor09a30232009-06-12 22:08:06 +00003117/// \param TemplateParams the template parameters of the primary class
3118/// template.
3119///
3120/// \param TemplateArg the template arguments of the class template
3121/// partial specialization.
3122///
3123/// \param MirrorsPrimaryTemplate will be set true if the class
3124/// template partial specialization arguments are identical to the
3125/// implicit template arguments of the primary template. This is not
3126/// necessarily an error (C++0x), and it is left to the caller to diagnose
3127/// this condition when it is an error.
3128///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003129/// \returns true if there was an error, false otherwise.
3130bool Sema::CheckClassTemplatePartialSpecializationArgs(
3131 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003132 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003133 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003134 // FIXME: the interface to this function will have to change to
3135 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003136 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003137
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003138 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003139
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003140 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003141 // Determine whether the template argument list of the partial
3142 // specialization is identical to the implicit argument list of
3143 // the primary template. The caller may need to diagnostic this as
3144 // an error per C++ [temp.class.spec]p9b3.
3145 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003146 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003147 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3148 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003149 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003150 MirrorsPrimaryTemplate = false;
3151 } else if (TemplateTemplateParmDecl *TTP
3152 = dyn_cast<TemplateTemplateParmDecl>(
3153 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003154 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003155 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003156 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003157 if (!ArgDecl ||
3158 ArgDecl->getIndex() != TTP->getIndex() ||
3159 ArgDecl->getDepth() != TTP->getDepth())
3160 MirrorsPrimaryTemplate = false;
3161 }
3162 }
3163
Mike Stump11289f42009-09-09 15:08:12 +00003164 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003165 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003166 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003167 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003168 }
3169
Anders Carlsson40c1d492009-06-13 18:20:51 +00003170 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003171 if (!ArgExpr) {
3172 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003173 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003174 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003175
3176 // C++ [temp.class.spec]p8:
3177 // A non-type argument is non-specialized if it is the name of a
3178 // non-type parameter. All other non-type arguments are
3179 // specialized.
3180 //
3181 // Below, we check the two conditions that only apply to
3182 // specialized non-type arguments, so skip any non-specialized
3183 // arguments.
3184 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003185 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003186 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003187 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003188 (Param->getIndex() != NTTP->getIndex() ||
3189 Param->getDepth() != NTTP->getDepth()))
3190 MirrorsPrimaryTemplate = false;
3191
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003192 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003193 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003194
3195 // C++ [temp.class.spec]p9:
3196 // Within the argument list of a class template partial
3197 // specialization, the following restrictions apply:
3198 // -- A partially specialized non-type argument expression
3199 // shall not involve a template parameter of the partial
3200 // specialization except when the argument expression is a
3201 // simple identifier.
3202 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003203 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003204 diag::err_dependent_non_type_arg_in_partial_spec)
3205 << ArgExpr->getSourceRange();
3206 return true;
3207 }
3208
3209 // -- The type of a template parameter corresponding to a
3210 // specialized non-type argument shall not be dependent on a
3211 // parameter of the specialization.
3212 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003213 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003214 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3215 << Param->getType()
3216 << ArgExpr->getSourceRange();
3217 Diag(Param->getLocation(), diag::note_template_param_here);
3218 return true;
3219 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003220
3221 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003222 }
3223
3224 return false;
3225}
3226
Douglas Gregorc08f4892009-03-25 00:13:59 +00003227Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003228Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3229 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003230 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00003231 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003232 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003233 SourceLocation TemplateNameLoc,
3234 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003235 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003236 SourceLocation RAngleLoc,
3237 AttributeList *Attr,
3238 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003239 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003240
Douglas Gregor67a65642009-02-17 23:15:12 +00003241 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003242 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003243 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003244 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3245
3246 if (!ClassTemplate) {
3247 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3248 << (Name.getAsTemplateDecl() &&
3249 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3250 return true;
3251 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003252
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003253 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003254 bool isPartialSpecialization = false;
3255
Douglas Gregorf47b9112009-02-25 22:02:03 +00003256 // Check the validity of the template headers that introduce this
3257 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003258 // FIXME: We probably shouldn't complain about these headers for
3259 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003260 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003261 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3262 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003263 TemplateParameterLists.size(),
3264 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003265 if (TemplateParams && TemplateParams->size() > 0) {
3266 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003267
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003268 // C++ [temp.class.spec]p10:
3269 // The template parameter list of a specialization shall not
3270 // contain default template argument values.
3271 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3272 Decl *Param = TemplateParams->getParam(I);
3273 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3274 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003275 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003276 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003277 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003278 }
3279 } else if (NonTypeTemplateParmDecl *NTTP
3280 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3281 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003282 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003283 diag::err_default_arg_in_partial_spec)
3284 << DefArg->getSourceRange();
3285 NTTP->setDefaultArgument(0);
3286 DefArg->Destroy(Context);
3287 }
3288 } else {
3289 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003290 if (TTP->hasDefaultArgument()) {
3291 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003292 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003293 << TTP->getDefaultArgument().getSourceRange();
3294 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003295 }
3296 }
3297 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003298 } else if (TemplateParams) {
3299 if (TUK == TUK_Friend)
3300 Diag(KWLoc, diag::err_template_spec_friend)
3301 << CodeModificationHint::CreateRemoval(
3302 SourceRange(TemplateParams->getTemplateLoc(),
3303 TemplateParams->getRAngleLoc()))
3304 << SourceRange(LAngleLoc, RAngleLoc);
3305 else
3306 isExplicitSpecialization = true;
3307 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003308 Diag(KWLoc, diag::err_template_spec_needs_header)
3309 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003310 isExplicitSpecialization = true;
3311 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003312
Douglas Gregor67a65642009-02-17 23:15:12 +00003313 // Check that the specialization uses the same tag kind as the
3314 // original template.
3315 TagDecl::TagKind Kind;
3316 switch (TagSpec) {
3317 default: assert(0 && "Unknown tag type!");
3318 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3319 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3320 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3321 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003322 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003323 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003324 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003325 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003326 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003327 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003328 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003329 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003330 diag::note_previous_use);
3331 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3332 }
3333
Douglas Gregorc40290e2009-03-09 23:48:35 +00003334 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003335 TemplateArgumentListInfo TemplateArgs;
3336 TemplateArgs.setLAngleLoc(LAngleLoc);
3337 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003338 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003339
Douglas Gregor67a65642009-02-17 23:15:12 +00003340 // Check that the template argument list is well-formed for this
3341 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003342 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3343 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003344 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3345 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003346 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003347
Mike Stump11289f42009-09-09 15:08:12 +00003348 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003349 ClassTemplate->getTemplateParameters()->size()) &&
3350 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003351
Douglas Gregor2373c592009-05-31 09:31:02 +00003352 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003353 // corresponds to these arguments.
3354 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003355 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003356 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003357 if (CheckClassTemplatePartialSpecializationArgs(
3358 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003359 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003360 return true;
3361
Douglas Gregor09a30232009-06-12 22:08:06 +00003362 if (MirrorsPrimaryTemplate) {
3363 // C++ [temp.class.spec]p9b3:
3364 //
Mike Stump11289f42009-09-09 15:08:12 +00003365 // -- The argument list of the specialization shall not be identical
3366 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003367 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003368 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003369 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003370 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003371 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003372 ClassTemplate->getIdentifier(),
3373 TemplateNameLoc,
3374 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003375 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003376 AS_none);
3377 }
3378
Douglas Gregor2208a292009-09-26 20:57:03 +00003379 // FIXME: Diagnose friend partial specializations
3380
Douglas Gregor2373c592009-05-31 09:31:02 +00003381 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00003382 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003383 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003384 Converted.flatSize(),
3385 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003386 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003387 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003388 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003389 Converted.flatSize(),
3390 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003391 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003392 ClassTemplateSpecializationDecl *PrevDecl = 0;
3393
3394 if (isPartialSpecialization)
3395 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003396 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003397 InsertPos);
3398 else
3399 PrevDecl
3400 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003401
3402 ClassTemplateSpecializationDecl *Specialization = 0;
3403
Douglas Gregorf47b9112009-02-25 22:02:03 +00003404 // Check whether we can declare a class template specialization in
3405 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003406 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003407 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003408 TemplateNameLoc,
3409 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003410 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003411
Douglas Gregor15301382009-07-30 17:40:51 +00003412 // The canonical type
3413 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003414 if (PrevDecl &&
3415 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3416 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003417 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003418 // arguments was referenced but not declared, or we're only
3419 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003420 // declaration node as our own, updating its source location to
3421 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003422 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003423 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003424 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003425 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003426 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003427 // Build the canonical type that describes the converted template
3428 // arguments of the class template partial specialization.
3429 CanonType = Context.getTemplateSpecializationType(
3430 TemplateName(ClassTemplate),
3431 Converted.getFlatArguments(),
3432 Converted.flatSize());
3433
Douglas Gregor2373c592009-05-31 09:31:02 +00003434 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003435 ClassTemplatePartialSpecializationDecl *PrevPartial
3436 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003437 ClassTemplatePartialSpecializationDecl *Partial
3438 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003439 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003440 TemplateNameLoc,
3441 TemplateParams,
3442 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003443 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003444 TemplateArgs,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003445 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003446
3447 if (PrevPartial) {
3448 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3449 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3450 } else {
3451 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3452 }
3453 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003454
Douglas Gregor21610382009-10-29 00:04:11 +00003455 // If we are providing an explicit specialization of a member class
3456 // template specialization, make a note of that.
3457 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3458 PrevPartial->setMemberSpecialization();
3459
Douglas Gregor91772d12009-06-13 00:26:55 +00003460 // Check that all of the template parameters of the class template
3461 // partial specialization are deducible from the template
3462 // arguments. If not, this class template partial specialization
3463 // will never be used.
3464 llvm::SmallVector<bool, 8> DeducibleParams;
3465 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003466 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003467 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003468 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003469 unsigned NumNonDeducible = 0;
3470 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3471 if (!DeducibleParams[I])
3472 ++NumNonDeducible;
3473
3474 if (NumNonDeducible) {
3475 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3476 << (NumNonDeducible > 1)
3477 << SourceRange(TemplateNameLoc, RAngleLoc);
3478 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3479 if (!DeducibleParams[I]) {
3480 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3481 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003482 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003483 diag::note_partial_spec_unused_parameter)
3484 << Param->getDeclName();
3485 else
Mike Stump11289f42009-09-09 15:08:12 +00003486 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003487 diag::note_partial_spec_unused_parameter)
3488 << std::string("<anonymous>");
3489 }
3490 }
3491 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003492 } else {
3493 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003494 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003495 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003496 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003497 ClassTemplate->getDeclContext(),
3498 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003499 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003500 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003501 PrevDecl);
3502
3503 if (PrevDecl) {
3504 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3505 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3506 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003507 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003508 InsertPos);
3509 }
Douglas Gregor15301382009-07-30 17:40:51 +00003510
3511 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003512 }
3513
Douglas Gregor06db9f52009-10-12 20:18:28 +00003514 // C++ [temp.expl.spec]p6:
3515 // If a template, a member template or the member of a class template is
3516 // explicitly specialized then that specialization shall be declared
3517 // before the first use of that specialization that would cause an implicit
3518 // instantiation to take place, in every translation unit in which such a
3519 // use occurs; no diagnostic is required.
3520 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3521 SourceRange Range(TemplateNameLoc, RAngleLoc);
3522 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3523 << Context.getTypeDeclType(Specialization) << Range;
3524
3525 Diag(PrevDecl->getPointOfInstantiation(),
3526 diag::note_instantiation_required_here)
3527 << (PrevDecl->getTemplateSpecializationKind()
3528 != TSK_ImplicitInstantiation);
3529 return true;
3530 }
3531
Douglas Gregor2208a292009-09-26 20:57:03 +00003532 // If this is not a friend, note that this is an explicit specialization.
3533 if (TUK != TUK_Friend)
3534 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003535
3536 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003537 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003538 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003539 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003540 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003541 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003542 Diag(Def->getLocation(), diag::note_previous_definition);
3543 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003544 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003545 }
3546 }
3547
Douglas Gregord56a91e2009-02-26 22:19:44 +00003548 // Build the fully-sugared type for this class template
3549 // specialization as the user wrote in the specialization
3550 // itself. This means that we'll pretty-print the type retrieved
3551 // from the specialization's declaration the way that the user
3552 // actually wrote the specialization, rather than formatting the
3553 // name based on the "canonical" representation used to store the
3554 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003555 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00003556 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003557 if (TUK != TUK_Friend)
3558 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003559 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003560
Douglas Gregor1e249f82009-02-25 22:18:32 +00003561 // C++ [temp.expl.spec]p9:
3562 // A template explicit specialization is in the scope of the
3563 // namespace in which the template was defined.
3564 //
3565 // We actually implement this paragraph where we set the semantic
3566 // context (in the creation of the ClassTemplateSpecializationDecl),
3567 // but we also maintain the lexical context where the actual
3568 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003569 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003570
Douglas Gregor67a65642009-02-17 23:15:12 +00003571 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003572 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003573 Specialization->startDefinition();
3574
Douglas Gregor2208a292009-09-26 20:57:03 +00003575 if (TUK == TUK_Friend) {
3576 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3577 TemplateNameLoc,
3578 WrittenTy.getTypePtr(),
3579 /*FIXME:*/KWLoc);
3580 Friend->setAccess(AS_public);
3581 CurContext->addDecl(Friend);
3582 } else {
3583 // Add the specialization into its lexical context, so that it can
3584 // be seen when iterating through the list of declarations in that
3585 // context. However, specializations are not found by name lookup.
3586 CurContext->addDecl(Specialization);
3587 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003588 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003589}
Douglas Gregor333489b2009-03-27 23:10:48 +00003590
Mike Stump11289f42009-09-09 15:08:12 +00003591Sema::DeclPtrTy
3592Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003593 MultiTemplateParamsArg TemplateParameterLists,
3594 Declarator &D) {
3595 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3596}
3597
Mike Stump11289f42009-09-09 15:08:12 +00003598Sema::DeclPtrTy
3599Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003600 MultiTemplateParamsArg TemplateParameterLists,
3601 Declarator &D) {
3602 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3603 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3604 "Not a function declarator!");
3605 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003606
Douglas Gregor17a7c122009-06-24 00:54:41 +00003607 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003608 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003609 }
Mike Stump11289f42009-09-09 15:08:12 +00003610
Douglas Gregor17a7c122009-06-24 00:54:41 +00003611 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003612
3613 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003614 move(TemplateParameterLists),
3615 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003616 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003617 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003618 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003619 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003620 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3621 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003622 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003623}
3624
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003625/// \brief Diagnose cases where we have an explicit template specialization
3626/// before/after an explicit template instantiation, producing diagnostics
3627/// for those cases where they are required and determining whether the
3628/// new specialization/instantiation will have any effect.
3629///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003630/// \param NewLoc the location of the new explicit specialization or
3631/// instantiation.
3632///
3633/// \param NewTSK the kind of the new explicit specialization or instantiation.
3634///
3635/// \param PrevDecl the previous declaration of the entity.
3636///
3637/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3638///
3639/// \param PrevPointOfInstantiation if valid, indicates where the previus
3640/// declaration was instantiated (either implicitly or explicitly).
3641///
3642/// \param SuppressNew will be set to true to indicate that the new
3643/// specialization or instantiation has no effect and should be ignored.
3644///
3645/// \returns true if there was an error that should prevent the introduction of
3646/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003647bool
3648Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3649 TemplateSpecializationKind NewTSK,
3650 NamedDecl *PrevDecl,
3651 TemplateSpecializationKind PrevTSK,
3652 SourceLocation PrevPointOfInstantiation,
3653 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003654 SuppressNew = false;
3655
3656 switch (NewTSK) {
3657 case TSK_Undeclared:
3658 case TSK_ImplicitInstantiation:
3659 assert(false && "Don't check implicit instantiations here");
3660 return false;
3661
3662 case TSK_ExplicitSpecialization:
3663 switch (PrevTSK) {
3664 case TSK_Undeclared:
3665 case TSK_ExplicitSpecialization:
3666 // Okay, we're just specializing something that is either already
3667 // explicitly specialized or has merely been mentioned without any
3668 // instantiation.
3669 return false;
3670
3671 case TSK_ImplicitInstantiation:
3672 if (PrevPointOfInstantiation.isInvalid()) {
3673 // The declaration itself has not actually been instantiated, so it is
3674 // still okay to specialize it.
3675 return false;
3676 }
3677 // Fall through
3678
3679 case TSK_ExplicitInstantiationDeclaration:
3680 case TSK_ExplicitInstantiationDefinition:
3681 assert((PrevTSK == TSK_ImplicitInstantiation ||
3682 PrevPointOfInstantiation.isValid()) &&
3683 "Explicit instantiation without point of instantiation?");
3684
3685 // C++ [temp.expl.spec]p6:
3686 // If a template, a member template or the member of a class template
3687 // is explicitly specialized then that specialization shall be declared
3688 // before the first use of that specialization that would cause an
3689 // implicit instantiation to take place, in every translation unit in
3690 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003691 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003692 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003693 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003694 << (PrevTSK != TSK_ImplicitInstantiation);
3695
3696 return true;
3697 }
3698 break;
3699
3700 case TSK_ExplicitInstantiationDeclaration:
3701 switch (PrevTSK) {
3702 case TSK_ExplicitInstantiationDeclaration:
3703 // This explicit instantiation declaration is redundant (that's okay).
3704 SuppressNew = true;
3705 return false;
3706
3707 case TSK_Undeclared:
3708 case TSK_ImplicitInstantiation:
3709 // We're explicitly instantiating something that may have already been
3710 // implicitly instantiated; that's fine.
3711 return false;
3712
3713 case TSK_ExplicitSpecialization:
3714 // C++0x [temp.explicit]p4:
3715 // For a given set of template parameters, if an explicit instantiation
3716 // of a template appears after a declaration of an explicit
3717 // specialization for that template, the explicit instantiation has no
3718 // effect.
3719 return false;
3720
3721 case TSK_ExplicitInstantiationDefinition:
3722 // C++0x [temp.explicit]p10:
3723 // If an entity is the subject of both an explicit instantiation
3724 // declaration and an explicit instantiation definition in the same
3725 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003726 Diag(NewLoc,
3727 diag::err_explicit_instantiation_declaration_after_definition);
3728 Diag(PrevPointOfInstantiation,
3729 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003730 assert(PrevPointOfInstantiation.isValid() &&
3731 "Explicit instantiation without point of instantiation?");
3732 SuppressNew = true;
3733 return false;
3734 }
3735 break;
3736
3737 case TSK_ExplicitInstantiationDefinition:
3738 switch (PrevTSK) {
3739 case TSK_Undeclared:
3740 case TSK_ImplicitInstantiation:
3741 // We're explicitly instantiating something that may have already been
3742 // implicitly instantiated; that's fine.
3743 return false;
3744
3745 case TSK_ExplicitSpecialization:
3746 // C++ DR 259, C++0x [temp.explicit]p4:
3747 // For a given set of template parameters, if an explicit
3748 // instantiation of a template appears after a declaration of
3749 // an explicit specialization for that template, the explicit
3750 // instantiation has no effect.
3751 //
3752 // In C++98/03 mode, we only give an extension warning here, because it
3753 // is not not harmful to try to explicitly instantiate something that
3754 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003755 if (!getLangOptions().CPlusPlus0x) {
3756 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003757 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003758 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003759 diag::note_previous_template_specialization);
3760 }
3761 SuppressNew = true;
3762 return false;
3763
3764 case TSK_ExplicitInstantiationDeclaration:
3765 // We're explicity instantiating a definition for something for which we
3766 // were previously asked to suppress instantiations. That's fine.
3767 return false;
3768
3769 case TSK_ExplicitInstantiationDefinition:
3770 // C++0x [temp.spec]p5:
3771 // For a given template and a given set of template-arguments,
3772 // - an explicit instantiation definition shall appear at most once
3773 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003774 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003775 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003776 Diag(PrevPointOfInstantiation,
3777 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003778 SuppressNew = true;
3779 return false;
3780 }
3781 break;
3782 }
3783
3784 assert(false && "Missing specialization/instantiation case?");
3785
3786 return false;
3787}
3788
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003789/// \brief Perform semantic analysis for the given function template
3790/// specialization.
3791///
3792/// This routine performs all of the semantic analysis required for an
3793/// explicit function template specialization. On successful completion,
3794/// the function declaration \p FD will become a function template
3795/// specialization.
3796///
3797/// \param FD the function declaration, which will be updated to become a
3798/// function template specialization.
3799///
3800/// \param HasExplicitTemplateArgs whether any template arguments were
3801/// explicitly provided.
3802///
3803/// \param LAngleLoc the location of the left angle bracket ('<'), if
3804/// template arguments were explicitly provided.
3805///
3806/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3807/// if any.
3808///
3809/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3810/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3811/// true as in, e.g., \c void sort<>(char*, char*);
3812///
3813/// \param RAngleLoc the location of the right angle bracket ('>'), if
3814/// template arguments were explicitly provided.
3815///
3816/// \param PrevDecl the set of declarations that
3817bool
3818Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00003819 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00003820 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003821 // The set of function template specializations that could match this
3822 // explicit function template specialization.
3823 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3824 CandidateSet Candidates;
3825
3826 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00003827 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3828 I != E; ++I) {
3829 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3830 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003831 // Only consider templates found within the same semantic lookup scope as
3832 // FD.
3833 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3834 continue;
3835
3836 // C++ [temp.expl.spec]p11:
3837 // A trailing template-argument can be left unspecified in the
3838 // template-id naming an explicit function template specialization
3839 // provided it can be deduced from the function argument type.
3840 // Perform template argument deduction to determine whether we may be
3841 // specializing this template.
3842 // FIXME: It is somewhat wasteful to build
3843 TemplateDeductionInfo Info(Context);
3844 FunctionDecl *Specialization = 0;
3845 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00003846 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003847 FD->getType(),
3848 Specialization,
3849 Info)) {
3850 // FIXME: Template argument deduction failed; record why it failed, so
3851 // that we can provide nifty diagnostics.
3852 (void)TDK;
3853 continue;
3854 }
3855
3856 // Record this candidate.
3857 Candidates.push_back(Specialization);
3858 }
3859 }
3860
Douglas Gregor5de279c2009-09-26 03:41:46 +00003861 // Find the most specialized function template.
3862 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3863 Candidates.size(),
3864 TPOC_Other,
3865 FD->getLocation(),
3866 PartialDiagnostic(diag::err_function_template_spec_no_match)
3867 << FD->getDeclName(),
3868 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00003869 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor5de279c2009-09-26 03:41:46 +00003870 PartialDiagnostic(diag::note_function_template_spec_matched));
3871 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003872 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003873
3874 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003875 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003876
Douglas Gregor54888652009-10-07 00:13:32 +00003877 // Check the scope of this explicit specialization.
3878 if (CheckTemplateSpecializationScope(*this,
3879 Specialization->getPrimaryTemplate(),
3880 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003881 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003882 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003883
3884 // C++ [temp.expl.spec]p6:
3885 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003886 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003887 // before the first use of that specialization that would cause an implicit
3888 // instantiation to take place, in every translation unit in which such a
3889 // use occurs; no diagnostic is required.
3890 FunctionTemplateSpecializationInfo *SpecInfo
3891 = Specialization->getTemplateSpecializationInfo();
3892 assert(SpecInfo && "Function template specialization info missing?");
3893 if (SpecInfo->getPointOfInstantiation().isValid()) {
3894 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3895 << FD;
3896 Diag(SpecInfo->getPointOfInstantiation(),
3897 diag::note_instantiation_required_here)
3898 << (Specialization->getTemplateSpecializationKind()
3899 != TSK_ImplicitInstantiation);
3900 return true;
3901 }
Douglas Gregor54888652009-10-07 00:13:32 +00003902
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003903 // Mark the prior declaration as an explicit specialization, so that later
3904 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003905 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003906
3907 // Turn the given function declaration into a function template
3908 // specialization, with the template arguments from the previous
3909 // specialization.
3910 FD->setFunctionTemplateSpecialization(Context,
3911 Specialization->getPrimaryTemplate(),
3912 new (Context) TemplateArgumentList(
3913 *Specialization->getTemplateSpecializationArgs()),
3914 /*InsertPos=*/0,
3915 TSK_ExplicitSpecialization);
3916
3917 // The "previous declaration" for this function template specialization is
3918 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00003919 Previous.clear();
3920 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003921 return false;
3922}
3923
Douglas Gregor86d142a2009-10-08 07:24:58 +00003924/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003925/// specialization.
3926///
3927/// This routine performs all of the semantic analysis required for an
3928/// explicit member function specialization. On successful completion,
3929/// the function declaration \p FD will become a member function
3930/// specialization.
3931///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003932/// \param Member the member declaration, which will be updated to become a
3933/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003934///
John McCall1f82f242009-11-18 22:49:29 +00003935/// \param Previous the set of declarations, one of which may be specialized
3936/// by this function specialization; the set will be modified to contain the
3937/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003938bool
John McCall1f82f242009-11-18 22:49:29 +00003939Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003940 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3941
3942 // Try to find the member we are instantiating.
3943 NamedDecl *Instantiation = 0;
3944 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003945 MemberSpecializationInfo *MSInfo = 0;
3946
John McCall1f82f242009-11-18 22:49:29 +00003947 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003948 // Nowhere to look anyway.
3949 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003950 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3951 I != E; ++I) {
3952 NamedDecl *D = (*I)->getUnderlyingDecl();
3953 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003954 if (Context.hasSameType(Function->getType(), Method->getType())) {
3955 Instantiation = Method;
3956 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003957 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003958 break;
3959 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003960 }
3961 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003962 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003963 VarDecl *PrevVar;
3964 if (Previous.isSingleResult() &&
3965 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00003966 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00003967 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003968 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003969 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003970 }
3971 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003972 CXXRecordDecl *PrevRecord;
3973 if (Previous.isSingleResult() &&
3974 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3975 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003976 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003977 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003978 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003979 }
3980
3981 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003982 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003983 // specializations are always out-of-line, the caller will complain about
3984 // this mismatch later.
3985 return false;
3986 }
3987
Douglas Gregor86d142a2009-10-08 07:24:58 +00003988 // Make sure that this is a specialization of a member.
3989 if (!InstantiatedFrom) {
3990 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3991 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003992 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3993 return true;
3994 }
3995
Douglas Gregor06db9f52009-10-12 20:18:28 +00003996 // C++ [temp.expl.spec]p6:
3997 // If a template, a member template or the member of a class template is
3998 // explicitly specialized then that spe- cialization shall be declared
3999 // before the first use of that specialization that would cause an implicit
4000 // instantiation to take place, in every translation unit in which such a
4001 // use occurs; no diagnostic is required.
4002 assert(MSInfo && "Member specialization info missing?");
4003 if (MSInfo->getPointOfInstantiation().isValid()) {
4004 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
4005 << Member;
4006 Diag(MSInfo->getPointOfInstantiation(),
4007 diag::note_instantiation_required_here)
4008 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
4009 return true;
4010 }
4011
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004012 // Check the scope of this explicit specialization.
4013 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004014 InstantiatedFrom,
4015 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004016 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004017 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004018
Douglas Gregor86d142a2009-10-08 07:24:58 +00004019 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004020 // the original declaration to note that it is an explicit specialization
4021 // (if it was previously an implicit instantiation). This latter step
4022 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004023 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004024 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4025 if (InstantiationFunction->getTemplateSpecializationKind() ==
4026 TSK_ImplicitInstantiation) {
4027 InstantiationFunction->setTemplateSpecializationKind(
4028 TSK_ExplicitSpecialization);
4029 InstantiationFunction->setLocation(Member->getLocation());
4030 }
4031
Douglas Gregor86d142a2009-10-08 07:24:58 +00004032 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4033 cast<CXXMethodDecl>(InstantiatedFrom),
4034 TSK_ExplicitSpecialization);
4035 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004036 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4037 if (InstantiationVar->getTemplateSpecializationKind() ==
4038 TSK_ImplicitInstantiation) {
4039 InstantiationVar->setTemplateSpecializationKind(
4040 TSK_ExplicitSpecialization);
4041 InstantiationVar->setLocation(Member->getLocation());
4042 }
4043
Douglas Gregor86d142a2009-10-08 07:24:58 +00004044 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4045 cast<VarDecl>(InstantiatedFrom),
4046 TSK_ExplicitSpecialization);
4047 } else {
4048 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004049 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4050 if (InstantiationClass->getTemplateSpecializationKind() ==
4051 TSK_ImplicitInstantiation) {
4052 InstantiationClass->setTemplateSpecializationKind(
4053 TSK_ExplicitSpecialization);
4054 InstantiationClass->setLocation(Member->getLocation());
4055 }
4056
Douglas Gregor86d142a2009-10-08 07:24:58 +00004057 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004058 cast<CXXRecordDecl>(InstantiatedFrom),
4059 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004060 }
4061
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004062 // Save the caller the trouble of having to figure out which declaration
4063 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004064 Previous.clear();
4065 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004066 return false;
4067}
4068
Douglas Gregore47f5a72009-10-14 23:41:34 +00004069/// \brief Check the scope of an explicit instantiation.
4070static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4071 SourceLocation InstLoc,
4072 bool WasQualifiedName) {
4073 DeclContext *ExpectedContext
4074 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4075 DeclContext *CurContext = S.CurContext->getLookupContext();
4076
4077 // C++0x [temp.explicit]p2:
4078 // An explicit instantiation shall appear in an enclosing namespace of its
4079 // template.
4080 //
4081 // This is DR275, which we do not retroactively apply to C++98/03.
4082 if (S.getLangOptions().CPlusPlus0x &&
4083 !CurContext->Encloses(ExpectedContext)) {
4084 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4085 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4086 << D << NS;
4087 else
4088 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4089 << D;
4090 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4091 return;
4092 }
4093
4094 // C++0x [temp.explicit]p2:
4095 // If the name declared in the explicit instantiation is an unqualified
4096 // name, the explicit instantiation shall appear in the namespace where
4097 // its template is declared or, if that namespace is inline (7.3.1), any
4098 // namespace from its enclosing namespace set.
4099 if (WasQualifiedName)
4100 return;
4101
4102 if (CurContext->Equals(ExpectedContext))
4103 return;
4104
4105 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4106 << D << ExpectedContext;
4107 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4108}
4109
4110/// \brief Determine whether the given scope specifier has a template-id in it.
4111static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4112 if (!SS.isSet())
4113 return false;
4114
4115 // C++0x [temp.explicit]p2:
4116 // If the explicit instantiation is for a member function, a member class
4117 // or a static data member of a class template specialization, the name of
4118 // the class template specialization in the qualified-id for the member
4119 // name shall be a simple-template-id.
4120 //
4121 // C++98 has the same restriction, just worded differently.
4122 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4123 NNS; NNS = NNS->getPrefix())
4124 if (Type *T = NNS->getAsType())
4125 if (isa<TemplateSpecializationType>(T))
4126 return true;
4127
4128 return false;
4129}
4130
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004131// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004132// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004133Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004134Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004135 SourceLocation ExternLoc,
4136 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004137 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004138 SourceLocation KWLoc,
4139 const CXXScopeSpec &SS,
4140 TemplateTy TemplateD,
4141 SourceLocation TemplateNameLoc,
4142 SourceLocation LAngleLoc,
4143 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004144 SourceLocation RAngleLoc,
4145 AttributeList *Attr) {
4146 // Find the class template we're specializing
4147 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004148 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004149 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4150
4151 // Check that the specialization uses the same tag kind as the
4152 // original template.
4153 TagDecl::TagKind Kind;
4154 switch (TagSpec) {
4155 default: assert(0 && "Unknown tag type!");
4156 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4157 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4158 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4159 }
Douglas Gregord9034f02009-05-14 16:41:31 +00004160 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004161 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004162 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004163 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004164 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00004165 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004166 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004167 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004168 diag::note_previous_use);
4169 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4170 }
4171
Douglas Gregore47f5a72009-10-14 23:41:34 +00004172 // C++0x [temp.explicit]p2:
4173 // There are two forms of explicit instantiation: an explicit instantiation
4174 // definition and an explicit instantiation declaration. An explicit
4175 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004176 TemplateSpecializationKind TSK
4177 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4178 : TSK_ExplicitInstantiationDeclaration;
4179
Douglas Gregora1f49972009-05-13 00:25:59 +00004180 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004181 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004182 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004183
4184 // Check that the template argument list is well-formed for this
4185 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004186 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4187 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004188 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4189 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004190 return true;
4191
Mike Stump11289f42009-09-09 15:08:12 +00004192 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004193 ClassTemplate->getTemplateParameters()->size()) &&
4194 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004195
Douglas Gregora1f49972009-05-13 00:25:59 +00004196 // Find the class template specialization declaration that
4197 // corresponds to these arguments.
4198 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004199 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004200 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004201 Converted.flatSize(),
4202 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004203 void *InsertPos = 0;
4204 ClassTemplateSpecializationDecl *PrevDecl
4205 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4206
Douglas Gregor54888652009-10-07 00:13:32 +00004207 // C++0x [temp.explicit]p2:
4208 // [...] An explicit instantiation shall appear in an enclosing
4209 // namespace of its template. [...]
4210 //
4211 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004212 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4213 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004214
Douglas Gregora1f49972009-05-13 00:25:59 +00004215 ClassTemplateSpecializationDecl *Specialization = 0;
4216
Douglas Gregor0681a352009-11-25 06:01:46 +00004217 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004218 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004219 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004220 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004221 PrevDecl,
4222 PrevDecl->getSpecializationKind(),
4223 PrevDecl->getPointOfInstantiation(),
4224 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004225 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004226
Douglas Gregor12e49d32009-10-15 22:53:21 +00004227 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004228 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004229
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004230 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4231 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4232 // Since the only prior class template specialization with these
4233 // arguments was referenced but not declared, reuse that
4234 // declaration node as our own, updating its source location to
4235 // reflect our new declaration.
4236 Specialization = PrevDecl;
4237 Specialization->setLocation(TemplateNameLoc);
4238 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004239 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004240 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004241 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004242
4243 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004244 // Create a new class template specialization declaration node for
4245 // this explicit specialization.
4246 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00004247 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00004248 ClassTemplate->getDeclContext(),
4249 TemplateNameLoc,
4250 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004251 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004252
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004253 if (PrevDecl) {
4254 // Remove the previous declaration from the folding set, since we want
4255 // to introduce a new declaration.
4256 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4257 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4258 }
4259
4260 // Insert the new specialization.
4261 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004262 }
4263
4264 // Build the fully-sugared type for this explicit instantiation as
4265 // the user wrote in the explicit instantiation itself. This means
4266 // that we'll pretty-print the type retrieved from the
4267 // specialization's declaration the way that the user actually wrote
4268 // the explicit instantiation, rather than formatting the name based
4269 // on the "canonical" representation used to store the template
4270 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004271 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00004272 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004273 Context.getTypeDeclType(Specialization));
4274 Specialization->setTypeAsWritten(WrittenTy);
4275 TemplateArgsIn.release();
4276
Douglas Gregor0681a352009-11-25 06:01:46 +00004277 if (!ReusedDecl) {
4278 // Add the explicit instantiation into its lexical context. However,
4279 // since explicit instantiations are never found by name lookup, we
4280 // just put it into the declaration context directly.
4281 Specialization->setLexicalDeclContext(CurContext);
4282 CurContext->addDecl(Specialization);
4283 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004284
4285 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004286 // A definition of a class template or class member template
4287 // shall be in scope at the point of the explicit instantiation of
4288 // the class template or class member template.
4289 //
4290 // This check comes when we actually try to perform the
4291 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004292 ClassTemplateSpecializationDecl *Def
4293 = cast_or_null<ClassTemplateSpecializationDecl>(
4294 Specialization->getDefinition(Context));
4295 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004296 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004297
4298 // Instantiate the members of this class template specialization.
4299 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4300 Specialization->getDefinition(Context));
4301 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00004302 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004303
4304 return DeclPtrTy::make(Specialization);
4305}
4306
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004307// Explicit instantiation of a member class of a class template.
4308Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004309Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004310 SourceLocation ExternLoc,
4311 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004312 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004313 SourceLocation KWLoc,
4314 const CXXScopeSpec &SS,
4315 IdentifierInfo *Name,
4316 SourceLocation NameLoc,
4317 AttributeList *Attr) {
4318
Douglas Gregord6ab8742009-05-28 23:31:59 +00004319 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004320 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004321 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004322 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004323 MultiTemplateParamsArg(*this, 0, 0),
4324 Owned, IsDependent);
4325 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4326
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004327 if (!TagD)
4328 return true;
4329
4330 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4331 if (Tag->isEnum()) {
4332 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4333 << Context.getTypeDeclType(Tag);
4334 return true;
4335 }
4336
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004337 if (Tag->isInvalidDecl())
4338 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004339
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004340 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4341 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4342 if (!Pattern) {
4343 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4344 << Context.getTypeDeclType(Record);
4345 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4346 return true;
4347 }
4348
Douglas Gregore47f5a72009-10-14 23:41:34 +00004349 // C++0x [temp.explicit]p2:
4350 // If the explicit instantiation is for a class or member class, the
4351 // elaborated-type-specifier in the declaration shall include a
4352 // simple-template-id.
4353 //
4354 // C++98 has the same restriction, just worded differently.
4355 if (!ScopeSpecifierHasTemplateId(SS))
4356 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4357 << Record << SS.getRange();
4358
4359 // C++0x [temp.explicit]p2:
4360 // There are two forms of explicit instantiation: an explicit instantiation
4361 // definition and an explicit instantiation declaration. An explicit
4362 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004363 TemplateSpecializationKind TSK
4364 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4365 : TSK_ExplicitInstantiationDeclaration;
4366
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004367 // C++0x [temp.explicit]p2:
4368 // [...] An explicit instantiation shall appear in an enclosing
4369 // namespace of its template. [...]
4370 //
4371 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004372 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004373
4374 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004375 CXXRecordDecl *PrevDecl
4376 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4377 if (!PrevDecl && Record->getDefinition(Context))
4378 PrevDecl = Record;
4379 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004380 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4381 bool SuppressNew = false;
4382 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004383 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004384 PrevDecl,
4385 MSInfo->getTemplateSpecializationKind(),
4386 MSInfo->getPointOfInstantiation(),
4387 SuppressNew))
4388 return true;
4389 if (SuppressNew)
4390 return TagD;
4391 }
4392
Douglas Gregor12e49d32009-10-15 22:53:21 +00004393 CXXRecordDecl *RecordDef
4394 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4395 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004396 // C++ [temp.explicit]p3:
4397 // A definition of a member class of a class template shall be in scope
4398 // at the point of an explicit instantiation of the member class.
4399 CXXRecordDecl *Def
4400 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4401 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004402 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4403 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004404 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4405 << Pattern;
4406 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004407 } else {
4408 if (InstantiateClass(NameLoc, Record, Def,
4409 getTemplateInstantiationArgs(Record),
4410 TSK))
4411 return true;
4412
4413 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4414 if (!RecordDef)
4415 return true;
4416 }
4417 }
4418
4419 // Instantiate all of the members of the class.
4420 InstantiateClassMembers(NameLoc, RecordDef,
4421 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004422
Mike Stump87c57ac2009-05-16 07:39:55 +00004423 // FIXME: We don't have any representation for explicit instantiations of
4424 // member classes. Such a representation is not needed for compilation, but it
4425 // should be available for clients that want to see all of the declarations in
4426 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004427 return TagD;
4428}
4429
Douglas Gregor450f00842009-09-25 18:43:00 +00004430Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4431 SourceLocation ExternLoc,
4432 SourceLocation TemplateLoc,
4433 Declarator &D) {
4434 // Explicit instantiations always require a name.
4435 DeclarationName Name = GetNameForDeclarator(D);
4436 if (!Name) {
4437 if (!D.isInvalidType())
4438 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4439 diag::err_explicit_instantiation_requires_name)
4440 << D.getDeclSpec().getSourceRange()
4441 << D.getSourceRange();
4442
4443 return true;
4444 }
4445
4446 // The scope passed in may not be a decl scope. Zip up the scope tree until
4447 // we find one that is.
4448 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4449 (S->getFlags() & Scope::TemplateParamScope) != 0)
4450 S = S->getParent();
4451
4452 // Determine the type of the declaration.
4453 QualType R = GetTypeForDeclarator(D, S, 0);
4454 if (R.isNull())
4455 return true;
4456
4457 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4458 // Cannot explicitly instantiate a typedef.
4459 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4460 << Name;
4461 return true;
4462 }
4463
Douglas Gregor3c74d412009-10-14 20:14:33 +00004464 // C++0x [temp.explicit]p1:
4465 // [...] An explicit instantiation of a function template shall not use the
4466 // inline or constexpr specifiers.
4467 // Presumably, this also applies to member functions of class templates as
4468 // well.
4469 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4470 Diag(D.getDeclSpec().getInlineSpecLoc(),
4471 diag::err_explicit_instantiation_inline)
4472 << CodeModificationHint::CreateRemoval(
4473 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
4474
4475 // FIXME: check for constexpr specifier.
4476
Douglas Gregore47f5a72009-10-14 23:41:34 +00004477 // C++0x [temp.explicit]p2:
4478 // There are two forms of explicit instantiation: an explicit instantiation
4479 // definition and an explicit instantiation declaration. An explicit
4480 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004481 TemplateSpecializationKind TSK
4482 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4483 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004484
John McCall27b18f82009-11-17 02:14:36 +00004485 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4486 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004487
4488 if (!R->isFunctionType()) {
4489 // C++ [temp.explicit]p1:
4490 // A [...] static data member of a class template can be explicitly
4491 // instantiated from the member definition associated with its class
4492 // template.
John McCall27b18f82009-11-17 02:14:36 +00004493 if (Previous.isAmbiguous())
4494 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004495
John McCall9f3059a2009-10-09 21:13:30 +00004496 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4497 Previous.getAsSingleDecl(Context));
Douglas Gregor450f00842009-09-25 18:43:00 +00004498 if (!Prev || !Prev->isStaticDataMember()) {
4499 // We expect to see a data data member here.
4500 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4501 << Name;
4502 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4503 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004504 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004505 return true;
4506 }
4507
4508 if (!Prev->getInstantiatedFromStaticDataMember()) {
4509 // FIXME: Check for explicit specialization?
4510 Diag(D.getIdentifierLoc(),
4511 diag::err_explicit_instantiation_data_member_not_instantiated)
4512 << Prev;
4513 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4514 // FIXME: Can we provide a note showing where this was declared?
4515 return true;
4516 }
4517
Douglas Gregore47f5a72009-10-14 23:41:34 +00004518 // C++0x [temp.explicit]p2:
4519 // If the explicit instantiation is for a member function, a member class
4520 // or a static data member of a class template specialization, the name of
4521 // the class template specialization in the qualified-id for the member
4522 // name shall be a simple-template-id.
4523 //
4524 // C++98 has the same restriction, just worded differently.
4525 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4526 Diag(D.getIdentifierLoc(),
4527 diag::err_explicit_instantiation_without_qualified_id)
4528 << Prev << D.getCXXScopeSpec().getRange();
4529
4530 // Check the scope of this explicit instantiation.
4531 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4532
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004533 // Verify that it is okay to explicitly instantiate here.
4534 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4535 assert(MSInfo && "Missing static data member specialization info?");
4536 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004537 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004538 MSInfo->getTemplateSpecializationKind(),
4539 MSInfo->getPointOfInstantiation(),
4540 SuppressNew))
4541 return true;
4542 if (SuppressNew)
4543 return DeclPtrTy();
4544
Douglas Gregor450f00842009-09-25 18:43:00 +00004545 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004546 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004547 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004548 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4549 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004550
4551 // FIXME: Create an ExplicitInstantiation node?
4552 return DeclPtrTy();
4553 }
4554
Douglas Gregor0e876e02009-09-25 23:53:26 +00004555 // If the declarator is a template-id, translate the parser's template
4556 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004557 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004558 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004559 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4560 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004561 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4562 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004563 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4564 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004565 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004566 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004567 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004568 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004569 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004570
Douglas Gregor450f00842009-09-25 18:43:00 +00004571 // C++ [temp.explicit]p1:
4572 // A [...] function [...] can be explicitly instantiated from its template.
4573 // A member function [...] of a class template can be explicitly
4574 // instantiated from the member definition associated with its class
4575 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004576 llvm::SmallVector<FunctionDecl *, 8> Matches;
4577 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4578 P != PEnd; ++P) {
4579 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004580 if (!HasExplicitTemplateArgs) {
4581 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4582 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4583 Matches.clear();
4584 Matches.push_back(Method);
4585 break;
4586 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004587 }
4588 }
4589
4590 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4591 if (!FunTmpl)
4592 continue;
4593
4594 TemplateDeductionInfo Info(Context);
4595 FunctionDecl *Specialization = 0;
4596 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004597 = DeduceTemplateArguments(FunTmpl,
4598 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004599 R, Specialization, Info)) {
4600 // FIXME: Keep track of almost-matches?
4601 (void)TDK;
4602 continue;
4603 }
4604
4605 Matches.push_back(Specialization);
4606 }
4607
4608 // Find the most specialized function template specialization.
4609 FunctionDecl *Specialization
4610 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4611 D.getIdentifierLoc(),
4612 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4613 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4614 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4615
4616 if (!Specialization)
4617 return true;
4618
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004619 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004620 Diag(D.getIdentifierLoc(),
4621 diag::err_explicit_instantiation_member_function_not_instantiated)
4622 << Specialization
4623 << (Specialization->getTemplateSpecializationKind() ==
4624 TSK_ExplicitSpecialization);
4625 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4626 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004627 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004628
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004629 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004630 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4631 PrevDecl = Specialization;
4632
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004633 if (PrevDecl) {
4634 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004635 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004636 PrevDecl,
4637 PrevDecl->getTemplateSpecializationKind(),
4638 PrevDecl->getPointOfInstantiation(),
4639 SuppressNew))
4640 return true;
4641
4642 // FIXME: We may still want to build some representation of this
4643 // explicit specialization.
4644 if (SuppressNew)
4645 return DeclPtrTy();
4646 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00004647
4648 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004649
4650 if (TSK == TSK_ExplicitInstantiationDefinition)
4651 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4652 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004653
Douglas Gregore47f5a72009-10-14 23:41:34 +00004654 // C++0x [temp.explicit]p2:
4655 // If the explicit instantiation is for a member function, a member class
4656 // or a static data member of a class template specialization, the name of
4657 // the class template specialization in the qualified-id for the member
4658 // name shall be a simple-template-id.
4659 //
4660 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004661 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004662 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004663 D.getCXXScopeSpec().isSet() &&
4664 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4665 Diag(D.getIdentifierLoc(),
4666 diag::err_explicit_instantiation_without_qualified_id)
4667 << Specialization << D.getCXXScopeSpec().getRange();
4668
4669 CheckExplicitInstantiationScope(*this,
4670 FunTmpl? (NamedDecl *)FunTmpl
4671 : Specialization->getInstantiatedFromMemberFunction(),
4672 D.getIdentifierLoc(),
4673 D.getCXXScopeSpec().isSet());
4674
Douglas Gregor450f00842009-09-25 18:43:00 +00004675 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4676 return DeclPtrTy();
4677}
4678
Douglas Gregor333489b2009-03-27 23:10:48 +00004679Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004680Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4681 const CXXScopeSpec &SS, IdentifierInfo *Name,
4682 SourceLocation TagLoc, SourceLocation NameLoc) {
4683 // This has to hold, because SS is expected to be defined.
4684 assert(Name && "Expected a name in a dependent tag");
4685
4686 NestedNameSpecifier *NNS
4687 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4688 if (!NNS)
4689 return true;
4690
4691 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4692 if (T.isNull())
4693 return true;
4694
4695 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4696 QualType ElabType = Context.getElaboratedType(T, TagKind);
4697
4698 return ElabType.getAsOpaquePtr();
4699}
4700
4701Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004702Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4703 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004704 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004705 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4706 if (!NNS)
4707 return true;
4708
4709 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004710 if (T.isNull())
4711 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004712 return T.getAsOpaquePtr();
4713}
4714
Douglas Gregordce2b622009-04-01 00:28:59 +00004715Sema::TypeResult
4716Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4717 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004718 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004719 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004720 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004721 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004722 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004723 assert(TemplateId && "Expected a template specialization type");
4724
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004725 if (computeDeclContext(SS, false)) {
4726 // If we can compute a declaration context, then the "typename"
4727 // keyword was superfluous. Just build a QualifiedNameType to keep
4728 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004729
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004730 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4731 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4732 }
Mike Stump11289f42009-09-09 15:08:12 +00004733
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004734 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004735}
4736
Douglas Gregor333489b2009-03-27 23:10:48 +00004737/// \brief Build the type that describes a C++ typename specifier,
4738/// e.g., "typename T::type".
4739QualType
4740Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4741 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004742 CXXRecordDecl *CurrentInstantiation = 0;
4743 if (NNS->isDependent()) {
4744 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004745
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004746 // If the nested-name-specifier does not refer to the current
4747 // instantiation, then build a typename type.
4748 if (!CurrentInstantiation)
4749 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004750
Douglas Gregorc707da62009-09-02 13:12:51 +00004751 // The nested-name-specifier refers to the current instantiation, so the
4752 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004753 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004754 // extraneous "typename" keywords, and we retroactively apply this DR to
4755 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004756 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004757
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004758 DeclContext *Ctx = 0;
4759
4760 if (CurrentInstantiation)
4761 Ctx = CurrentInstantiation;
4762 else {
4763 CXXScopeSpec SS;
4764 SS.setScopeRep(NNS);
4765 SS.setRange(Range);
4766 if (RequireCompleteDeclContext(SS))
4767 return QualType();
4768
4769 Ctx = computeDeclContext(SS);
4770 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004771 assert(Ctx && "No declaration context?");
4772
4773 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00004774 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4775 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00004776 unsigned DiagID = 0;
4777 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00004778 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004779 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004780 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004781 break;
4782
4783 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004784 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004785 // We found a type. Build a QualifiedNameType, since the
4786 // typename-specifier was just sugar. FIXME: Tell
4787 // QualifiedNameType that it has a "typename" prefix.
4788 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4789 }
4790
4791 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004792 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004793 break;
4794
John McCalle61f2ba2009-11-18 02:36:19 +00004795 case LookupResult::FoundUnresolvedValue:
4796 llvm::llvm_unreachable("unresolved using decl in non-dependent context");
4797 return QualType();
4798
Douglas Gregor333489b2009-03-27 23:10:48 +00004799 case LookupResult::FoundOverloaded:
4800 DiagID = diag::err_typename_nested_not_type;
4801 Referenced = *Result.begin();
4802 break;
4803
John McCall6538c932009-10-10 05:48:19 +00004804 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004805 return QualType();
4806 }
4807
4808 // If we get here, it's because name lookup did not find a
4809 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004810 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004811 if (Referenced)
4812 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4813 << Name;
4814 return QualType();
4815}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004816
4817namespace {
4818 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00004819 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00004820 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004821 SourceLocation Loc;
4822 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004823
Douglas Gregor15acfb92009-08-06 16:20:37 +00004824 public:
Mike Stump11289f42009-09-09 15:08:12 +00004825 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004826 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004827 DeclarationName Entity)
4828 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004829 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004830
4831 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004832 /// transformed.
4833 ///
4834 /// For the purposes of type reconstruction, a type has already been
4835 /// transformed if it is NULL or if it is not dependent.
4836 bool AlreadyTransformed(QualType T) {
4837 return T.isNull() || !T->isDependentType();
4838 }
Mike Stump11289f42009-09-09 15:08:12 +00004839
4840 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004841 /// rebuilt.
4842 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004843
Douglas Gregor15acfb92009-08-06 16:20:37 +00004844 /// \brief Returns the name of the entity whose type is being rebuilt.
4845 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004846
Douglas Gregoref6ab412009-10-27 06:26:26 +00004847 /// \brief Sets the "base" location and entity when that
4848 /// information is known based on another transformation.
4849 void setBase(SourceLocation Loc, DeclarationName Entity) {
4850 this->Loc = Loc;
4851 this->Entity = Entity;
4852 }
4853
Douglas Gregor15acfb92009-08-06 16:20:37 +00004854 /// \brief Transforms an expression by returning the expression itself
4855 /// (an identity function).
4856 ///
4857 /// FIXME: This is completely unsafe; we will need to actually clone the
4858 /// expressions.
4859 Sema::OwningExprResult TransformExpr(Expr *E) {
4860 return getSema().Owned(E);
4861 }
Mike Stump11289f42009-09-09 15:08:12 +00004862
Douglas Gregor15acfb92009-08-06 16:20:37 +00004863 /// \brief Transforms a typename type by determining whether the type now
4864 /// refers to a member of the current instantiation, and then
4865 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004866 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004867 };
4868}
4869
Mike Stump11289f42009-09-09 15:08:12 +00004870QualType
John McCall550e0c22009-10-21 00:40:46 +00004871CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4872 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004873 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004874
Douglas Gregor15acfb92009-08-06 16:20:37 +00004875 NestedNameSpecifier *NNS
4876 = TransformNestedNameSpecifier(T->getQualifier(),
4877 /*FIXME:*/SourceRange(getBaseLocation()));
4878 if (!NNS)
4879 return QualType();
4880
4881 // If the nested-name-specifier did not change, and we cannot compute the
4882 // context corresponding to the nested-name-specifier, then this
4883 // typename type will not change; exit early.
4884 CXXScopeSpec SS;
4885 SS.setRange(SourceRange(getBaseLocation()));
4886 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004887
4888 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004889 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004890 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004891
4892 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004893 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004894 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004895 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004896 = TransformType(QualType(TemplateId, 0));
4897 if (NewTemplateId.isNull())
4898 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004899
Douglas Gregor15acfb92009-08-06 16:20:37 +00004900 if (NNS == T->getQualifier() &&
4901 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004902 Result = QualType(T, 0);
4903 else
4904 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4905 } else
4906 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4907 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004908
John McCall0ad16662009-10-29 08:12:44 +00004909 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4910 NewTL.setNameLoc(TL.getNameLoc());
4911 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004912}
4913
4914/// \brief Rebuilds a type within the context of the current instantiation.
4915///
Mike Stump11289f42009-09-09 15:08:12 +00004916/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004917/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004918/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004919/// partial specialization thereof). This routine will rebuild that type now
4920/// that we have entered the declarator's scope, which may produce different
4921/// canonical types, e.g.,
4922///
4923/// \code
4924/// template<typename T>
4925/// struct X {
4926/// typedef T* pointer;
4927/// pointer data();
4928/// };
4929///
4930/// template<typename T>
4931/// typename X<T>::pointer X<T>::data() { ... }
4932/// \endcode
4933///
4934/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4935/// since we do not know that we can look into X<T> when we parsed the type.
4936/// This function will rebuild the type, performing the lookup of "pointer"
4937/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4938/// as the canonical type of T*, allowing the return types of the out-of-line
4939/// definition and the declaration to match.
4940QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4941 DeclarationName Name) {
4942 if (T.isNull() || !T->isDependentType())
4943 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004944
Douglas Gregor15acfb92009-08-06 16:20:37 +00004945 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4946 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004947}
Douglas Gregorbe999392009-09-15 16:23:51 +00004948
4949/// \brief Produces a formatted string that describes the binding of
4950/// template parameters to template arguments.
4951std::string
4952Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4953 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004954 // FIXME: For variadic templates, we'll need to get the structured list.
4955 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4956 Args.flat_size());
4957}
4958
4959std::string
4960Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4961 const TemplateArgument *Args,
4962 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004963 std::string Result;
4964
Douglas Gregore62e6a02009-11-11 19:13:48 +00004965 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00004966 return Result;
4967
4968 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004969 if (I >= NumArgs)
4970 break;
4971
Douglas Gregorbe999392009-09-15 16:23:51 +00004972 if (I == 0)
4973 Result += "[with ";
4974 else
4975 Result += ", ";
4976
4977 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4978 Result += Id->getName();
4979 } else {
4980 Result += '$';
4981 Result += llvm::utostr(I);
4982 }
4983
4984 Result += " = ";
4985
4986 switch (Args[I].getKind()) {
4987 case TemplateArgument::Null:
4988 Result += "<no value>";
4989 break;
4990
4991 case TemplateArgument::Type: {
4992 std::string TypeStr;
4993 Args[I].getAsType().getAsStringInternal(TypeStr,
4994 Context.PrintingPolicy);
4995 Result += TypeStr;
4996 break;
4997 }
4998
4999 case TemplateArgument::Declaration: {
5000 bool Unnamed = true;
5001 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5002 if (ND->getDeclName()) {
5003 Unnamed = false;
5004 Result += ND->getNameAsString();
5005 }
5006 }
5007
5008 if (Unnamed) {
5009 Result += "<anonymous>";
5010 }
5011 break;
5012 }
5013
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005014 case TemplateArgument::Template: {
5015 std::string Str;
5016 llvm::raw_string_ostream OS(Str);
5017 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5018 Result += OS.str();
5019 break;
5020 }
5021
Douglas Gregorbe999392009-09-15 16:23:51 +00005022 case TemplateArgument::Integral: {
5023 Result += Args[I].getAsIntegral()->toString(10);
5024 break;
5025 }
5026
5027 case TemplateArgument::Expression: {
5028 assert(false && "No expressions in deduced template arguments!");
5029 Result += "<expression>";
5030 break;
5031 }
5032
5033 case TemplateArgument::Pack:
5034 // FIXME: Format template argument packs
5035 Result += "<template argument pack>";
5036 break;
5037 }
5038 }
5039
5040 Result += ']';
5041 return Result;
5042}