blob: 285495a41b0a83a7466bc3a66d290a6710925590 [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"
John McCallbbbbe4e2010-03-11 07:50:04 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000020#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000021#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregorb7bfe792009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
31 if (!D)
32 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
Mike Stump11289f42009-09-09 15:08:12 +000036
Douglas Gregorb7bfe792009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregorb7bfe792009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 return 0;
63}
64
John McCalle66edc12009-11-24 19:00:30 +000065static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
66 LookupResult::Filter filter = R.makeFilter();
67 while (filter.hasNext()) {
68 NamedDecl *Orig = filter.next();
69 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
70 if (!Repl)
71 filter.erase();
72 else if (Repl != Orig)
73 filter.replace(Repl);
74 }
75 filter.done();
76}
77
Douglas Gregorb7bfe792009-09-02 22:59:36 +000078TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000079 CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +000080 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +000081 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +000082 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +000083 TemplateTy &TemplateResult) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +000084 assert(getLangOptions().CPlusPlus && "No template names in C!");
85
Douglas Gregor3cf81312009-11-03 23:16:33 +000086 DeclarationName TName;
87
88 switch (Name.getKind()) {
89 case UnqualifiedId::IK_Identifier:
90 TName = DeclarationName(Name.Identifier);
91 break;
92
93 case UnqualifiedId::IK_OperatorFunctionId:
94 TName = Context.DeclarationNames.getCXXOperatorName(
95 Name.OperatorFunctionId.Operator);
96 break;
97
Alexis Hunted0530f2009-11-28 08:58:14 +000098 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +000099 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
100 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000101
Douglas Gregor3cf81312009-11-03 23:16:33 +0000102 default:
103 return TNK_Non_template;
104 }
Mike Stump11289f42009-09-09 15:08:12 +0000105
John McCalle66edc12009-11-24 19:00:30 +0000106 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000107
Douglas Gregorff18cc12009-12-31 08:11:17 +0000108 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
109 LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +0000110 R.suppressDiagnostics();
111 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
112 if (R.empty())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000113 return TNK_Non_template;
114
John McCalld28ae272009-12-02 08:04:21 +0000115 TemplateName Template;
116 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000117
John McCalld28ae272009-12-02 08:04:21 +0000118 unsigned ResultCount = R.end() - R.begin();
119 if (ResultCount > 1) {
120 // We assume that we'll preserve the qualifier from a function
121 // template name in other ways.
122 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
123 TemplateKind = TNK_Function_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000124 } else {
John McCalld28ae272009-12-02 08:04:21 +0000125 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
126
127 if (SS.isSet() && !SS.isInvalid()) {
128 NestedNameSpecifier *Qualifier
129 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
130 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
131 } else {
132 Template = TemplateName(TD);
133 }
134
135 if (isa<FunctionTemplateDecl>(TD))
136 TemplateKind = TNK_Function_template;
137 else {
138 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
139 TemplateKind = TNK_Type_template;
140 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000141 }
Mike Stump11289f42009-09-09 15:08:12 +0000142
John McCalld28ae272009-12-02 08:04:21 +0000143 TemplateResult = TemplateTy::make(Template);
144 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000145}
146
Douglas Gregor18473f32010-01-12 21:28:44 +0000147bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
148 SourceLocation IILoc,
149 Scope *S,
150 const CXXScopeSpec *SS,
151 TemplateTy &SuggestedTemplate,
152 TemplateNameKind &SuggestedKind) {
153 // We can't recover unless there's a dependent scope specifier preceding the
154 // template name.
155 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
156 computeDeclContext(*SS))
157 return false;
158
159 // The code is missing a 'template' keyword prior to the dependent template
160 // name.
161 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
162 Diag(IILoc, diag::err_template_kw_missing)
163 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000164 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000165 SuggestedTemplate
166 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
167 SuggestedKind = TNK_Dependent_template_name;
168 return true;
169}
170
John McCalle66edc12009-11-24 19:00:30 +0000171void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000172 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000173 QualType ObjectType,
174 bool EnteringContext) {
175 // Determine where to perform name lookup
176 DeclContext *LookupCtx = 0;
177 bool isDependent = false;
178 if (!ObjectType.isNull()) {
179 // This nested-name-specifier occurs in a member access expression, e.g.,
180 // x->B::f, and we are looking into the type of the object.
181 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
182 LookupCtx = computeDeclContext(ObjectType);
183 isDependent = ObjectType->isDependentType();
184 assert((isDependent || !ObjectType->isIncompleteType()) &&
185 "Caller should have completed object type");
186 } else if (SS.isSet()) {
187 // This nested-name-specifier occurs after another nested-name-specifier,
188 // so long into the context associated with the prior nested-name-specifier.
189 LookupCtx = computeDeclContext(SS, EnteringContext);
190 isDependent = isDependentScopeSpecifier(SS);
191
192 // The declaration context must be complete.
193 if (LookupCtx && RequireCompleteDeclContext(SS))
194 return;
195 }
196
197 bool ObjectTypeSearchedInScope = false;
198 if (LookupCtx) {
199 // Perform "qualified" name lookup into the declaration context we
200 // computed, which is either the type of the base of a member access
201 // expression or the declaration context associated with a prior
202 // nested-name-specifier.
203 LookupQualifiedName(Found, LookupCtx);
204
205 if (!ObjectType.isNull() && Found.empty()) {
206 // C++ [basic.lookup.classref]p1:
207 // In a class member access expression (5.2.5), if the . or -> token is
208 // immediately followed by an identifier followed by a <, the
209 // identifier must be looked up to determine whether the < is the
210 // beginning of a template argument list (14.2) or a less-than operator.
211 // The identifier is first looked up in the class of the object
212 // expression. If the identifier is not found, it is then looked up in
213 // the context of the entire postfix-expression and shall name a class
214 // or function template.
215 //
216 // FIXME: When we're instantiating a template, do we actually have to
217 // look in the scope of the template? Seems fishy...
218 if (S) LookupName(Found, S);
219 ObjectTypeSearchedInScope = true;
220 }
221 } else if (isDependent) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000222 // We cannot look into a dependent object type or nested nme
223 // specifier.
John McCalle66edc12009-11-24 19:00:30 +0000224 return;
225 } else {
226 // Perform unqualified name lookup in the current scope.
227 LookupName(Found, S);
228 }
229
230 // FIXME: Cope with ambiguous name-lookup results.
231 assert(!Found.isAmbiguous() &&
232 "Cannot handle template name-lookup ambiguities");
233
Douglas Gregorc119dd52010-01-12 17:06:20 +0000234 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000235 // If we did not find any names, attempt to correct any typos.
236 DeclarationName Name = Found.getLookupName();
237 if (CorrectTypo(Found, S, &SS, LookupCtx)) {
238 FilterAcceptableTemplateNames(Context, Found);
239 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
240 if (LookupCtx)
241 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
242 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000243 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000244 Found.getLookupName().getAsString());
245 else
246 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
247 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000248 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000249 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000250 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
251 Diag(Template->getLocation(), diag::note_previous_decl)
252 << Template->getDeclName();
Douglas Gregorff18cc12009-12-31 08:11:17 +0000253 } else
254 Found.clear();
255 } else {
256 Found.clear();
257 }
258 }
259
John McCalle66edc12009-11-24 19:00:30 +0000260 FilterAcceptableTemplateNames(Context, Found);
261 if (Found.empty())
262 return;
263
264 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
265 // C++ [basic.lookup.classref]p1:
266 // [...] If the lookup in the class of the object expression finds a
267 // template, the name is also looked up in the context of the entire
268 // postfix-expression and [...]
269 //
270 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
271 LookupOrdinaryName);
272 LookupName(FoundOuter, S);
273 FilterAcceptableTemplateNames(Context, FoundOuter);
274 // FIXME: Handle ambiguities in this lookup better
275
276 if (FoundOuter.empty()) {
277 // - if the name is not found, the name found in the class of the
278 // object expression is used, otherwise
279 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
280 // - if the name is found in the context of the entire
281 // postfix-expression and does not name a class template, the name
282 // found in the class of the object expression is used, otherwise
283 } else {
284 // - if the name found is a class template, it must refer to the same
285 // entity as the one found in the class of the object expression,
286 // otherwise the program is ill-formed.
287 if (!Found.isSingleResult() ||
288 Found.getFoundDecl()->getCanonicalDecl()
289 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
290 Diag(Found.getNameLoc(),
291 diag::err_nested_name_member_ref_lookup_ambiguous)
292 << Found.getLookupName();
293 Diag(Found.getRepresentativeDecl()->getLocation(),
294 diag::note_ambig_member_ref_object_type)
295 << ObjectType;
296 Diag(FoundOuter.getFoundDecl()->getLocation(),
297 diag::note_ambig_member_ref_scope);
298
299 // Recover by taking the template that we found in the object
300 // expression's type.
301 }
302 }
303 }
304}
305
John McCallcd4b4772009-12-02 03:53:29 +0000306/// ActOnDependentIdExpression - Handle a dependent id-expression that
307/// was just parsed. This is only possible with an explicit scope
308/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000309Sema::OwningExprResult
310Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
311 DeclarationName Name,
312 SourceLocation NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000313 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000314 const TemplateArgumentListInfo *TemplateArgs) {
315 NestedNameSpecifier *Qualifier
316 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
317
John McCallcd4b4772009-12-02 03:53:29 +0000318 if (!isAddressOfOperand &&
319 isa<CXXMethodDecl>(CurContext) &&
320 cast<CXXMethodDecl>(CurContext)->isInstance()) {
321 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
322
John McCalle66edc12009-11-24 19:00:30 +0000323 // Since the 'this' expression is synthesized, we don't need to
324 // perform the double-lookup check.
325 NamedDecl *FirstQualifierInScope = 0;
326
John McCall2d74de92009-12-01 22:10:20 +0000327 return Owned(CXXDependentScopeMemberExpr::Create(Context,
328 /*This*/ 0, ThisType,
329 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000330 /*Op*/ SourceLocation(),
331 Qualifier, SS.getRange(),
332 FirstQualifierInScope,
333 Name, NameLoc,
334 TemplateArgs));
335 }
336
337 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
338}
339
340Sema::OwningExprResult
341Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
342 DeclarationName Name,
343 SourceLocation NameLoc,
344 const TemplateArgumentListInfo *TemplateArgs) {
345 return Owned(DependentScopeDeclRefExpr::Create(Context,
346 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
347 SS.getRange(),
348 Name, NameLoc,
349 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000350}
351
Douglas Gregor5101c242008-12-05 18:15:24 +0000352/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
353/// that the template parameter 'PrevDecl' is being shadowed by a new
354/// declaration at location Loc. Returns true to indicate that this is
355/// an error, and false otherwise.
356bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000357 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000358
359 // Microsoft Visual C++ permits template parameters to be shadowed.
360 if (getLangOptions().Microsoft)
361 return false;
362
363 // C++ [temp.local]p4:
364 // A template-parameter shall not be redeclared within its
365 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000366 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000367 << cast<NamedDecl>(PrevDecl)->getDeclName();
368 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
369 return true;
370}
371
Douglas Gregor463421d2009-03-03 04:44:36 +0000372/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000373/// the parameter D to reference the templated declaration and return a pointer
374/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000375TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000376 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000377 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000378 return Temp;
379 }
380 return 0;
381}
382
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000383static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
384 const ParsedTemplateArgument &Arg) {
385
386 switch (Arg.getKind()) {
387 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000388 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000389 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
390 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000391 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000392 return TemplateArgumentLoc(TemplateArgument(T), DI);
393 }
394
395 case ParsedTemplateArgument::NonType: {
396 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
397 return TemplateArgumentLoc(TemplateArgument(E), E);
398 }
399
400 case ParsedTemplateArgument::Template: {
401 TemplateName Template
402 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
403 return TemplateArgumentLoc(TemplateArgument(Template),
404 Arg.getScopeSpec().getRange(),
405 Arg.getLocation());
406 }
407 }
408
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000409 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000410 return TemplateArgumentLoc();
411}
412
413/// \brief Translates template arguments as provided by the parser
414/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000415void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
416 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000417 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000418 TemplateArgs.addArgument(translateTemplateArgument(*this,
419 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000420}
421
Douglas Gregor5101c242008-12-05 18:15:24 +0000422/// ActOnTypeParameter - Called when a C++ template type parameter
423/// (e.g., "typename T") has been parsed. Typename specifies whether
424/// the keyword "typename" was used to declare the type parameter
425/// (otherwise, "class" was used), and KeyLoc is the location of the
426/// "class" or "typename" keyword. ParamName is the name of the
427/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000428/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000429/// If the type parameter has a default argument, it will be added
430/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000431Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000432 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000433 SourceLocation KeyLoc,
434 IdentifierInfo *ParamName,
435 SourceLocation ParamNameLoc,
436 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000437 assert(S->isTemplateParamScope() &&
438 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000439 bool Invalid = false;
440
441 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000442 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000443 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000444 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000445 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000446 }
447
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000448 SourceLocation Loc = ParamNameLoc;
449 if (!ParamName)
450 Loc = KeyLoc;
451
Douglas Gregor5101c242008-12-05 18:15:24 +0000452 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000453 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
454 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000455 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000456 if (Invalid)
457 Param->setInvalidDecl();
458
459 if (ParamName) {
460 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000461 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000462 IdResolver.AddDecl(Param);
463 }
464
Chris Lattner83f095c2009-03-28 19:18:32 +0000465 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000466}
467
Douglas Gregordba32632009-02-10 19:49:53 +0000468/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000469/// Default) to the given template type parameter (TypeParam).
470void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000471 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000472 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000473 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000474 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000475 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000476
John McCallbcd03502009-12-07 02:54:59 +0000477 TypeSourceInfo *DefaultTInfo;
478 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall0ad16662009-10-29 08:12:44 +0000479
John McCallbcd03502009-12-07 02:54:59 +0000480 assert(DefaultTInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000481
Anders Carlssond3824352009-06-12 22:30:13 +0000482 // C++0x [temp.param]p9:
483 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000484 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000485 if (Parm->isParameterPack()) {
486 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000487 return;
488 }
Mike Stump11289f42009-09-09 15:08:12 +0000489
Douglas Gregordba32632009-02-10 19:49:53 +0000490 // C++ [temp.param]p14:
491 // A template-parameter shall not be used in its own default argument.
492 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000493
Douglas Gregordba32632009-02-10 19:49:53 +0000494 // Check the template argument itself.
John McCallbcd03502009-12-07 02:54:59 +0000495 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000496 Parm->setInvalidDecl();
497 return;
498 }
499
John McCallbcd03502009-12-07 02:54:59 +0000500 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000501}
502
Douglas Gregor463421d2009-03-03 04:44:36 +0000503/// \brief Check that the type of a non-type template parameter is
504/// well-formed.
505///
506/// \returns the (possibly-promoted) parameter type if valid;
507/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000508QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000509Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
510 // C++ [temp.param]p4:
511 //
512 // A non-type template-parameter shall have one of the following
513 // (optionally cv-qualified) types:
514 //
515 // -- integral or enumeration type,
516 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000517 // -- pointer to object or pointer to function,
518 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000519 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
520 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000521 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000522 T->isReferenceType() ||
523 // -- pointer to member.
524 T->isMemberPointerType() ||
525 // If T is a dependent type, we can't do the check now, so we
526 // assume that it is well-formed.
527 T->isDependentType())
528 return T;
529 // C++ [temp.param]p8:
530 //
531 // A non-type template-parameter of type "array of T" or
532 // "function returning T" is adjusted to be of type "pointer to
533 // T" or "pointer to function returning T", respectively.
534 else if (T->isArrayType())
535 // FIXME: Keep the type prior to promotion?
536 return Context.getArrayDecayedType(T);
537 else if (T->isFunctionType())
538 // FIXME: Keep the type prior to promotion?
539 return Context.getPointerType(T);
540
541 Diag(Loc, diag::err_template_nontype_parm_bad_type)
542 << T;
543
544 return QualType();
545}
546
Douglas Gregor5101c242008-12-05 18:15:24 +0000547/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
548/// template parameter (e.g., "int Size" in "template<int Size>
549/// class Array") has been parsed. S is the current scope and D is
550/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000551Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000552 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000553 unsigned Position) {
John McCallbcd03502009-12-07 02:54:59 +0000554 TypeSourceInfo *TInfo = 0;
555 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000556
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000557 assert(S->isTemplateParamScope() &&
558 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000559 bool Invalid = false;
560
561 IdentifierInfo *ParamName = D.getIdentifier();
562 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000563 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000564 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000565 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000566 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000567 }
568
Douglas Gregor463421d2009-03-03 04:44:36 +0000569 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000570 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000571 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000572 Invalid = true;
573 }
Douglas Gregor81338792009-02-10 17:43:50 +0000574
Douglas Gregor5101c242008-12-05 18:15:24 +0000575 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000576 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
577 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000578 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000579 if (Invalid)
580 Param->setInvalidDecl();
581
582 if (D.getIdentifier()) {
583 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000584 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000585 IdResolver.AddDecl(Param);
586 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000587 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000588}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000589
Douglas Gregordba32632009-02-10 19:49:53 +0000590/// \brief Adds a default argument to the given non-type template
591/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000592void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000593 SourceLocation EqualLoc,
594 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000595 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000596 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000597 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000598
Douglas Gregordba32632009-02-10 19:49:53 +0000599 // C++ [temp.param]p14:
600 // A template-parameter shall not be used in its own default argument.
601 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000602
Douglas Gregordba32632009-02-10 19:49:53 +0000603 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000604 TemplateArgument Converted;
605 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
606 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000607 TemplateParm->setInvalidDecl();
608 return;
609 }
610
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000611 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000612}
613
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000614
615/// ActOnTemplateTemplateParameter - Called when a C++ template template
616/// parameter (e.g. T in template <template <typename> class T> class array)
617/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000618Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
619 SourceLocation TmpLoc,
620 TemplateParamsTy *Params,
621 IdentifierInfo *Name,
622 SourceLocation NameLoc,
623 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000624 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000625 assert(S->isTemplateParamScope() &&
626 "Template template parameter not in template parameter scope!");
627
628 // Construct the parameter object.
629 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000630 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
631 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000632 (TemplateParameterList*)Params);
633
634 // Make sure the parameter is valid.
635 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
636 // do anything yet. However, if the template parameter list or (eventual)
637 // default value is ever invalidated, that will propagate here.
638 bool Invalid = false;
639 if (Invalid) {
640 Param->setInvalidDecl();
641 }
642
643 // If the tt-param has a name, then link the identifier into the scope
644 // and lookup mechanisms.
645 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000646 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000647 IdResolver.AddDecl(Param);
648 }
649
Chris Lattner83f095c2009-03-28 19:18:32 +0000650 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000651}
652
Douglas Gregordba32632009-02-10 19:49:53 +0000653/// \brief Adds a default argument to the given template template
654/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000655void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000656 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000657 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000658 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000659 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000660
Douglas Gregordba32632009-02-10 19:49:53 +0000661 // C++ [temp.param]p14:
662 // A template-parameter shall not be used in its own default argument.
663 // FIXME: Implement this check! Needs a recursive walk over the types.
664
Douglas Gregore62e6a02009-11-11 19:13:48 +0000665 // Check only that we have a template template argument. We don't want to
666 // try to check well-formedness now, because our template template parameter
667 // might have dependent types in its template parameters, which we wouldn't
668 // be able to match now.
669 //
670 // If none of the template template parameter's template arguments mention
671 // other template parameters, we could actually perform more checking here.
672 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000673 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000674 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
675 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
676 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000677 return;
678 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000679
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000680 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000681}
682
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000683/// ActOnTemplateParameterList - Builds a TemplateParameterList that
684/// contains the template parameters in Params/NumParams.
685Sema::TemplateParamsTy *
686Sema::ActOnTemplateParameterList(unsigned Depth,
687 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000688 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000689 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000690 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000691 SourceLocation RAngleLoc) {
692 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000693 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000694
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000695 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000696 (NamedDecl**)Params, NumParams,
697 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000698}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000699
John McCall3e11ebe2010-03-15 10:12:16 +0000700static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
701 if (SS.isSet())
702 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
703 SS.getRange());
704}
705
Douglas Gregorc08f4892009-03-25 00:13:59 +0000706Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000707Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000708 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000709 IdentifierInfo *Name, SourceLocation NameLoc,
710 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000711 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000712 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000713 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000714 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000715 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000716 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000717
718 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000719 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000720 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000721
John McCall27b5c252009-09-14 21:59:20 +0000722 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
723 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000724
725 // There is no such thing as an unnamed class template.
726 if (!Name) {
727 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000728 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000729 }
730
731 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000732 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000733 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000734 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000735 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000736 if (RequireCompleteDeclContext(SS))
737 return true;
738
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000739 SemanticContext = computeDeclContext(SS, true);
740 if (!SemanticContext) {
741 // FIXME: Produce a reasonable diagnostic here
742 return true;
743 }
Mike Stump11289f42009-09-09 15:08:12 +0000744
John McCall27b18f82009-11-17 02:14:36 +0000745 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000746 } else {
747 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000748 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000749 }
Mike Stump11289f42009-09-09 15:08:12 +0000750
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000751 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
752 NamedDecl *PrevDecl = 0;
753 if (Previous.begin() != Previous.end())
754 PrevDecl = *Previous.begin();
755
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000756 // If there is a previous declaration with the same name, check
757 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000758 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000759 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000760
761 // We may have found the injected-class-name of a class template,
762 // class template partial specialization, or class template specialization.
763 // In these cases, grab the template that is being defined or specialized.
764 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
765 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
766 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
767 PrevClassTemplate
768 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
769 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
770 PrevClassTemplate
771 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
772 ->getSpecializedTemplate();
773 }
774 }
775
John McCalld43784f2009-12-18 11:25:59 +0000776 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000777 // C++ [namespace.memdef]p3:
778 // [...] When looking for a prior declaration of a class or a function
779 // declared as a friend, and when the name of the friend class or
780 // function is neither a qualified name nor a template-id, scopes outside
781 // the innermost enclosing namespace scope are not considered.
782 DeclContext *OutermostContext = CurContext;
783 while (!OutermostContext->isFileContext())
784 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000785
786 if (PrevDecl &&
787 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
788 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
John McCall90d3bb92009-12-17 23:21:11 +0000789 SemanticContext = PrevDecl->getDeclContext();
790 } else {
791 // Declarations in outer scopes don't matter. However, the outermost
792 // context we computed is the semantic context for our new
793 // declaration.
794 PrevDecl = PrevClassTemplate = 0;
795 SemanticContext = OutermostContext;
796 }
797
798 if (CurContext->isDependentContext()) {
799 // If this is a dependent context, we don't want to link the friend
800 // class template to the template in scope, because that would perform
801 // checking of the template parameter lists that can't be performed
802 // until the outer context is instantiated.
803 PrevDecl = PrevClassTemplate = 0;
804 }
805 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
806 PrevDecl = PrevClassTemplate = 0;
807
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000808 if (PrevClassTemplate) {
809 // Ensure that the template parameter lists are compatible.
810 if (!TemplateParameterListsAreEqual(TemplateParams,
811 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000812 /*Complain=*/true,
813 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000814 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000815
816 // C++ [temp.class]p4:
817 // In a redeclaration, partial specialization, explicit
818 // specialization or explicit instantiation of a class template,
819 // the class-key shall agree in kind with the original class
820 // template declaration (7.1.5.3).
821 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000822 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000823 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000824 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000825 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000826 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000827 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000828 }
829
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000830 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000831 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000832 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000833 Diag(NameLoc, diag::err_redefinition) << Name;
834 Diag(Def->getLocation(), diag::note_previous_definition);
835 // FIXME: Would it make sense to try to "forget" the previous
836 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000837 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000838 }
839 }
840 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
841 // Maybe we will complain about the shadowed template parameter.
842 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
843 // Just pretend that we didn't see the previous declaration.
844 PrevDecl = 0;
845 } else if (PrevDecl) {
846 // C++ [temp]p5:
847 // A class template shall not have the same name as any other
848 // template, class, function, object, enumeration, enumerator,
849 // namespace, or type in the same scope (3.3), except as specified
850 // in (14.5.4).
851 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
852 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000853 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000854 }
855
Douglas Gregordba32632009-02-10 19:49:53 +0000856 // Check the template parameter list of this declaration, possibly
857 // merging in the template parameter list from the previous class
858 // template declaration.
859 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000860 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
861 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000862 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000863
Douglas Gregore362cea2009-05-10 22:57:19 +0000864 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000865 // declaration!
866
Mike Stump11289f42009-09-09 15:08:12 +0000867 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000868 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000869 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000870 PrevClassTemplate->getTemplatedDecl() : 0,
871 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000872 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000873
874 ClassTemplateDecl *NewTemplate
875 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
876 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000877 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000878 NewClass->setDescribedClassTemplate(NewTemplate);
879
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000880 // Build the type for the class template declaration now.
John McCalle78aac42010-03-10 03:28:59 +0000881 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
882 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000883 assert(T->isDependentType() && "Class template type is not dependent?");
884 (void)T;
885
Douglas Gregorcf915552009-10-13 16:30:37 +0000886 // If we are providing an explicit specialization of a member that is a
887 // class template, make a note of that.
888 if (PrevClassTemplate &&
889 PrevClassTemplate->getInstantiatedFromMemberTemplate())
890 PrevClassTemplate->setMemberSpecialization();
891
Anders Carlsson137108d2009-03-26 01:24:28 +0000892 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000893 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000894 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000895
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000896 // Set the lexical context of these templates
897 NewClass->setLexicalDeclContext(CurContext);
898 NewTemplate->setLexicalDeclContext(CurContext);
899
John McCall9bb74a52009-07-31 02:45:11 +0000900 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000901 NewClass->startDefinition();
902
903 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000904 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000905
John McCall27b5c252009-09-14 21:59:20 +0000906 if (TUK != TUK_Friend)
907 PushOnScopeChains(NewTemplate, S);
908 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000909 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000910 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000911 NewClass->setAccess(PrevClassTemplate->getAccess());
912 }
John McCall27b5c252009-09-14 21:59:20 +0000913
Douglas Gregor3dad8422009-09-26 06:47:28 +0000914 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
915 PrevClassTemplate != NULL);
916
John McCall27b5c252009-09-14 21:59:20 +0000917 // Friend templates are visible in fairly strange ways.
918 if (!CurContext->isDependentContext()) {
919 DeclContext *DC = SemanticContext->getLookupContext();
920 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
921 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
922 PushOnScopeChains(NewTemplate, EnclosingScope,
923 /* AddToContext = */ false);
924 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000925
926 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
927 NewClass->getLocation(),
928 NewTemplate,
929 /*FIXME:*/NewClass->getLocation());
930 Friend->setAccess(AS_public);
931 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000932 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000933
Douglas Gregordba32632009-02-10 19:49:53 +0000934 if (Invalid) {
935 NewTemplate->setInvalidDecl();
936 NewClass->setInvalidDecl();
937 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000938 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000939}
940
Douglas Gregored5731f2009-11-25 17:50:39 +0000941/// \brief Diagnose the presence of a default template argument on a
942/// template parameter, which is ill-formed in certain contexts.
943///
944/// \returns true if the default template argument should be dropped.
945static bool DiagnoseDefaultTemplateArgument(Sema &S,
946 Sema::TemplateParamListContext TPC,
947 SourceLocation ParamLoc,
948 SourceRange DefArgRange) {
949 switch (TPC) {
950 case Sema::TPC_ClassTemplate:
951 return false;
952
953 case Sema::TPC_FunctionTemplate:
954 // C++ [temp.param]p9:
955 // A default template-argument shall not be specified in a
956 // function template declaration or a function template
957 // definition [...]
958 // (This sentence is not in C++0x, per DR226).
959 if (!S.getLangOptions().CPlusPlus0x)
960 S.Diag(ParamLoc,
961 diag::err_template_parameter_default_in_function_template)
962 << DefArgRange;
963 return false;
964
965 case Sema::TPC_ClassTemplateMember:
966 // C++0x [temp.param]p9:
967 // A default template-argument shall not be specified in the
968 // template-parameter-lists of the definition of a member of a
969 // class template that appears outside of the member's class.
970 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
971 << DefArgRange;
972 return true;
973
974 case Sema::TPC_FriendFunctionTemplate:
975 // C++ [temp.param]p9:
976 // A default template-argument shall not be specified in a
977 // friend template declaration.
978 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
979 << DefArgRange;
980 return true;
981
982 // FIXME: C++0x [temp.param]p9 allows default template-arguments
983 // for friend function templates if there is only a single
984 // declaration (and it is a definition). Strange!
985 }
986
987 return false;
988}
989
Douglas Gregordba32632009-02-10 19:49:53 +0000990/// \brief Checks the validity of a template parameter list, possibly
991/// considering the template parameter list from a previous
992/// declaration.
993///
994/// If an "old" template parameter list is provided, it must be
995/// equivalent (per TemplateParameterListsAreEqual) to the "new"
996/// template parameter list.
997///
998/// \param NewParams Template parameter list for a new template
999/// declaration. This template parameter list will be updated with any
1000/// default arguments that are carried through from the previous
1001/// template parameter list.
1002///
1003/// \param OldParams If provided, template parameter list from a
1004/// previous declaration of the same template. Default template
1005/// arguments will be merged from the old template parameter list to
1006/// the new template parameter list.
1007///
Douglas Gregored5731f2009-11-25 17:50:39 +00001008/// \param TPC Describes the context in which we are checking the given
1009/// template parameter list.
1010///
Douglas Gregordba32632009-02-10 19:49:53 +00001011/// \returns true if an error occurred, false otherwise.
1012bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001013 TemplateParameterList *OldParams,
1014 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001015 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001016
Douglas Gregordba32632009-02-10 19:49:53 +00001017 // C++ [temp.param]p10:
1018 // The set of default template-arguments available for use with a
1019 // template declaration or definition is obtained by merging the
1020 // default arguments from the definition (if in scope) and all
1021 // declarations in scope in the same way default function
1022 // arguments are (8.3.6).
1023 bool SawDefaultArgument = false;
1024 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001025
Anders Carlsson327865d2009-06-12 23:20:15 +00001026 bool SawParameterPack = false;
1027 SourceLocation ParameterPackLoc;
1028
Mike Stumpc89c8e32009-02-11 23:03:27 +00001029 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001030 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001031 if (OldParams)
1032 OldParam = OldParams->begin();
1033
1034 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1035 NewParamEnd = NewParams->end();
1036 NewParam != NewParamEnd; ++NewParam) {
1037 // Variables used to diagnose redundant default arguments
1038 bool RedundantDefaultArg = false;
1039 SourceLocation OldDefaultLoc;
1040 SourceLocation NewDefaultLoc;
1041
1042 // Variables used to diagnose missing default arguments
1043 bool MissingDefaultArg = false;
1044
Anders Carlsson327865d2009-06-12 23:20:15 +00001045 // C++0x [temp.param]p11:
1046 // If a template parameter of a class template is a template parameter pack,
1047 // it must be the last template parameter.
1048 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001049 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001050 diag::err_template_param_pack_must_be_last_template_parameter);
1051 Invalid = true;
1052 }
1053
Douglas Gregordba32632009-02-10 19:49:53 +00001054 if (TemplateTypeParmDecl *NewTypeParm
1055 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001056 // Check the presence of a default argument here.
1057 if (NewTypeParm->hasDefaultArgument() &&
1058 DiagnoseDefaultTemplateArgument(*this, TPC,
1059 NewTypeParm->getLocation(),
1060 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1061 .getFullSourceRange()))
1062 NewTypeParm->removeDefaultArgument();
1063
1064 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001065 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001066 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001067
Anders Carlsson327865d2009-06-12 23:20:15 +00001068 if (NewTypeParm->isParameterPack()) {
1069 assert(!NewTypeParm->hasDefaultArgument() &&
1070 "Parameter packs can't have a default argument!");
1071 SawParameterPack = true;
1072 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001073 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001074 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001075 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1076 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1077 SawDefaultArgument = true;
1078 RedundantDefaultArg = true;
1079 PreviousDefaultArgLoc = NewDefaultLoc;
1080 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1081 // Merge the default argument from the old declaration to the
1082 // new declaration.
1083 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001084 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001085 true);
1086 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1087 } else if (NewTypeParm->hasDefaultArgument()) {
1088 SawDefaultArgument = true;
1089 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1090 } else if (SawDefaultArgument)
1091 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001092 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001093 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001094 // Check the presence of a default argument here.
1095 if (NewNonTypeParm->hasDefaultArgument() &&
1096 DiagnoseDefaultTemplateArgument(*this, TPC,
1097 NewNonTypeParm->getLocation(),
1098 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1099 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1100 NewNonTypeParm->setDefaultArgument(0);
1101 }
1102
Mike Stump12b8ce12009-08-04 21:02:39 +00001103 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001104 NonTypeTemplateParmDecl *OldNonTypeParm
1105 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001106 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001107 NewNonTypeParm->hasDefaultArgument()) {
1108 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1109 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1110 SawDefaultArgument = true;
1111 RedundantDefaultArg = true;
1112 PreviousDefaultArgLoc = NewDefaultLoc;
1113 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1114 // Merge the default argument from the old declaration to the
1115 // new declaration.
1116 SawDefaultArgument = true;
1117 // FIXME: We need to create a new kind of "default argument"
1118 // expression that points to a previous template template
1119 // parameter.
1120 NewNonTypeParm->setDefaultArgument(
1121 OldNonTypeParm->getDefaultArgument());
1122 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1123 } else if (NewNonTypeParm->hasDefaultArgument()) {
1124 SawDefaultArgument = true;
1125 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1126 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001127 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001128 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001129 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001130 TemplateTemplateParmDecl *NewTemplateParm
1131 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001132 if (NewTemplateParm->hasDefaultArgument() &&
1133 DiagnoseDefaultTemplateArgument(*this, TPC,
1134 NewTemplateParm->getLocation(),
1135 NewTemplateParm->getDefaultArgument().getSourceRange()))
1136 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1137
1138 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001139 TemplateTemplateParmDecl *OldTemplateParm
1140 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001141 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001142 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001143 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1144 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001145 SawDefaultArgument = true;
1146 RedundantDefaultArg = true;
1147 PreviousDefaultArgLoc = NewDefaultLoc;
1148 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1149 // Merge the default argument from the old declaration to the
1150 // new declaration.
1151 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001152 // FIXME: We need to create a new kind of "default argument" expression
1153 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001154 NewTemplateParm->setDefaultArgument(
1155 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001156 PreviousDefaultArgLoc
1157 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001158 } else if (NewTemplateParm->hasDefaultArgument()) {
1159 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001160 PreviousDefaultArgLoc
1161 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001162 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001163 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001164 }
1165
1166 if (RedundantDefaultArg) {
1167 // C++ [temp.param]p12:
1168 // A template-parameter shall not be given default arguments
1169 // by two different declarations in the same scope.
1170 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1171 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1172 Invalid = true;
1173 } else if (MissingDefaultArg) {
1174 // C++ [temp.param]p11:
1175 // If a template-parameter has a default template-argument,
1176 // all subsequent template-parameters shall have a default
1177 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001178 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001179 diag::err_template_param_default_arg_missing);
1180 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1181 Invalid = true;
1182 }
1183
1184 // If we have an old template parameter list that we're merging
1185 // in, move on to the next parameter.
1186 if (OldParams)
1187 ++OldParam;
1188 }
1189
1190 return Invalid;
1191}
Douglas Gregord32e0282009-02-09 23:23:08 +00001192
Mike Stump11289f42009-09-09 15:08:12 +00001193/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001194/// specifier, returning the template parameter list that applies to the
1195/// name.
1196///
1197/// \param DeclStartLoc the start of the declaration that has a scope
1198/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001199///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001200/// \param SS the scope specifier that will be matched to the given template
1201/// parameter lists. This scope specifier precedes a qualified name that is
1202/// being declared.
1203///
1204/// \param ParamLists the template parameter lists, from the outermost to the
1205/// innermost template parameter lists.
1206///
1207/// \param NumParamLists the number of template parameter lists in ParamLists.
1208///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001209/// \param IsExplicitSpecialization will be set true if the entity being
1210/// declared is an explicit specialization, false otherwise.
1211///
Mike Stump11289f42009-09-09 15:08:12 +00001212/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001213/// name that is preceded by the scope specifier @p SS. This template
1214/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001215/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001216/// template specialization), or may be NULL (if we were's declaring isn't
1217/// itself a template).
1218TemplateParameterList *
1219Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1220 const CXXScopeSpec &SS,
1221 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001222 unsigned NumParamLists,
1223 bool &IsExplicitSpecialization) {
1224 IsExplicitSpecialization = false;
1225
Douglas Gregord8d297c2009-07-21 23:53:31 +00001226 // Find the template-ids that occur within the nested-name-specifier. These
1227 // template-ids will match up with the template parameter lists.
1228 llvm::SmallVector<const TemplateSpecializationType *, 4>
1229 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001230 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1231 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001232 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1233 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001234 const Type *T = NNS->getAsType();
1235 if (!T) break;
1236
1237 // C++0x [temp.expl.spec]p17:
1238 // A member or a member template may be nested within many
1239 // enclosing class templates. In an explicit specialization for
1240 // such a member, the member declaration shall be preceded by a
1241 // template<> for each enclosing class template that is
1242 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001243 //
1244 // Following the existing practice of GNU and EDG, we allow a typedef of a
1245 // template specialization type.
1246 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1247 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001248
Mike Stump11289f42009-09-09 15:08:12 +00001249 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001250 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001251 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1252 if (!Template)
1253 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001254
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001255 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001256 ClassTemplateSpecializationDecl *SpecDecl
1257 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1258 // If the nested name specifier refers to an explicit specialization,
1259 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001260 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1261 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001262 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001263 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001264 }
Mike Stump11289f42009-09-09 15:08:12 +00001265
Douglas Gregord8d297c2009-07-21 23:53:31 +00001266 TemplateIdsInSpecifier.push_back(SpecType);
1267 }
1268 }
Mike Stump11289f42009-09-09 15:08:12 +00001269
Douglas Gregord8d297c2009-07-21 23:53:31 +00001270 // Reverse the list of template-ids in the scope specifier, so that we can
1271 // more easily match up the template-ids and the template parameter lists.
1272 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001273
Douglas Gregord8d297c2009-07-21 23:53:31 +00001274 SourceLocation FirstTemplateLoc = DeclStartLoc;
1275 if (NumParamLists)
1276 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001277
Douglas Gregord8d297c2009-07-21 23:53:31 +00001278 // Match the template-ids found in the specifier to the template parameter
1279 // lists.
1280 unsigned Idx = 0;
1281 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1282 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001283 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1284 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001285 if (Idx >= NumParamLists) {
1286 // We have a template-id without a corresponding template parameter
1287 // list.
1288 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001289 // FIXME: the location information here isn't great.
1290 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001291 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001292 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001293 << SS.getRange();
1294 } else {
1295 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1296 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001297 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001298 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001299 }
1300 return 0;
1301 }
Mike Stump11289f42009-09-09 15:08:12 +00001302
Douglas Gregord8d297c2009-07-21 23:53:31 +00001303 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001304 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001305 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001306 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1307
Mike Stump11289f42009-09-09 15:08:12 +00001308 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001309 = dyn_cast<ClassTemplateDecl>(Template)) {
1310 TemplateParameterList *ExpectedTemplateParams = 0;
1311 // Is this template-id naming the primary template?
1312 if (Context.hasSameType(TemplateId,
John McCalle78aac42010-03-10 03:28:59 +00001313 ClassTemplate->getInjectedClassNameSpecialization(Context)))
Douglas Gregor15301382009-07-30 17:40:51 +00001314 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1315 // ... or a partial specialization?
1316 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1317 = ClassTemplate->findPartialSpecialization(TemplateId))
1318 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1319
1320 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001321 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001322 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001323 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001324 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001325
1326 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001327 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001328 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001329 diag::err_template_param_list_matches_nontemplate)
1330 << TemplateId
1331 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001332 else
1333 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001334 }
Mike Stump11289f42009-09-09 15:08:12 +00001335
Douglas Gregord8d297c2009-07-21 23:53:31 +00001336 // If there were at least as many template-ids as there were template
1337 // parameter lists, then there are no template parameter lists remaining for
1338 // the declaration itself.
1339 if (Idx >= NumParamLists)
1340 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001341
Douglas Gregord8d297c2009-07-21 23:53:31 +00001342 // If there were too many template parameter lists, complain about that now.
1343 if (Idx != NumParamLists - 1) {
1344 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001345 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001346 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001347 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1348 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001349 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1350 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001351
1352 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1353 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1354 diag::note_explicit_template_spec_does_not_need_header)
1355 << ExplicitSpecializationsInSpecifier.back();
1356 ExplicitSpecializationsInSpecifier.pop_back();
1357 }
1358
Douglas Gregord8d297c2009-07-21 23:53:31 +00001359 ++Idx;
1360 }
1361 }
Mike Stump11289f42009-09-09 15:08:12 +00001362
Douglas Gregord8d297c2009-07-21 23:53:31 +00001363 // Return the last template parameter list, which corresponds to the
1364 // entity being declared.
1365 return ParamLists[NumParamLists - 1];
1366}
1367
Douglas Gregordc572a32009-03-30 22:58:21 +00001368QualType Sema::CheckTemplateIdType(TemplateName Name,
1369 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001370 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001371 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001372 if (!Template) {
1373 // The template name does not resolve to a template, so we just
1374 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001375 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001376 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001377
Douglas Gregorc40290e2009-03-09 23:48:35 +00001378 // Check that the template argument list is well-formed for this
1379 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001380 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001381 TemplateArgs.size());
1382 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001383 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001384 return QualType();
1385
Mike Stump11289f42009-09-09 15:08:12 +00001386 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001387 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001388 "Converted template argument list is too short!");
1389
1390 QualType CanonType;
1391
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001392 if (Name.isDependent() ||
1393 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001394 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001395 // This class template specialization is a dependent
1396 // type. Therefore, its canonical type is another class template
1397 // specialization type that contains all of the converted
1398 // arguments in canonical form. This ensures that, e.g., A<T> and
1399 // A<T, T> have identical types when A is declared as:
1400 //
1401 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001402 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001403 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001404 Converted.getFlatArguments(),
1405 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001406
Douglas Gregora8e02e72009-07-28 23:00:59 +00001407 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001408 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001409 // In the future, we need to teach getTemplateSpecializationType to only
1410 // build the canonical type and return that to us.
1411 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001412 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001413 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001414 // Find the class template specialization declaration that
1415 // corresponds to these arguments.
1416 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001417 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001418 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001419 Converted.flatSize(),
1420 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001421 void *InsertPos = 0;
1422 ClassTemplateSpecializationDecl *Decl
1423 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1424 if (!Decl) {
1425 // This is the first time we have referenced this class template
1426 // specialization. Create the canonical declaration and add it to
1427 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001428 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001429 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001430 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001431 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001432 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001433 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1434 Decl->setLexicalDeclContext(CurContext);
1435 }
1436
1437 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001438 assert(isa<RecordType>(CanonType) &&
1439 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001440 }
Mike Stump11289f42009-09-09 15:08:12 +00001441
Douglas Gregorc40290e2009-03-09 23:48:35 +00001442 // Build the fully-sugared type for this class template
1443 // specialization, which refers back to the class template
1444 // specialization we created or found.
John McCall6b51f282009-11-23 01:53:49 +00001445 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001446}
1447
Douglas Gregor67a65642009-02-17 23:15:12 +00001448Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001449Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001450 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001451 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001452 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001453 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001454
Douglas Gregorc40290e2009-03-09 23:48:35 +00001455 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001456 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001457 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001458
John McCall6b51f282009-11-23 01:53:49 +00001459 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001460 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001461
1462 if (Result.isNull())
1463 return true;
1464
John McCallbcd03502009-12-07 02:54:59 +00001465 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001466 TemplateSpecializationTypeLoc TL
1467 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1468 TL.setTemplateNameLoc(TemplateLoc);
1469 TL.setLAngleLoc(LAngleLoc);
1470 TL.setRAngleLoc(RAngleLoc);
1471 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1472 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1473
1474 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001475}
John McCall06f6fe8d2009-09-04 01:14:41 +00001476
John McCalld8fe9af2009-09-08 17:47:29 +00001477Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1478 TagUseKind TUK,
1479 DeclSpec::TST TagSpec,
1480 SourceLocation TagLoc) {
1481 if (TypeResult.isInvalid())
1482 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001483
John McCall0ad16662009-10-29 08:12:44 +00001484 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001485 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001486 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001487
John McCalld8fe9af2009-09-08 17:47:29 +00001488 // Verify the tag specifier.
1489 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001490
John McCalld8fe9af2009-09-08 17:47:29 +00001491 if (const RecordType *RT = Type->getAs<RecordType>()) {
1492 RecordDecl *D = RT->getDecl();
1493
1494 IdentifierInfo *Id = D->getIdentifier();
1495 assert(Id && "templated class must have an identifier");
1496
1497 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1498 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001499 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001500 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001501 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001502 }
1503 }
1504
John McCalld8fe9af2009-09-08 17:47:29 +00001505 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1506
1507 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001508}
1509
John McCalle66edc12009-11-24 19:00:30 +00001510Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1511 LookupResult &R,
1512 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001513 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001514 // FIXME: Can we do any checking at this point? I guess we could check the
1515 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001516 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001517 // though.
John McCalle66edc12009-11-24 19:00:30 +00001518
1519 // These should be filtered out by our callers.
1520 assert(!R.empty() && "empty lookup results when building templateid");
1521 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1522
1523 NestedNameSpecifier *Qualifier = 0;
1524 SourceRange QualifierRange;
1525 if (SS.isSet()) {
1526 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1527 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001528 }
John McCall58cc69d2010-01-27 01:50:18 +00001529
1530 // We don't want lookup warnings at this point.
1531 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001532
John McCalle66edc12009-11-24 19:00:30 +00001533 bool Dependent
1534 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1535 &TemplateArgs);
1536 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001537 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001538 Qualifier, QualifierRange,
1539 R.getLookupName(), R.getNameLoc(),
1540 RequiresADL, TemplateArgs);
John McCall58cc69d2010-01-27 01:50:18 +00001541 ULE->addDecls(R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001542
1543 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001544}
1545
John McCalle66edc12009-11-24 19:00:30 +00001546// We actually only call this from template instantiation.
1547Sema::OwningExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001548Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001549 DeclarationName Name,
1550 SourceLocation NameLoc,
1551 const TemplateArgumentListInfo &TemplateArgs) {
1552 DeclContext *DC;
1553 if (!(DC = computeDeclContext(SS, false)) ||
1554 DC->isDependentContext() ||
1555 RequireCompleteDeclContext(SS))
1556 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001557
John McCalle66edc12009-11-24 19:00:30 +00001558 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1559 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00001560
John McCalle66edc12009-11-24 19:00:30 +00001561 if (R.isAmbiguous())
1562 return ExprError();
1563
1564 if (R.empty()) {
1565 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1566 << Name << SS.getRange();
1567 return ExprError();
1568 }
1569
1570 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1571 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1572 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1573 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1574 return ExprError();
1575 }
1576
1577 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001578}
1579
Douglas Gregorb67535d2009-03-31 00:43:58 +00001580/// \brief Form a dependent template name.
1581///
1582/// This action forms a dependent template name given the template
1583/// name and its (presumably dependent) scope specifier. For
1584/// example, given "MetaFun::template apply", the scope specifier \p
1585/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1586/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001587Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001588Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001589 CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001590 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001591 TypeTy *ObjectType,
1592 bool EnteringContext) {
Douglas Gregor9abe2372010-01-19 16:01:07 +00001593 DeclContext *LookupCtx = 0;
1594 if (SS.isSet())
1595 LookupCtx = computeDeclContext(SS, EnteringContext);
1596 if (!LookupCtx && ObjectType)
1597 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1598 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001599 // C++0x [temp.names]p5:
1600 // If a name prefixed by the keyword template is not the name of
1601 // a template, the program is ill-formed. [Note: the keyword
1602 // template may not be applied to non-template members of class
1603 // templates. -end note ] [ Note: as is the case with the
1604 // typename prefix, the template prefix is allowed in cases
1605 // where it is not strictly necessary; i.e., when the
1606 // nested-name-specifier or the expression on the left of the ->
1607 // or . is not dependent on a template-parameter, or the use
1608 // does not appear in the scope of a template. -end note]
1609 //
1610 // Note: C++03 was more strict here, because it banned the use of
1611 // the "template" keyword prior to a template-name that was not a
1612 // dependent name. C++ DR468 relaxed this requirement (the
1613 // "template" keyword is now permitted). We follow the C++0x
1614 // rules, even in C++03 mode, retroactively applying the DR.
1615 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001616 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001617 EnteringContext, Template);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001618 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1619 isa<CXXRecordDecl>(LookupCtx) &&
1620 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00001621 // This is a dependent template.
1622 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001623 Diag(Name.getSourceRange().getBegin(),
1624 diag::err_template_kw_refers_to_non_template)
1625 << GetNameFromUnqualifiedId(Name)
1626 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001627 return TemplateTy();
Douglas Gregord2e6a452010-01-14 17:47:39 +00001628 } else {
1629 // We found something; return it.
1630 return Template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001631 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001632 }
1633
Mike Stump11289f42009-09-09 15:08:12 +00001634 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001635 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001636
1637 switch (Name.getKind()) {
1638 case UnqualifiedId::IK_Identifier:
1639 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1640 Name.Identifier));
1641
Douglas Gregor71395fa2009-11-04 00:56:37 +00001642 case UnqualifiedId::IK_OperatorFunctionId:
1643 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1644 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001645
1646 case UnqualifiedId::IK_LiteralOperatorId:
1647 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1648
Douglas Gregor3cf81312009-11-03 23:16:33 +00001649 default:
1650 break;
1651 }
1652
1653 Diag(Name.getSourceRange().getBegin(),
1654 diag::err_template_kw_refers_to_non_template)
1655 << GetNameFromUnqualifiedId(Name)
1656 << Name.getSourceRange();
1657 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001658}
1659
Mike Stump11289f42009-09-09 15:08:12 +00001660bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001661 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001662 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001663 const TemplateArgument &Arg = AL.getArgument();
1664
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001665 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001666 switch(Arg.getKind()) {
1667 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001668 // C++ [temp.arg.type]p1:
1669 // A template-argument for a template-parameter which is a
1670 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001671 break;
1672 case TemplateArgument::Template: {
1673 // We have a template type parameter but the template argument
1674 // is a template without any arguments.
1675 SourceRange SR = AL.getSourceRange();
1676 TemplateName Name = Arg.getAsTemplate();
1677 Diag(SR.getBegin(), diag::err_template_missing_args)
1678 << Name << SR;
1679 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1680 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001681
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001682 return true;
1683 }
1684 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001685 // We have a template type parameter but the template argument
1686 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001687 SourceRange SR = AL.getSourceRange();
1688 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001689 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001690
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001691 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001692 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001693 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001694
John McCallbcd03502009-12-07 02:54:59 +00001695 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001696 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001697
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001698 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001699 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001700 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001701 return false;
1702}
1703
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001704/// \brief Substitute template arguments into the default template argument for
1705/// the given template type parameter.
1706///
1707/// \param SemaRef the semantic analysis object for which we are performing
1708/// the substitution.
1709///
1710/// \param Template the template that we are synthesizing template arguments
1711/// for.
1712///
1713/// \param TemplateLoc the location of the template name that started the
1714/// template-id we are checking.
1715///
1716/// \param RAngleLoc the location of the right angle bracket ('>') that
1717/// terminates the template-id.
1718///
1719/// \param Param the template template parameter whose default we are
1720/// substituting into.
1721///
1722/// \param Converted the list of template arguments provided for template
1723/// parameters that precede \p Param in the template parameter list.
1724///
1725/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001726static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001727SubstDefaultTemplateArgument(Sema &SemaRef,
1728 TemplateDecl *Template,
1729 SourceLocation TemplateLoc,
1730 SourceLocation RAngleLoc,
1731 TemplateTypeParmDecl *Param,
1732 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001733 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001734
1735 // If the argument type is dependent, instantiate it now based
1736 // on the previously-computed template arguments.
1737 if (ArgType->getType()->isDependentType()) {
1738 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1739 /*TakeArgs=*/false);
1740
1741 MultiLevelTemplateArgumentList AllTemplateArgs
1742 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1743
1744 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1745 Template, Converted.getFlatArguments(),
1746 Converted.flatSize(),
1747 SourceRange(TemplateLoc, RAngleLoc));
1748
1749 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1750 Param->getDefaultArgumentLoc(),
1751 Param->getDeclName());
1752 }
1753
1754 return ArgType;
1755}
1756
1757/// \brief Substitute template arguments into the default template argument for
1758/// the given non-type template parameter.
1759///
1760/// \param SemaRef the semantic analysis object for which we are performing
1761/// the substitution.
1762///
1763/// \param Template the template that we are synthesizing template arguments
1764/// for.
1765///
1766/// \param TemplateLoc the location of the template name that started the
1767/// template-id we are checking.
1768///
1769/// \param RAngleLoc the location of the right angle bracket ('>') that
1770/// terminates the template-id.
1771///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001772/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001773/// substituting into.
1774///
1775/// \param Converted the list of template arguments provided for template
1776/// parameters that precede \p Param in the template parameter list.
1777///
1778/// \returns the substituted template argument, or NULL if an error occurred.
1779static Sema::OwningExprResult
1780SubstDefaultTemplateArgument(Sema &SemaRef,
1781 TemplateDecl *Template,
1782 SourceLocation TemplateLoc,
1783 SourceLocation RAngleLoc,
1784 NonTypeTemplateParmDecl *Param,
1785 TemplateArgumentListBuilder &Converted) {
1786 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1787 /*TakeArgs=*/false);
1788
1789 MultiLevelTemplateArgumentList AllTemplateArgs
1790 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1791
1792 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1793 Template, Converted.getFlatArguments(),
1794 Converted.flatSize(),
1795 SourceRange(TemplateLoc, RAngleLoc));
1796
1797 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1798}
1799
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001800/// \brief Substitute template arguments into the default template argument for
1801/// the given template template parameter.
1802///
1803/// \param SemaRef the semantic analysis object for which we are performing
1804/// the substitution.
1805///
1806/// \param Template the template that we are synthesizing template arguments
1807/// for.
1808///
1809/// \param TemplateLoc the location of the template name that started the
1810/// template-id we are checking.
1811///
1812/// \param RAngleLoc the location of the right angle bracket ('>') that
1813/// terminates the template-id.
1814///
1815/// \param Param the template template parameter whose default we are
1816/// substituting into.
1817///
1818/// \param Converted the list of template arguments provided for template
1819/// parameters that precede \p Param in the template parameter list.
1820///
1821/// \returns the substituted template argument, or NULL if an error occurred.
1822static TemplateName
1823SubstDefaultTemplateArgument(Sema &SemaRef,
1824 TemplateDecl *Template,
1825 SourceLocation TemplateLoc,
1826 SourceLocation RAngleLoc,
1827 TemplateTemplateParmDecl *Param,
1828 TemplateArgumentListBuilder &Converted) {
1829 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1830 /*TakeArgs=*/false);
1831
1832 MultiLevelTemplateArgumentList AllTemplateArgs
1833 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1834
1835 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1836 Template, Converted.getFlatArguments(),
1837 Converted.flatSize(),
1838 SourceRange(TemplateLoc, RAngleLoc));
1839
1840 return SemaRef.SubstTemplateName(
1841 Param->getDefaultArgument().getArgument().getAsTemplate(),
1842 Param->getDefaultArgument().getTemplateNameLoc(),
1843 AllTemplateArgs);
1844}
1845
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001846/// \brief If the given template parameter has a default template
1847/// argument, substitute into that default template argument and
1848/// return the corresponding template argument.
1849TemplateArgumentLoc
1850Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1851 SourceLocation TemplateLoc,
1852 SourceLocation RAngleLoc,
1853 Decl *Param,
1854 TemplateArgumentListBuilder &Converted) {
1855 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1856 if (!TypeParm->hasDefaultArgument())
1857 return TemplateArgumentLoc();
1858
John McCallbcd03502009-12-07 02:54:59 +00001859 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001860 TemplateLoc,
1861 RAngleLoc,
1862 TypeParm,
1863 Converted);
1864 if (DI)
1865 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1866
1867 return TemplateArgumentLoc();
1868 }
1869
1870 if (NonTypeTemplateParmDecl *NonTypeParm
1871 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1872 if (!NonTypeParm->hasDefaultArgument())
1873 return TemplateArgumentLoc();
1874
1875 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1876 TemplateLoc,
1877 RAngleLoc,
1878 NonTypeParm,
1879 Converted);
1880 if (Arg.isInvalid())
1881 return TemplateArgumentLoc();
1882
1883 Expr *ArgE = Arg.takeAs<Expr>();
1884 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1885 }
1886
1887 TemplateTemplateParmDecl *TempTempParm
1888 = cast<TemplateTemplateParmDecl>(Param);
1889 if (!TempTempParm->hasDefaultArgument())
1890 return TemplateArgumentLoc();
1891
1892 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1893 TemplateLoc,
1894 RAngleLoc,
1895 TempTempParm,
1896 Converted);
1897 if (TName.isNull())
1898 return TemplateArgumentLoc();
1899
1900 return TemplateArgumentLoc(TemplateArgument(TName),
1901 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1902 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1903}
1904
Douglas Gregorda0fb532009-11-11 19:31:23 +00001905/// \brief Check that the given template argument corresponds to the given
1906/// template parameter.
1907bool Sema::CheckTemplateArgument(NamedDecl *Param,
1908 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001909 TemplateDecl *Template,
1910 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001911 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001912 TemplateArgumentListBuilder &Converted,
1913 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001914 // Check template type parameters.
1915 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001916 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001917
Douglas Gregoreebed722009-11-11 19:41:09 +00001918 // Check non-type template parameters.
1919 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001920 // Do substitution on the type of the non-type template parameter
1921 // with the template arguments we've seen thus far.
1922 QualType NTTPType = NTTP->getType();
1923 if (NTTPType->isDependentType()) {
1924 // Do substitution on the type of the non-type template parameter.
1925 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1926 NTTP, Converted.getFlatArguments(),
1927 Converted.flatSize(),
1928 SourceRange(TemplateLoc, RAngleLoc));
1929
1930 TemplateArgumentList TemplateArgs(Context, Converted,
1931 /*TakeArgs=*/false);
1932 NTTPType = SubstType(NTTPType,
1933 MultiLevelTemplateArgumentList(TemplateArgs),
1934 NTTP->getLocation(),
1935 NTTP->getDeclName());
1936 // If that worked, check the non-type template parameter type
1937 // for validity.
1938 if (!NTTPType.isNull())
1939 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1940 NTTP->getLocation());
1941 if (NTTPType.isNull())
1942 return true;
1943 }
1944
1945 switch (Arg.getArgument().getKind()) {
1946 case TemplateArgument::Null:
1947 assert(false && "Should never see a NULL template argument here");
1948 return true;
1949
1950 case TemplateArgument::Expression: {
1951 Expr *E = Arg.getArgument().getAsExpr();
1952 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001953 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001954 return true;
1955
1956 Converted.Append(Result);
1957 break;
1958 }
1959
1960 case TemplateArgument::Declaration:
1961 case TemplateArgument::Integral:
1962 // We've already checked this template argument, so just copy
1963 // it to the list of converted arguments.
1964 Converted.Append(Arg.getArgument());
1965 break;
1966
1967 case TemplateArgument::Template:
1968 // We were given a template template argument. It may not be ill-formed;
1969 // see below.
1970 if (DependentTemplateName *DTN
1971 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1972 // We have a template argument such as \c T::template X, which we
1973 // parsed as a template template argument. However, since we now
1974 // know that we need a non-type template argument, convert this
1975 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00001976 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1977 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00001978 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00001979 DTN->getIdentifier(),
1980 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00001981
1982 TemplateArgument Result;
1983 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1984 return true;
1985
1986 Converted.Append(Result);
1987 break;
1988 }
1989
1990 // We have a template argument that actually does refer to a class
1991 // template, template alias, or template template parameter, and
1992 // therefore cannot be a non-type template argument.
1993 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1994 << Arg.getSourceRange();
1995
1996 Diag(Param->getLocation(), diag::note_template_param_here);
1997 return true;
1998
1999 case TemplateArgument::Type: {
2000 // We have a non-type template parameter but the template
2001 // argument is a type.
2002
2003 // C++ [temp.arg]p2:
2004 // In a template-argument, an ambiguity between a type-id and
2005 // an expression is resolved to a type-id, regardless of the
2006 // form of the corresponding template-parameter.
2007 //
2008 // We warn specifically about this case, since it can be rather
2009 // confusing for users.
2010 QualType T = Arg.getArgument().getAsType();
2011 SourceRange SR = Arg.getSourceRange();
2012 if (T->isFunctionType())
2013 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2014 else
2015 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2016 Diag(Param->getLocation(), diag::note_template_param_here);
2017 return true;
2018 }
2019
2020 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002021 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002022 break;
2023 }
2024
2025 return false;
2026 }
2027
2028
2029 // Check template template parameters.
2030 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2031
2032 // Substitute into the template parameter list of the template
2033 // template parameter, since previously-supplied template arguments
2034 // may appear within the template template parameter.
2035 {
2036 // Set up a template instantiation context.
2037 LocalInstantiationScope Scope(*this);
2038 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2039 TempParm, Converted.getFlatArguments(),
2040 Converted.flatSize(),
2041 SourceRange(TemplateLoc, RAngleLoc));
2042
2043 TemplateArgumentList TemplateArgs(Context, Converted,
2044 /*TakeArgs=*/false);
2045 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2046 SubstDecl(TempParm, CurContext,
2047 MultiLevelTemplateArgumentList(TemplateArgs)));
2048 if (!TempParm)
2049 return true;
2050
2051 // FIXME: TempParam is leaked.
2052 }
2053
2054 switch (Arg.getArgument().getKind()) {
2055 case TemplateArgument::Null:
2056 assert(false && "Should never see a NULL template argument here");
2057 return true;
2058
2059 case TemplateArgument::Template:
2060 if (CheckTemplateArgument(TempParm, Arg))
2061 return true;
2062
2063 Converted.Append(Arg.getArgument());
2064 break;
2065
2066 case TemplateArgument::Expression:
2067 case TemplateArgument::Type:
2068 // We have a template template parameter but the template
2069 // argument does not refer to a template.
2070 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2071 return true;
2072
2073 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002074 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002075 "Declaration argument with template template parameter");
2076 break;
2077 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002078 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002079 "Integral argument with template template parameter");
2080 break;
2081
2082 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002083 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002084 break;
2085 }
2086
2087 return false;
2088}
2089
Douglas Gregord32e0282009-02-09 23:23:08 +00002090/// \brief Check that the given template argument list is well-formed
2091/// for specializing the given template.
2092bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2093 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002094 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002095 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002096 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002097 TemplateParameterList *Params = Template->getTemplateParameters();
2098 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002099 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002100 bool Invalid = false;
2101
John McCall6b51f282009-11-23 01:53:49 +00002102 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2103
Mike Stump11289f42009-09-09 15:08:12 +00002104 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002105 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002106
Anders Carlsson15201f12009-06-13 02:08:00 +00002107 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002108 (NumArgs < Params->getMinRequiredArguments() &&
2109 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002110 // FIXME: point at either the first arg beyond what we can handle,
2111 // or the '>', depending on whether we have too many or too few
2112 // arguments.
2113 SourceRange Range;
2114 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002115 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002116 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2117 << (NumArgs > NumParams)
2118 << (isa<ClassTemplateDecl>(Template)? 0 :
2119 isa<FunctionTemplateDecl>(Template)? 1 :
2120 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2121 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002122 Diag(Template->getLocation(), diag::note_template_decl_here)
2123 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002124 Invalid = true;
2125 }
Mike Stump11289f42009-09-09 15:08:12 +00002126
2127 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002128 // [...] The type and form of each template-argument specified in
2129 // a template-id shall match the type and form specified for the
2130 // corresponding parameter declared by the template in its
2131 // template-parameter-list.
2132 unsigned ArgIdx = 0;
2133 for (TemplateParameterList::iterator Param = Params->begin(),
2134 ParamEnd = Params->end();
2135 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002136 if (ArgIdx > NumArgs && PartialTemplateArgs)
2137 break;
Mike Stump11289f42009-09-09 15:08:12 +00002138
Douglas Gregoreebed722009-11-11 19:41:09 +00002139 // If we have a template parameter pack, check every remaining template
2140 // argument against that template parameter pack.
2141 if ((*Param)->isTemplateParameterPack()) {
2142 Converted.BeginPack();
2143 for (; ArgIdx < NumArgs; ++ArgIdx) {
2144 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2145 TemplateLoc, RAngleLoc, Converted)) {
2146 Invalid = true;
2147 break;
2148 }
2149 }
2150 Converted.EndPack();
2151 continue;
2152 }
2153
Douglas Gregor84d49a22009-11-11 21:54:23 +00002154 if (ArgIdx < NumArgs) {
2155 // Check the template argument we were given.
2156 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2157 TemplateLoc, RAngleLoc, Converted))
2158 return true;
2159
2160 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002161 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002162
Douglas Gregor84d49a22009-11-11 21:54:23 +00002163 // We have a default template argument that we will use.
2164 TemplateArgumentLoc Arg;
2165
2166 // Retrieve the default template argument from the template
2167 // parameter. For each kind of template parameter, we substitute the
2168 // template arguments provided thus far and any "outer" template arguments
2169 // (when the template parameter was part of a nested template) into
2170 // the default argument.
2171 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2172 if (!TTP->hasDefaultArgument()) {
2173 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2174 break;
2175 }
2176
John McCallbcd03502009-12-07 02:54:59 +00002177 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002178 Template,
2179 TemplateLoc,
2180 RAngleLoc,
2181 TTP,
2182 Converted);
2183 if (!ArgType)
2184 return true;
2185
2186 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2187 ArgType);
2188 } else if (NonTypeTemplateParmDecl *NTTP
2189 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2190 if (!NTTP->hasDefaultArgument()) {
2191 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2192 break;
2193 }
2194
2195 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2196 TemplateLoc,
2197 RAngleLoc,
2198 NTTP,
2199 Converted);
2200 if (E.isInvalid())
2201 return true;
2202
2203 Expr *Ex = E.takeAs<Expr>();
2204 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2205 } else {
2206 TemplateTemplateParmDecl *TempParm
2207 = cast<TemplateTemplateParmDecl>(*Param);
2208
2209 if (!TempParm->hasDefaultArgument()) {
2210 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2211 break;
2212 }
2213
2214 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2215 TemplateLoc,
2216 RAngleLoc,
2217 TempParm,
2218 Converted);
2219 if (Name.isNull())
2220 return true;
2221
2222 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2223 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2224 TempParm->getDefaultArgument().getTemplateNameLoc());
2225 }
2226
2227 // Introduce an instantiation record that describes where we are using
2228 // the default template argument.
2229 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2230 Converted.getFlatArguments(),
2231 Converted.flatSize(),
2232 SourceRange(TemplateLoc, RAngleLoc));
2233
2234 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002235 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002236 RAngleLoc, Converted))
2237 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002238 }
2239
2240 return Invalid;
2241}
2242
2243/// \brief Check a template argument against its corresponding
2244/// template type parameter.
2245///
2246/// This routine implements the semantics of C++ [temp.arg.type]. It
2247/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002248bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002249 TypeSourceInfo *ArgInfo) {
2250 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002251 QualType Arg = ArgInfo->getType();
2252
Douglas Gregord32e0282009-02-09 23:23:08 +00002253 // C++ [temp.arg.type]p2:
2254 // A local type, a type with no linkage, an unnamed type or a type
2255 // compounded from any of these types shall not be used as a
2256 // template-argument for a template type-parameter.
2257 //
2258 // FIXME: Perform the recursive and no-linkage type checks.
2259 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002260 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002261 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002262 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002263 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002264 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2265 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2266 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2267 << QualType(Tag, 0) << SR;
2268 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002269 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002270 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2271 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002272 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2273 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002274 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2275 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2276 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002277 }
2278
2279 return false;
2280}
2281
Douglas Gregorccb07762009-02-11 19:52:55 +00002282/// \brief Checks whether the given template argument is the address
2283/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002284static bool
2285CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2286 NonTypeTemplateParmDecl *Param,
2287 QualType ParamType,
2288 Expr *ArgIn,
2289 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002290 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002291 Expr *Arg = ArgIn;
2292 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002293
2294 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002295 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002296 Arg = Cast->getSubExpr();
2297
2298 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002299 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002300 // A template-argument for a non-type, non-template
2301 // template-parameter shall be one of: [...]
2302 //
2303 // -- the address of an object or function with external
2304 // linkage, including function templates and function
2305 // template-ids but excluding non-static class members,
2306 // expressed as & id-expression where the & is optional if
2307 // the name refers to a function or array, or if the
2308 // corresponding template-parameter is a reference; or
2309 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002310
Douglas Gregorccb07762009-02-11 19:52:55 +00002311 // Ignore (and complain about) any excess parentheses.
2312 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2313 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002314 S.Diag(Arg->getSourceRange().getBegin(),
2315 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002316 << Arg->getSourceRange();
2317 Invalid = true;
2318 }
2319
2320 Arg = Parens->getSubExpr();
2321 }
2322
Douglas Gregorb242683d2010-04-01 18:32:35 +00002323 bool AddressTaken = false;
2324 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002325 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002326 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002327 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002328 AddressTaken = true;
2329 AddrOpLoc = UnOp->getOperatorLoc();
2330 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002331 } else
2332 DRE = dyn_cast<DeclRefExpr>(Arg);
2333
Douglas Gregorb242683d2010-04-01 18:32:35 +00002334 if (!DRE) {
2335 if (S.Context.hasSameUnqualifiedType(ArgType, S.Context.OverloadTy)) {
2336 S.Diag(Arg->getLocStart(),
2337 diag::err_template_arg_unresolved_overloaded_function)
2338 << ParamType << Arg->getSourceRange();
2339 } else {
2340 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2341 << Arg->getSourceRange();
2342 }
2343 S.Diag(Param->getLocation(), diag::note_template_param_here);
2344 return true;
2345 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002346
2347 // Stop checking the precise nature of the argument if it is value dependent,
2348 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002349 if (Arg->isValueDependent()) {
2350 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002351 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002352 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002353
Douglas Gregorb242683d2010-04-01 18:32:35 +00002354 if (!isa<ValueDecl>(DRE->getDecl())) {
2355 S.Diag(Arg->getSourceRange().getBegin(),
2356 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002357 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002358 S.Diag(Param->getLocation(), diag::note_template_param_here);
2359 return true;
2360 }
2361
2362 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002363
2364 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002365 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2366 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002367 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002368 S.Diag(Param->getLocation(), diag::note_template_param_here);
2369 return true;
2370 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002371
2372 // Cannot refer to non-static member functions
2373 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002374 if (!Method->isStatic()) {
2375 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002376 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002377 S.Diag(Param->getLocation(), diag::note_template_param_here);
2378 return true;
2379 }
Mike Stump11289f42009-09-09 15:08:12 +00002380
Douglas Gregorccb07762009-02-11 19:52:55 +00002381 // Functions must have external linkage.
2382 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002383 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002384 S.Diag(Arg->getSourceRange().getBegin(),
2385 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002386 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002387 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002388 << true;
2389 return true;
2390 }
2391
2392 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002393 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002394
Douglas Gregorb242683d2010-04-01 18:32:35 +00002395 // If the template parameter has pointer type, the function decays.
2396 if (ParamType->isPointerType() && !AddressTaken)
2397 ArgType = S.Context.getPointerType(Func->getType());
2398 else if (AddressTaken && ParamType->isReferenceType()) {
2399 // If we originally had an address-of operator, but the
2400 // parameter has reference type, complain and (if things look
2401 // like they will work) drop the address-of operator.
2402 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2403 ParamType.getNonReferenceType())) {
2404 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2405 << ParamType;
2406 S.Diag(Param->getLocation(), diag::note_template_param_here);
2407 return true;
2408 }
2409
2410 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2411 << ParamType
2412 << FixItHint::CreateRemoval(AddrOpLoc);
2413 S.Diag(Param->getLocation(), diag::note_template_param_here);
2414
2415 ArgType = Func->getType();
2416 }
2417 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002418 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002419 S.Diag(Arg->getSourceRange().getBegin(),
2420 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002421 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002422 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002423 << true;
2424 return true;
2425 }
2426
Douglas Gregorb242683d2010-04-01 18:32:35 +00002427 // A value of reference type is not an object.
2428 if (Var->getType()->isReferenceType()) {
2429 S.Diag(Arg->getSourceRange().getBegin(),
2430 diag::err_template_arg_reference_var)
2431 << Var->getType() << Arg->getSourceRange();
2432 S.Diag(Param->getLocation(), diag::note_template_param_here);
2433 return true;
2434 }
2435
Douglas Gregorccb07762009-02-11 19:52:55 +00002436 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002437 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002438
2439 // If the template parameter has pointer type, we must have taken
2440 // the address of this object.
2441 if (ParamType->isReferenceType()) {
2442 if (AddressTaken) {
2443 // If we originally had an address-of operator, but the
2444 // parameter has reference type, complain and (if things look
2445 // like they will work) drop the address-of operator.
2446 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2447 ParamType.getNonReferenceType())) {
2448 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2449 << ParamType;
2450 S.Diag(Param->getLocation(), diag::note_template_param_here);
2451 return true;
2452 }
2453
2454 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2455 << ParamType
2456 << FixItHint::CreateRemoval(AddrOpLoc);
2457 S.Diag(Param->getLocation(), diag::note_template_param_here);
2458
2459 ArgType = Var->getType();
2460 }
2461 } else if (!AddressTaken && ParamType->isPointerType()) {
2462 if (Var->getType()->isArrayType()) {
2463 // Array-to-pointer decay.
2464 ArgType = S.Context.getArrayDecayedType(Var->getType());
2465 } else {
2466 // If the template parameter has pointer type but the address of
2467 // this object was not taken, complain and (possibly) recover by
2468 // taking the address of the entity.
2469 ArgType = S.Context.getPointerType(Var->getType());
2470 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2471 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2472 << ParamType;
2473 S.Diag(Param->getLocation(), diag::note_template_param_here);
2474 return true;
2475 }
2476
2477 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2478 << ParamType
2479 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2480
2481 S.Diag(Param->getLocation(), diag::note_template_param_here);
2482 }
2483 }
2484 } else {
2485 // We found something else, but we don't know specifically what it is.
2486 S.Diag(Arg->getSourceRange().getBegin(),
2487 diag::err_template_arg_not_object_or_func)
2488 << Arg->getSourceRange();
2489 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2490 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002491 }
Mike Stump11289f42009-09-09 15:08:12 +00002492
Douglas Gregorb242683d2010-04-01 18:32:35 +00002493 if (ParamType->isPointerType() &&
2494 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2495 S.IsQualificationConversion(ArgType, ParamType)) {
2496 // For pointer-to-object types, qualification conversions are
2497 // permitted.
2498 } else {
2499 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2500 if (!ParamRef->getPointeeType()->isFunctionType()) {
2501 // C++ [temp.arg.nontype]p5b3:
2502 // For a non-type template-parameter of type reference to
2503 // object, no conversions apply. The type referred to by the
2504 // reference may be more cv-qualified than the (otherwise
2505 // identical) type of the template- argument. The
2506 // template-parameter is bound directly to the
2507 // template-argument, which shall be an lvalue.
2508
2509 // FIXME: Other qualifiers?
2510 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2511 unsigned ArgQuals = ArgType.getCVRQualifiers();
2512
2513 if ((ParamQuals | ArgQuals) != ParamQuals) {
2514 S.Diag(Arg->getSourceRange().getBegin(),
2515 diag::err_template_arg_ref_bind_ignores_quals)
2516 << ParamType << Arg->getType()
2517 << Arg->getSourceRange();
2518 S.Diag(Param->getLocation(), diag::note_template_param_here);
2519 return true;
2520 }
2521 }
2522 }
2523
2524 // At this point, the template argument refers to an object or
2525 // function with external linkage. We now need to check whether the
2526 // argument and parameter types are compatible.
2527 if (!S.Context.hasSameUnqualifiedType(ArgType,
2528 ParamType.getNonReferenceType())) {
2529 // We can't perform this conversion or binding.
2530 if (ParamType->isReferenceType())
2531 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2532 << ParamType << Arg->getType() << Arg->getSourceRange();
2533 else
2534 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2535 << Arg->getType() << ParamType << Arg->getSourceRange();
2536 S.Diag(Param->getLocation(), diag::note_template_param_here);
2537 return true;
2538 }
2539 }
2540
2541 // Create the template argument.
2542 Converted = TemplateArgument(Entity->getCanonicalDecl());
2543 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002544}
2545
2546/// \brief Checks whether the given template argument is a pointer to
2547/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002548bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2549 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002550 bool Invalid = false;
2551
2552 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002553 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002554 Arg = Cast->getSubExpr();
2555
2556 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002557 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002558 // A template-argument for a non-type, non-template
2559 // template-parameter shall be one of: [...]
2560 //
2561 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002562 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002563
2564 // Ignore (and complain about) any excess parentheses.
2565 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2566 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002567 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002568 diag::err_template_arg_extra_parens)
2569 << Arg->getSourceRange();
2570 Invalid = true;
2571 }
2572
2573 Arg = Parens->getSubExpr();
2574 }
2575
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002576 // A pointer-to-member constant written &Class::member.
2577 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002578 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2579 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2580 if (DRE && !DRE->getQualifier())
2581 DRE = 0;
2582 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002583 }
2584 // A constant of pointer-to-member type.
2585 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2586 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2587 if (VD->getType()->isMemberPointerType()) {
2588 if (isa<NonTypeTemplateParmDecl>(VD) ||
2589 (isa<VarDecl>(VD) &&
2590 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2591 if (Arg->isTypeDependent() || Arg->isValueDependent())
2592 Converted = TemplateArgument(Arg->Retain());
2593 else
2594 Converted = TemplateArgument(VD->getCanonicalDecl());
2595 return Invalid;
2596 }
2597 }
2598 }
2599
2600 DRE = 0;
2601 }
2602
Douglas Gregorccb07762009-02-11 19:52:55 +00002603 if (!DRE)
2604 return Diag(Arg->getSourceRange().getBegin(),
2605 diag::err_template_arg_not_pointer_to_member_form)
2606 << Arg->getSourceRange();
2607
2608 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2609 assert((isa<FieldDecl>(DRE->getDecl()) ||
2610 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2611 "Only non-static member pointers can make it here");
2612
2613 // Okay: this is the address of a non-static member, and therefore
2614 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002615 if (Arg->isTypeDependent() || Arg->isValueDependent())
2616 Converted = TemplateArgument(Arg->Retain());
2617 else
2618 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002619 return Invalid;
2620 }
2621
2622 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002623 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002624 diag::err_template_arg_not_pointer_to_member_form)
2625 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002626 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002627 diag::note_template_arg_refers_here);
2628 return true;
2629}
2630
Douglas Gregord32e0282009-02-09 23:23:08 +00002631/// \brief Check a template argument against its corresponding
2632/// non-type template parameter.
2633///
Douglas Gregor463421d2009-03-03 04:44:36 +00002634/// This routine implements the semantics of C++ [temp.arg.nontype].
2635/// It returns true if an error occurred, and false otherwise. \p
2636/// InstantiatedParamType is the type of the non-type template
2637/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002638///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002639/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002640bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002641 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002642 TemplateArgument &Converted,
2643 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002644 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2645
Douglas Gregor86560402009-02-10 23:36:10 +00002646 // If either the parameter has a dependent type or the argument is
2647 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002648 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2649 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002650 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002651 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002652 }
Douglas Gregor86560402009-02-10 23:36:10 +00002653
2654 // C++ [temp.arg.nontype]p5:
2655 // The following conversions are performed on each expression used
2656 // as a non-type template-argument. If a non-type
2657 // template-argument cannot be converted to the type of the
2658 // corresponding template-parameter then the program is
2659 // ill-formed.
2660 //
2661 // -- for a non-type template-parameter of integral or
2662 // enumeration type, integral promotions (4.5) and integral
2663 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002664 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002665 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002666 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002667 // C++ [temp.arg.nontype]p1:
2668 // A template-argument for a non-type, non-template
2669 // template-parameter shall be one of:
2670 //
2671 // -- an integral constant-expression of integral or enumeration
2672 // type; or
2673 // -- the name of a non-type template-parameter; or
2674 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002675 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002676 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002677 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002678 diag::err_template_arg_not_integral_or_enumeral)
2679 << ArgType << Arg->getSourceRange();
2680 Diag(Param->getLocation(), diag::note_template_param_here);
2681 return true;
2682 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002683 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002684 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2685 << ArgType << Arg->getSourceRange();
2686 return true;
2687 }
2688
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002689 // From here on out, all we care about are the unqualified forms
2690 // of the parameter and argument types.
2691 ParamType = ParamType.getUnqualifiedType();
2692 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002693
2694 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002695 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002696 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002697 } else if (CTAK == CTAK_Deduced) {
2698 // C++ [temp.deduct.type]p17:
2699 // If, in the declaration of a function template with a non-type
2700 // template-parameter, the non-type template- parameter is used
2701 // in an expression in the function parameter-list and, if the
2702 // corresponding template-argument is deduced, the
2703 // template-argument type shall match the type of the
2704 // template-parameter exactly, except that a template-argument
2705 // deduced from an array bound may be of any integral type.
2706 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2707 << ArgType << ParamType;
2708 Diag(Param->getLocation(), diag::note_template_param_here);
2709 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002710 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2711 !ParamType->isEnumeralType()) {
2712 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002713 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002714 } else {
2715 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002716 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002717 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002718 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002719 Diag(Param->getLocation(), diag::note_template_param_here);
2720 return true;
2721 }
2722
Douglas Gregor52aba872009-03-14 00:20:21 +00002723 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002724 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002725 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002726
2727 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002728 llvm::APSInt OldValue = Value;
2729
2730 // Coerce the template argument's value to the value it will have
2731 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002732 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002733 if (Value.getBitWidth() != AllowedBits)
2734 Value.extOrTrunc(AllowedBits);
2735 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002736
2737 // Complain if an unsigned parameter received a negative value.
2738 if (IntegerType->isUnsignedIntegerType()
2739 && (OldValue.isSigned() && OldValue.isNegative())) {
2740 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2741 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2742 << Arg->getSourceRange();
2743 Diag(Param->getLocation(), diag::note_template_param_here);
2744 }
2745
2746 // Complain if we overflowed the template parameter's type.
2747 unsigned RequiredBits;
2748 if (IntegerType->isUnsignedIntegerType())
2749 RequiredBits = OldValue.getActiveBits();
2750 else if (OldValue.isUnsigned())
2751 RequiredBits = OldValue.getActiveBits() + 1;
2752 else
2753 RequiredBits = OldValue.getMinSignedBits();
2754 if (RequiredBits > AllowedBits) {
2755 Diag(Arg->getSourceRange().getBegin(),
2756 diag::warn_template_arg_too_large)
2757 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2758 << Arg->getSourceRange();
2759 Diag(Param->getLocation(), diag::note_template_param_here);
2760 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002761 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002762
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002763 // Add the value of this argument to the list of converted
2764 // arguments. We use the bitwidth and signedness of the template
2765 // parameter.
2766 if (Arg->isValueDependent()) {
2767 // The argument is value-dependent. Create a new
2768 // TemplateArgument with the converted expression.
2769 Converted = TemplateArgument(Arg);
2770 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002771 }
2772
John McCall0ad16662009-10-29 08:12:44 +00002773 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002774 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002775 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002776 return false;
2777 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002778
John McCall16df1e52010-03-30 21:47:33 +00002779 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2780
Douglas Gregorb242683d2010-04-01 18:32:35 +00002781 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2782 // from a template argument of type std::nullptr_t to a non-type
2783 // template parameter of type pointer to object, pointer to
2784 // function, or pointer-to-member, respectively.
2785 if (ArgType->isNullPtrType() &&
2786 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2787 Converted = TemplateArgument((NamedDecl *)0);
2788 return false;
2789 }
2790
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002791 // Handle pointer-to-function, reference-to-function, and
2792 // pointer-to-member-function all in (roughly) the same way.
2793 if (// -- For a non-type template-parameter of type pointer to
2794 // function, only the function-to-pointer conversion (4.3) is
2795 // applied. If the template-argument represents a set of
2796 // overloaded functions (or a pointer to such), the matching
2797 // function is selected from the set (13.4).
2798 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002799 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002800 // -- For a non-type template-parameter of type reference to
2801 // function, no conversions apply. If the template-argument
2802 // represents a set of overloaded functions, the matching
2803 // function is selected from the set (13.4).
2804 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002805 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002806 // -- For a non-type template-parameter of type pointer to
2807 // member function, no conversions apply. If the
2808 // template-argument represents a set of overloaded member
2809 // functions, the matching member function is selected from
2810 // the set (13.4).
2811 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002812 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002813 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002814
2815 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2816 true,
2817 FoundResult)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002818 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2819 return true;
2820
John McCall16df1e52010-03-30 21:47:33 +00002821 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002822 ArgType = Arg->getType();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002823 }
2824
Douglas Gregorb242683d2010-04-01 18:32:35 +00002825 if (!ParamType->isMemberPointerType())
2826 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2827 ParamType,
2828 Arg, Converted);
2829
2830 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2831 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2832 Arg->isLvalue(Context) == Expr::LV_Valid);
2833 } else if (!Context.hasSameUnqualifiedType(ArgType,
2834 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002835 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002836 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002837 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002838 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002839 Diag(Param->getLocation(), diag::note_template_param_here);
2840 return true;
2841 }
Mike Stump11289f42009-09-09 15:08:12 +00002842
Douglas Gregorb242683d2010-04-01 18:32:35 +00002843 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002844 }
2845
Chris Lattner696197c2009-02-20 21:37:53 +00002846 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002847 // -- for a non-type template-parameter of type pointer to
2848 // object, qualification conversions (4.4) and the
2849 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002850 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002851 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002852 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002853
Douglas Gregorb242683d2010-04-01 18:32:35 +00002854 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2855 ParamType,
2856 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002857 }
Mike Stump11289f42009-09-09 15:08:12 +00002858
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002859 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002860 // -- For a non-type template-parameter of type reference to
2861 // object, no conversions apply. The type referred to by the
2862 // reference may be more cv-qualified than the (otherwise
2863 // identical) type of the template-argument. The
2864 // template-parameter is bound directly to the
2865 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002866 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002867 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002868
Douglas Gregorb242683d2010-04-01 18:32:35 +00002869 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2870 ParamRefType->getPointeeType(),
2871 true,
2872 FoundResult)) {
2873 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2874 return true;
2875
2876 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2877 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002878 }
2879
Douglas Gregorb242683d2010-04-01 18:32:35 +00002880 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2881 ParamType,
2882 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002883 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002884
2885 // -- For a non-type template-parameter of type pointer to data
2886 // member, qualification conversions (4.4) are applied.
2887 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2888
Douglas Gregor1515f762009-02-11 18:22:40 +00002889 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002890 // Types match exactly: nothing more to do here.
2891 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002892 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2893 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor0e558532009-02-11 16:16:59 +00002894 } else {
2895 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002896 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002897 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002898 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002899 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002900 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002901 }
2902
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002903 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002904}
2905
2906/// \brief Check a template argument against its corresponding
2907/// template template parameter.
2908///
2909/// This routine implements the semantics of C++ [temp.arg.template].
2910/// It returns true if an error occurred, and false otherwise.
2911bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002912 const TemplateArgumentLoc &Arg) {
2913 TemplateName Name = Arg.getArgument().getAsTemplate();
2914 TemplateDecl *Template = Name.getAsTemplateDecl();
2915 if (!Template) {
2916 // Any dependent template name is fine.
2917 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2918 return false;
2919 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002920
2921 // C++ [temp.arg.template]p1:
2922 // A template-argument for a template template-parameter shall be
2923 // the name of a class template, expressed as id-expression. Only
2924 // primary class templates are considered when matching the
2925 // template template argument with the corresponding parameter;
2926 // partial specializations are not considered even if their
2927 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002928 //
2929 // Note that we also allow template template parameters here, which
2930 // will happen when we are dealing with, e.g., class template
2931 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002932 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002933 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002934 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002935 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002936 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002937 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002938 << Template;
2939 }
2940
2941 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2942 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002943 true,
2944 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002945 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002946}
2947
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002948/// \brief Given a non-type template argument that refers to a
2949/// declaration and the type of its corresponding non-type template
2950/// parameter, produce an expression that properly refers to that
2951/// declaration.
2952Sema::OwningExprResult
2953Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
2954 QualType ParamType,
2955 SourceLocation Loc) {
2956 assert(Arg.getKind() == TemplateArgument::Declaration &&
2957 "Only declaration template arguments permitted here");
2958 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
2959
2960 if (VD->getDeclContext()->isRecord() &&
2961 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
2962 // If the value is a class member, we might have a pointer-to-member.
2963 // Determine whether the non-type template template parameter is of
2964 // pointer-to-member type. If so, we need to build an appropriate
2965 // expression for a pointer-to-member, since a "normal" DeclRefExpr
2966 // would refer to the member itself.
2967 if (ParamType->isMemberPointerType()) {
2968 QualType ClassType
2969 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
2970 NestedNameSpecifier *Qualifier
2971 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
2972 CXXScopeSpec SS;
2973 SS.setScopeRep(Qualifier);
2974 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
2975 VD->getType().getNonReferenceType(),
2976 Loc,
2977 &SS);
2978 if (RefExpr.isInvalid())
2979 return ExprError();
2980
2981 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
2982 assert(!RefExpr.isInvalid() &&
2983 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
2984 ParamType));
2985 return move(RefExpr);
2986 }
2987 }
2988
2989 QualType T = VD->getType().getNonReferenceType();
2990 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002991 // When the non-type template parameter is a pointer, take the
2992 // address of the declaration.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002993 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
2994 if (RefExpr.isInvalid())
2995 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002996
2997 if (T->isFunctionType() || T->isArrayType()) {
2998 // Decay functions and arrays.
2999 Expr *RefE = (Expr *)RefExpr.get();
3000 DefaultFunctionArrayConversion(RefE);
3001 if (RefE != RefExpr.get()) {
3002 RefExpr.release();
3003 RefExpr = Owned(RefE);
3004 }
3005
3006 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003007 }
3008
Douglas Gregorb242683d2010-04-01 18:32:35 +00003009 // Take the address of everything else
3010 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003011 }
3012
3013 // If the non-type template parameter has reference type, qualify the
3014 // resulting declaration reference with the extra qualifiers on the
3015 // type that the reference refers to.
3016 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3017 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3018
3019 return BuildDeclRefExpr(VD, T, Loc);
3020}
3021
3022/// \brief Construct a new expression that refers to the given
3023/// integral template argument with the given source-location
3024/// information.
3025///
3026/// This routine takes care of the mapping from an integral template
3027/// argument (which may have any integral type) to the appropriate
3028/// literal value.
3029Sema::OwningExprResult
3030Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3031 SourceLocation Loc) {
3032 assert(Arg.getKind() == TemplateArgument::Integral &&
3033 "Operation is only value for integral template arguments");
3034 QualType T = Arg.getIntegralType();
3035 if (T->isCharType() || T->isWideCharType())
3036 return Owned(new (Context) CharacterLiteral(
3037 Arg.getAsIntegral()->getZExtValue(),
3038 T->isWideCharType(),
3039 T,
3040 Loc));
3041 if (T->isBooleanType())
3042 return Owned(new (Context) CXXBoolLiteralExpr(
3043 Arg.getAsIntegral()->getBoolValue(),
3044 T,
3045 Loc));
3046
3047 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3048}
3049
3050
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003051/// \brief Determine whether the given template parameter lists are
3052/// equivalent.
3053///
Mike Stump11289f42009-09-09 15:08:12 +00003054/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003055/// source code as part of a new template declaration.
3056///
3057/// \param Old The old template parameter list, typically found via
3058/// name lookup of the template declared with this template parameter
3059/// list.
3060///
3061/// \param Complain If true, this routine will produce a diagnostic if
3062/// the template parameter lists are not equivalent.
3063///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003064/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003065///
3066/// \param TemplateArgLoc If this source location is valid, then we
3067/// are actually checking the template parameter list of a template
3068/// argument (New) against the template parameter list of its
3069/// corresponding template template parameter (Old). We produce
3070/// slightly different diagnostics in this scenario.
3071///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003072/// \returns True if the template parameter lists are equal, false
3073/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003074bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003075Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3076 TemplateParameterList *Old,
3077 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003078 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003079 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003080 if (Old->size() != New->size()) {
3081 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003082 unsigned NextDiag = diag::err_template_param_list_different_arity;
3083 if (TemplateArgLoc.isValid()) {
3084 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3085 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003086 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003087 Diag(New->getTemplateLoc(), NextDiag)
3088 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003089 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003090 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003091 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003092 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003093 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3094 }
3095
3096 return false;
3097 }
3098
3099 for (TemplateParameterList::iterator OldParm = Old->begin(),
3100 OldParmEnd = Old->end(), NewParm = New->begin();
3101 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3102 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003103 if (Complain) {
3104 unsigned NextDiag = diag::err_template_param_different_kind;
3105 if (TemplateArgLoc.isValid()) {
3106 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3107 NextDiag = diag::note_template_param_different_kind;
3108 }
3109 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003110 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003111 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003112 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003113 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003114 return false;
3115 }
3116
3117 if (isa<TemplateTypeParmDecl>(*OldParm)) {
3118 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00003119 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00003120 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003121 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3122 // The types of non-type template parameters must agree.
3123 NonTypeTemplateParmDecl *NewNTTP
3124 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003125
3126 // If we are matching a template template argument to a template
3127 // template parameter and one of the non-type template parameter types
3128 // is dependent, then we must wait until template instantiation time
3129 // to actually compare the arguments.
3130 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3131 (OldNTTP->getType()->isDependentType() ||
3132 NewNTTP->getType()->isDependentType()))
3133 continue;
3134
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003135 if (Context.getCanonicalType(OldNTTP->getType()) !=
3136 Context.getCanonicalType(NewNTTP->getType())) {
3137 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003138 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3139 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003140 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003141 diag::err_template_arg_template_params_mismatch);
3142 NextDiag = diag::note_template_nontype_parm_different_type;
3143 }
3144 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003145 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003146 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003147 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003148 diag::note_template_nontype_parm_prev_declaration)
3149 << OldNTTP->getType();
3150 }
3151 return false;
3152 }
3153 } else {
3154 // The template parameter lists of template template
3155 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003156 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003157 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003158 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003159 = cast<TemplateTemplateParmDecl>(*OldParm);
3160 TemplateTemplateParmDecl *NewTTP
3161 = cast<TemplateTemplateParmDecl>(*NewParm);
3162 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3163 OldTTP->getTemplateParameters(),
3164 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003165 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003166 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003167 return false;
3168 }
3169 }
3170
3171 return true;
3172}
3173
3174/// \brief Check whether a template can be declared within this scope.
3175///
3176/// If the template declaration is valid in this scope, returns
3177/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003178bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003179Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003180 // Find the nearest enclosing declaration scope.
3181 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3182 (S->getFlags() & Scope::TemplateParamScope) != 0)
3183 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003184
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003185 // C++ [temp]p2:
3186 // A template-declaration can appear only as a namespace scope or
3187 // class scope declaration.
3188 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003189 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3190 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003191 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003192 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003193
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003194 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003195 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003196
3197 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3198 return false;
3199
Mike Stump11289f42009-09-09 15:08:12 +00003200 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003201 diag::err_template_outside_namespace_or_class_scope)
3202 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003203}
Douglas Gregor67a65642009-02-17 23:15:12 +00003204
Douglas Gregor54888652009-10-07 00:13:32 +00003205/// \brief Determine what kind of template specialization the given declaration
3206/// is.
3207static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3208 if (!D)
3209 return TSK_Undeclared;
3210
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003211 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3212 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003213 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3214 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003215 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3216 return Var->getTemplateSpecializationKind();
3217
Douglas Gregor54888652009-10-07 00:13:32 +00003218 return TSK_Undeclared;
3219}
3220
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003221/// \brief Check whether a specialization is well-formed in the current
3222/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003223///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003224/// This routine determines whether a template specialization can be declared
3225/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003226///
3227/// \param S the semantic analysis object for which this check is being
3228/// performed.
3229///
3230/// \param Specialized the entity being specialized or instantiated, which
3231/// may be a kind of template (class template, function template, etc.) or
3232/// a member of a class template (member function, static data member,
3233/// member class).
3234///
3235/// \param PrevDecl the previous declaration of this entity, if any.
3236///
3237/// \param Loc the location of the explicit specialization or instantiation of
3238/// this entity.
3239///
3240/// \param IsPartialSpecialization whether this is a partial specialization of
3241/// a class template.
3242///
Douglas Gregor54888652009-10-07 00:13:32 +00003243/// \returns true if there was an error that we cannot recover from, false
3244/// otherwise.
3245static bool CheckTemplateSpecializationScope(Sema &S,
3246 NamedDecl *Specialized,
3247 NamedDecl *PrevDecl,
3248 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003249 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003250 // Keep these "kind" numbers in sync with the %select statements in the
3251 // various diagnostics emitted by this routine.
3252 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003253 bool isTemplateSpecialization = false;
3254 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003255 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003256 isTemplateSpecialization = true;
3257 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003258 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003259 isTemplateSpecialization = true;
3260 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003261 EntityKind = 3;
3262 else if (isa<VarDecl>(Specialized))
3263 EntityKind = 4;
3264 else if (isa<RecordDecl>(Specialized))
3265 EntityKind = 5;
3266 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003267 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3268 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003269 return true;
3270 }
3271
Douglas Gregorf47b9112009-02-25 22:02:03 +00003272 // C++ [temp.expl.spec]p2:
3273 // An explicit specialization shall be declared in the namespace
3274 // of which the template is a member, or, for member templates, in
3275 // the namespace of which the enclosing class or enclosing class
3276 // template is a member. An explicit specialization of a member
3277 // function, member class or static data member of a class
3278 // template shall be declared in the namespace of which the class
3279 // template is a member. Such a declaration may also be a
3280 // definition. If the declaration is not a definition, the
3281 // specialization may be defined later in the name- space in which
3282 // the explicit specialization was declared, or in a namespace
3283 // that encloses the one in which the explicit specialization was
3284 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003285 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3286 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003287 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003288 return true;
3289 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003290
Douglas Gregor40fb7442009-10-07 17:30:37 +00003291 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3292 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003293 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003294 return true;
3295 }
3296
Douglas Gregore4b05162009-10-07 17:21:34 +00003297 // C++ [temp.class.spec]p6:
3298 // A class template partial specialization may be declared or redeclared
3299 // in any namespace scope in which its definition may be defined (14.5.1
3300 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003301 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003302 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003303 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003304 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003305 if ((!PrevDecl ||
3306 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3307 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3308 // There is no prior declaration of this entity, so this
3309 // specialization must be in the same context as the template
3310 // itself.
3311 if (!DC->Equals(SpecializedContext)) {
3312 if (isa<TranslationUnitDecl>(SpecializedContext))
3313 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3314 << EntityKind << Specialized;
3315 else if (isa<NamespaceDecl>(SpecializedContext))
3316 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3317 << EntityKind << Specialized
3318 << cast<NamedDecl>(SpecializedContext);
3319
3320 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3321 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003322 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003323 }
Douglas Gregor54888652009-10-07 00:13:32 +00003324
3325 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003326 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003327 // Note that HandleDeclarator() performs this check for explicit
3328 // specializations of function templates, static data members, and member
3329 // functions, so we skip the check here for those kinds of entities.
3330 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003331 // Should we refactor that check, so that it occurs later?
3332 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003333 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3334 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003335 if (isa<TranslationUnitDecl>(SpecializedContext))
3336 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3337 << EntityKind << Specialized;
3338 else if (isa<NamespaceDecl>(SpecializedContext))
3339 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3340 << EntityKind << Specialized
3341 << cast<NamedDecl>(SpecializedContext);
3342
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003343 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003344 }
Douglas Gregor54888652009-10-07 00:13:32 +00003345
3346 // FIXME: check for specialization-after-instantiation errors and such.
3347
Douglas Gregorf47b9112009-02-25 22:02:03 +00003348 return false;
3349}
Douglas Gregor54888652009-10-07 00:13:32 +00003350
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003351/// \brief Check the non-type template arguments of a class template
3352/// partial specialization according to C++ [temp.class.spec]p9.
3353///
Douglas Gregor09a30232009-06-12 22:08:06 +00003354/// \param TemplateParams the template parameters of the primary class
3355/// template.
3356///
3357/// \param TemplateArg the template arguments of the class template
3358/// partial specialization.
3359///
3360/// \param MirrorsPrimaryTemplate will be set true if the class
3361/// template partial specialization arguments are identical to the
3362/// implicit template arguments of the primary template. This is not
3363/// necessarily an error (C++0x), and it is left to the caller to diagnose
3364/// this condition when it is an error.
3365///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003366/// \returns true if there was an error, false otherwise.
3367bool Sema::CheckClassTemplatePartialSpecializationArgs(
3368 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003369 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003370 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003371 // FIXME: the interface to this function will have to change to
3372 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003373 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003374
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003375 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003376
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003377 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003378 // Determine whether the template argument list of the partial
3379 // specialization is identical to the implicit argument list of
3380 // the primary template. The caller may need to diagnostic this as
3381 // an error per C++ [temp.class.spec]p9b3.
3382 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003383 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003384 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3385 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003386 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003387 MirrorsPrimaryTemplate = false;
3388 } else if (TemplateTemplateParmDecl *TTP
3389 = dyn_cast<TemplateTemplateParmDecl>(
3390 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003391 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003392 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003393 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003394 if (!ArgDecl ||
3395 ArgDecl->getIndex() != TTP->getIndex() ||
3396 ArgDecl->getDepth() != TTP->getDepth())
3397 MirrorsPrimaryTemplate = false;
3398 }
3399 }
3400
Mike Stump11289f42009-09-09 15:08:12 +00003401 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003402 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003403 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003404 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003405 }
3406
Anders Carlsson40c1d492009-06-13 18:20:51 +00003407 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003408 if (!ArgExpr) {
3409 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003410 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003411 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003412
3413 // C++ [temp.class.spec]p8:
3414 // A non-type argument is non-specialized if it is the name of a
3415 // non-type parameter. All other non-type arguments are
3416 // specialized.
3417 //
3418 // Below, we check the two conditions that only apply to
3419 // specialized non-type arguments, so skip any non-specialized
3420 // arguments.
3421 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003422 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003423 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003424 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003425 (Param->getIndex() != NTTP->getIndex() ||
3426 Param->getDepth() != NTTP->getDepth()))
3427 MirrorsPrimaryTemplate = false;
3428
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003429 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003430 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003431
3432 // C++ [temp.class.spec]p9:
3433 // Within the argument list of a class template partial
3434 // specialization, the following restrictions apply:
3435 // -- A partially specialized non-type argument expression
3436 // shall not involve a template parameter of the partial
3437 // specialization except when the argument expression is a
3438 // simple identifier.
3439 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003440 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003441 diag::err_dependent_non_type_arg_in_partial_spec)
3442 << ArgExpr->getSourceRange();
3443 return true;
3444 }
3445
3446 // -- The type of a template parameter corresponding to a
3447 // specialized non-type argument shall not be dependent on a
3448 // parameter of the specialization.
3449 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003450 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003451 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3452 << Param->getType()
3453 << ArgExpr->getSourceRange();
3454 Diag(Param->getLocation(), diag::note_template_param_here);
3455 return true;
3456 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003457
3458 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003459 }
3460
3461 return false;
3462}
3463
Douglas Gregorc854c662010-02-26 06:03:23 +00003464/// \brief Retrieve the previous declaration of the given declaration.
3465static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3466 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3467 return VD->getPreviousDeclaration();
3468 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3469 return FD->getPreviousDeclaration();
3470 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3471 return TD->getPreviousDeclaration();
3472 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3473 return TD->getPreviousDeclaration();
3474 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3475 return FTD->getPreviousDeclaration();
3476 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3477 return CTD->getPreviousDeclaration();
3478 return 0;
3479}
3480
Douglas Gregorc08f4892009-03-25 00:13:59 +00003481Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003482Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3483 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003484 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003485 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003486 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003487 SourceLocation TemplateNameLoc,
3488 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003489 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003490 SourceLocation RAngleLoc,
3491 AttributeList *Attr,
3492 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003493 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003494
Douglas Gregor67a65642009-02-17 23:15:12 +00003495 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003496 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003497 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003498 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3499
3500 if (!ClassTemplate) {
3501 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3502 << (Name.getAsTemplateDecl() &&
3503 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3504 return true;
3505 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003506
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003507 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003508 bool isPartialSpecialization = false;
3509
Douglas Gregorf47b9112009-02-25 22:02:03 +00003510 // Check the validity of the template headers that introduce this
3511 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003512 // FIXME: We probably shouldn't complain about these headers for
3513 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003514 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003515 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3516 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003517 TemplateParameterLists.size(),
3518 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003519 if (TemplateParams && TemplateParams->size() > 0) {
3520 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003521
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003522 // C++ [temp.class.spec]p10:
3523 // The template parameter list of a specialization shall not
3524 // contain default template argument values.
3525 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3526 Decl *Param = TemplateParams->getParam(I);
3527 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3528 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003529 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003530 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003531 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003532 }
3533 } else if (NonTypeTemplateParmDecl *NTTP
3534 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3535 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003536 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003537 diag::err_default_arg_in_partial_spec)
3538 << DefArg->getSourceRange();
3539 NTTP->setDefaultArgument(0);
3540 DefArg->Destroy(Context);
3541 }
3542 } else {
3543 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003544 if (TTP->hasDefaultArgument()) {
3545 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003546 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003547 << TTP->getDefaultArgument().getSourceRange();
3548 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003549 }
3550 }
3551 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003552 } else if (TemplateParams) {
3553 if (TUK == TUK_Friend)
3554 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003555 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003556 SourceRange(TemplateParams->getTemplateLoc(),
3557 TemplateParams->getRAngleLoc()))
3558 << SourceRange(LAngleLoc, RAngleLoc);
3559 else
3560 isExplicitSpecialization = true;
3561 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003562 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003563 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003564 isExplicitSpecialization = true;
3565 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003566
Douglas Gregor67a65642009-02-17 23:15:12 +00003567 // Check that the specialization uses the same tag kind as the
3568 // original template.
3569 TagDecl::TagKind Kind;
3570 switch (TagSpec) {
3571 default: assert(0 && "Unknown tag type!");
3572 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3573 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3574 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3575 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003576 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003577 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003578 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003579 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003580 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003581 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003582 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003583 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003584 diag::note_previous_use);
3585 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3586 }
3587
Douglas Gregorc40290e2009-03-09 23:48:35 +00003588 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003589 TemplateArgumentListInfo TemplateArgs;
3590 TemplateArgs.setLAngleLoc(LAngleLoc);
3591 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003592 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003593
Douglas Gregor67a65642009-02-17 23:15:12 +00003594 // Check that the template argument list is well-formed for this
3595 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003596 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3597 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003598 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3599 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003600 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003601
Mike Stump11289f42009-09-09 15:08:12 +00003602 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003603 ClassTemplate->getTemplateParameters()->size()) &&
3604 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003605
Douglas Gregor2373c592009-05-31 09:31:02 +00003606 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003607 // corresponds to these arguments.
3608 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003609 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003610 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003611 if (CheckClassTemplatePartialSpecializationArgs(
3612 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003613 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003614 return true;
3615
Douglas Gregor09a30232009-06-12 22:08:06 +00003616 if (MirrorsPrimaryTemplate) {
3617 // C++ [temp.class.spec]p9b3:
3618 //
Mike Stump11289f42009-09-09 15:08:12 +00003619 // -- The argument list of the specialization shall not be identical
3620 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003621 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003622 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003623 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003624 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003625 ClassTemplate->getIdentifier(),
3626 TemplateNameLoc,
3627 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003628 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003629 AS_none);
3630 }
3631
Douglas Gregor2208a292009-09-26 20:57:03 +00003632 // FIXME: Diagnose friend partial specializations
3633
Douglas Gregor92354b62010-02-09 00:37:32 +00003634 if (!Name.isDependent() &&
3635 !TemplateSpecializationType::anyDependentTemplateArguments(
3636 TemplateArgs.getArgumentArray(),
3637 TemplateArgs.size())) {
3638 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3639 << ClassTemplate->getDeclName();
3640 isPartialSpecialization = false;
3641 } else {
3642 // FIXME: Template parameter list matters, too
3643 ClassTemplatePartialSpecializationDecl::Profile(ID,
3644 Converted.getFlatArguments(),
3645 Converted.flatSize(),
3646 Context);
3647 }
3648 }
3649
3650 if (!isPartialSpecialization)
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003651 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003652 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003653 Converted.flatSize(),
3654 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003655 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003656 ClassTemplateSpecializationDecl *PrevDecl = 0;
3657
3658 if (isPartialSpecialization)
3659 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003660 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003661 InsertPos);
3662 else
3663 PrevDecl
3664 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003665
3666 ClassTemplateSpecializationDecl *Specialization = 0;
3667
Douglas Gregorf47b9112009-02-25 22:02:03 +00003668 // Check whether we can declare a class template specialization in
3669 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003670 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003671 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003672 TemplateNameLoc,
3673 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003674 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003675
Douglas Gregor15301382009-07-30 17:40:51 +00003676 // The canonical type
3677 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003678 if (PrevDecl &&
3679 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003680 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003681 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003682 // arguments was referenced but not declared, or we're only
3683 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003684 // declaration node as our own, updating its source location to
3685 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003686 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003687 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003688 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003689 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003690 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003691 // Build the canonical type that describes the converted template
3692 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003693 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3694 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003695 Converted.getFlatArguments(),
3696 Converted.flatSize());
3697
Douglas Gregor2373c592009-05-31 09:31:02 +00003698 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003699 ClassTemplatePartialSpecializationDecl *PrevPartial
3700 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003701 ClassTemplatePartialSpecializationDecl *Partial
3702 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003703 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003704 TemplateNameLoc,
3705 TemplateParams,
3706 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003707 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003708 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003709 CanonType,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003710 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00003711 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor2373c592009-05-31 09:31:02 +00003712
3713 if (PrevPartial) {
3714 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3715 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3716 } else {
3717 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3718 }
3719 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003720
Douglas Gregor21610382009-10-29 00:04:11 +00003721 // If we are providing an explicit specialization of a member class
3722 // template specialization, make a note of that.
3723 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3724 PrevPartial->setMemberSpecialization();
3725
Douglas Gregor91772d12009-06-13 00:26:55 +00003726 // Check that all of the template parameters of the class template
3727 // partial specialization are deducible from the template
3728 // arguments. If not, this class template partial specialization
3729 // will never be used.
3730 llvm::SmallVector<bool, 8> DeducibleParams;
3731 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003732 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003733 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003734 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003735 unsigned NumNonDeducible = 0;
3736 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3737 if (!DeducibleParams[I])
3738 ++NumNonDeducible;
3739
3740 if (NumNonDeducible) {
3741 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3742 << (NumNonDeducible > 1)
3743 << SourceRange(TemplateNameLoc, RAngleLoc);
3744 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3745 if (!DeducibleParams[I]) {
3746 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3747 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003748 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003749 diag::note_partial_spec_unused_parameter)
3750 << Param->getDeclName();
3751 else
Mike Stump11289f42009-09-09 15:08:12 +00003752 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003753 diag::note_partial_spec_unused_parameter)
3754 << std::string("<anonymous>");
3755 }
3756 }
3757 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003758 } else {
3759 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003760 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003761 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003762 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003763 ClassTemplate->getDeclContext(),
3764 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003765 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003766 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003767 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003768 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor67a65642009-02-17 23:15:12 +00003769
3770 if (PrevDecl) {
3771 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3772 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3773 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003774 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003775 InsertPos);
3776 }
Douglas Gregor15301382009-07-30 17:40:51 +00003777
3778 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003779 }
3780
Douglas Gregor06db9f52009-10-12 20:18:28 +00003781 // C++ [temp.expl.spec]p6:
3782 // If a template, a member template or the member of a class template is
3783 // explicitly specialized then that specialization shall be declared
3784 // before the first use of that specialization that would cause an implicit
3785 // instantiation to take place, in every translation unit in which such a
3786 // use occurs; no diagnostic is required.
3787 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003788 bool Okay = false;
3789 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3790 // Is there any previous explicit specialization declaration?
3791 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3792 Okay = true;
3793 break;
3794 }
3795 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003796
Douglas Gregorc854c662010-02-26 06:03:23 +00003797 if (!Okay) {
3798 SourceRange Range(TemplateNameLoc, RAngleLoc);
3799 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3800 << Context.getTypeDeclType(Specialization) << Range;
3801
3802 Diag(PrevDecl->getPointOfInstantiation(),
3803 diag::note_instantiation_required_here)
3804 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003805 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003806 return true;
3807 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003808 }
3809
Douglas Gregor2208a292009-09-26 20:57:03 +00003810 // If this is not a friend, note that this is an explicit specialization.
3811 if (TUK != TUK_Friend)
3812 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003813
3814 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003815 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003816 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003817 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003818 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003819 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003820 Diag(Def->getLocation(), diag::note_previous_definition);
3821 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003822 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003823 }
3824 }
3825
Douglas Gregord56a91e2009-02-26 22:19:44 +00003826 // Build the fully-sugared type for this class template
3827 // specialization as the user wrote in the specialization
3828 // itself. This means that we'll pretty-print the type retrieved
3829 // from the specialization's declaration the way that the user
3830 // actually wrote the specialization, rather than formatting the
3831 // name based on the "canonical" representation used to store the
3832 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003833 TypeSourceInfo *WrittenTy
3834 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3835 TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003836 if (TUK != TUK_Friend)
3837 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003838 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003839
Douglas Gregor1e249f82009-02-25 22:18:32 +00003840 // C++ [temp.expl.spec]p9:
3841 // A template explicit specialization is in the scope of the
3842 // namespace in which the template was defined.
3843 //
3844 // We actually implement this paragraph where we set the semantic
3845 // context (in the creation of the ClassTemplateSpecializationDecl),
3846 // but we also maintain the lexical context where the actual
3847 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003848 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003849
Douglas Gregor67a65642009-02-17 23:15:12 +00003850 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003851 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003852 Specialization->startDefinition();
3853
Douglas Gregor2208a292009-09-26 20:57:03 +00003854 if (TUK == TUK_Friend) {
3855 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3856 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00003857 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00003858 /*FIXME:*/KWLoc);
3859 Friend->setAccess(AS_public);
3860 CurContext->addDecl(Friend);
3861 } else {
3862 // Add the specialization into its lexical context, so that it can
3863 // be seen when iterating through the list of declarations in that
3864 // context. However, specializations are not found by name lookup.
3865 CurContext->addDecl(Specialization);
3866 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003867 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003868}
Douglas Gregor333489b2009-03-27 23:10:48 +00003869
Mike Stump11289f42009-09-09 15:08:12 +00003870Sema::DeclPtrTy
3871Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003872 MultiTemplateParamsArg TemplateParameterLists,
3873 Declarator &D) {
3874 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3875}
3876
Mike Stump11289f42009-09-09 15:08:12 +00003877Sema::DeclPtrTy
3878Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003879 MultiTemplateParamsArg TemplateParameterLists,
3880 Declarator &D) {
3881 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3882 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3883 "Not a function declarator!");
3884 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003885
Douglas Gregor17a7c122009-06-24 00:54:41 +00003886 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003887 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003888 }
Mike Stump11289f42009-09-09 15:08:12 +00003889
Douglas Gregor17a7c122009-06-24 00:54:41 +00003890 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003891
3892 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003893 move(TemplateParameterLists),
3894 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003895 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003896 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003897 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003898 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003899 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3900 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003901 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003902}
3903
John McCall4f7ced62010-02-11 01:33:53 +00003904/// \brief Strips various properties off an implicit instantiation
3905/// that has just been explicitly specialized.
3906static void StripImplicitInstantiation(NamedDecl *D) {
3907 D->invalidateAttrs();
3908
3909 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3910 FD->setInlineSpecified(false);
3911 }
3912}
3913
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003914/// \brief Diagnose cases where we have an explicit template specialization
3915/// before/after an explicit template instantiation, producing diagnostics
3916/// for those cases where they are required and determining whether the
3917/// new specialization/instantiation will have any effect.
3918///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003919/// \param NewLoc the location of the new explicit specialization or
3920/// instantiation.
3921///
3922/// \param NewTSK the kind of the new explicit specialization or instantiation.
3923///
3924/// \param PrevDecl the previous declaration of the entity.
3925///
3926/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3927///
3928/// \param PrevPointOfInstantiation if valid, indicates where the previus
3929/// declaration was instantiated (either implicitly or explicitly).
3930///
3931/// \param SuppressNew will be set to true to indicate that the new
3932/// specialization or instantiation has no effect and should be ignored.
3933///
3934/// \returns true if there was an error that should prevent the introduction of
3935/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003936bool
3937Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3938 TemplateSpecializationKind NewTSK,
3939 NamedDecl *PrevDecl,
3940 TemplateSpecializationKind PrevTSK,
3941 SourceLocation PrevPointOfInstantiation,
3942 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003943 SuppressNew = false;
3944
3945 switch (NewTSK) {
3946 case TSK_Undeclared:
3947 case TSK_ImplicitInstantiation:
3948 assert(false && "Don't check implicit instantiations here");
3949 return false;
3950
3951 case TSK_ExplicitSpecialization:
3952 switch (PrevTSK) {
3953 case TSK_Undeclared:
3954 case TSK_ExplicitSpecialization:
3955 // Okay, we're just specializing something that is either already
3956 // explicitly specialized or has merely been mentioned without any
3957 // instantiation.
3958 return false;
3959
3960 case TSK_ImplicitInstantiation:
3961 if (PrevPointOfInstantiation.isInvalid()) {
3962 // The declaration itself has not actually been instantiated, so it is
3963 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00003964 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003965 return false;
3966 }
3967 // Fall through
3968
3969 case TSK_ExplicitInstantiationDeclaration:
3970 case TSK_ExplicitInstantiationDefinition:
3971 assert((PrevTSK == TSK_ImplicitInstantiation ||
3972 PrevPointOfInstantiation.isValid()) &&
3973 "Explicit instantiation without point of instantiation?");
3974
3975 // C++ [temp.expl.spec]p6:
3976 // If a template, a member template or the member of a class template
3977 // is explicitly specialized then that specialization shall be declared
3978 // before the first use of that specialization that would cause an
3979 // implicit instantiation to take place, in every translation unit in
3980 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00003981 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3982 // Is there any previous explicit specialization declaration?
3983 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
3984 return false;
3985 }
3986
Douglas Gregor1d957a32009-10-27 18:42:08 +00003987 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003988 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003989 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003990 << (PrevTSK != TSK_ImplicitInstantiation);
3991
3992 return true;
3993 }
3994 break;
3995
3996 case TSK_ExplicitInstantiationDeclaration:
3997 switch (PrevTSK) {
3998 case TSK_ExplicitInstantiationDeclaration:
3999 // This explicit instantiation declaration is redundant (that's okay).
4000 SuppressNew = true;
4001 return false;
4002
4003 case TSK_Undeclared:
4004 case TSK_ImplicitInstantiation:
4005 // We're explicitly instantiating something that may have already been
4006 // implicitly instantiated; that's fine.
4007 return false;
4008
4009 case TSK_ExplicitSpecialization:
4010 // C++0x [temp.explicit]p4:
4011 // For a given set of template parameters, if an explicit instantiation
4012 // of a template appears after a declaration of an explicit
4013 // specialization for that template, the explicit instantiation has no
4014 // effect.
John McCall6b21eb52010-03-02 23:09:38 +00004015 SuppressNew = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004016 return false;
4017
4018 case TSK_ExplicitInstantiationDefinition:
4019 // C++0x [temp.explicit]p10:
4020 // If an entity is the subject of both an explicit instantiation
4021 // declaration and an explicit instantiation definition in the same
4022 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004023 Diag(NewLoc,
4024 diag::err_explicit_instantiation_declaration_after_definition);
4025 Diag(PrevPointOfInstantiation,
4026 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004027 assert(PrevPointOfInstantiation.isValid() &&
4028 "Explicit instantiation without point of instantiation?");
4029 SuppressNew = true;
4030 return false;
4031 }
4032 break;
4033
4034 case TSK_ExplicitInstantiationDefinition:
4035 switch (PrevTSK) {
4036 case TSK_Undeclared:
4037 case TSK_ImplicitInstantiation:
4038 // We're explicitly instantiating something that may have already been
4039 // implicitly instantiated; that's fine.
4040 return false;
4041
4042 case TSK_ExplicitSpecialization:
4043 // C++ DR 259, C++0x [temp.explicit]p4:
4044 // For a given set of template parameters, if an explicit
4045 // instantiation of a template appears after a declaration of
4046 // an explicit specialization for that template, the explicit
4047 // instantiation has no effect.
4048 //
4049 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004050 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004051 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004052 if (!getLangOptions().CPlusPlus0x) {
4053 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004054 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004055 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004056 diag::note_previous_template_specialization);
4057 }
4058 SuppressNew = true;
4059 return false;
4060
4061 case TSK_ExplicitInstantiationDeclaration:
4062 // We're explicity instantiating a definition for something for which we
4063 // were previously asked to suppress instantiations. That's fine.
4064 return false;
4065
4066 case TSK_ExplicitInstantiationDefinition:
4067 // C++0x [temp.spec]p5:
4068 // For a given template and a given set of template-arguments,
4069 // - an explicit instantiation definition shall appear at most once
4070 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004071 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004072 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004073 Diag(PrevPointOfInstantiation,
4074 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004075 SuppressNew = true;
4076 return false;
4077 }
4078 break;
4079 }
4080
4081 assert(false && "Missing specialization/instantiation case?");
4082
4083 return false;
4084}
4085
John McCallb9c78482010-04-08 09:05:18 +00004086/// \brief Perform semantic analysis for the given dependent function
4087/// template specialization. The only possible way to get a dependent
4088/// function template specialization is with a friend declaration,
4089/// like so:
4090///
4091/// template <class T> void foo(T);
4092/// template <class T> class A {
4093/// friend void foo<>(T);
4094/// };
4095///
4096/// There really isn't any useful analysis we can do here, so we
4097/// just store the information.
4098bool
4099Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4100 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4101 LookupResult &Previous) {
4102 // Remove anything from Previous that isn't a function template in
4103 // the correct context.
4104 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4105 LookupResult::Filter F = Previous.makeFilter();
4106 while (F.hasNext()) {
4107 NamedDecl *D = F.next()->getUnderlyingDecl();
4108 if (!isa<FunctionTemplateDecl>(D) ||
4109 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4110 F.erase();
4111 }
4112 F.done();
4113
4114 // Should this be diagnosed here?
4115 if (Previous.empty()) return true;
4116
4117 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4118 ExplicitTemplateArgs);
4119 return false;
4120}
4121
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004122/// \brief Perform semantic analysis for the given function template
4123/// specialization.
4124///
4125/// This routine performs all of the semantic analysis required for an
4126/// explicit function template specialization. On successful completion,
4127/// the function declaration \p FD will become a function template
4128/// specialization.
4129///
4130/// \param FD the function declaration, which will be updated to become a
4131/// function template specialization.
4132///
4133/// \param HasExplicitTemplateArgs whether any template arguments were
4134/// explicitly provided.
4135///
4136/// \param LAngleLoc the location of the left angle bracket ('<'), if
4137/// template arguments were explicitly provided.
4138///
4139/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4140/// if any.
4141///
4142/// \param NumExplicitTemplateArgs the number of explicitly-provided template
4143/// arguments. This number may be zero even when HasExplicitTemplateArgs is
4144/// true as in, e.g., \c void sort<>(char*, char*);
4145///
4146/// \param RAngleLoc the location of the right angle bracket ('>'), if
4147/// template arguments were explicitly provided.
4148///
4149/// \param PrevDecl the set of declarations that
4150bool
4151Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004152 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004153 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004154 // The set of function template specializations that could match this
4155 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004156 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004157
4158 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004159 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4160 I != E; ++I) {
4161 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4162 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004163 // Only consider templates found within the same semantic lookup scope as
4164 // FD.
4165 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4166 continue;
4167
4168 // C++ [temp.expl.spec]p11:
4169 // A trailing template-argument can be left unspecified in the
4170 // template-id naming an explicit function template specialization
4171 // provided it can be deduced from the function argument type.
4172 // Perform template argument deduction to determine whether we may be
4173 // specializing this template.
4174 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004175 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004176 FunctionDecl *Specialization = 0;
4177 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004178 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004179 FD->getType(),
4180 Specialization,
4181 Info)) {
4182 // FIXME: Template argument deduction failed; record why it failed, so
4183 // that we can provide nifty diagnostics.
4184 (void)TDK;
4185 continue;
4186 }
4187
4188 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004189 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004190 }
4191 }
4192
Douglas Gregor5de279c2009-09-26 03:41:46 +00004193 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004194 UnresolvedSetIterator Result
4195 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4196 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004197 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004198 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004199 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004200 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004201 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004202 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004203 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004204
4205 // Ignore access information; it doesn't figure into redeclaration checking.
4206 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004207 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004208
4209 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004210 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004211
4212 // If this is a friend declaration, then we're not really declaring
4213 // an explicit specialization.
4214 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004215
Douglas Gregor54888652009-10-07 00:13:32 +00004216 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004217 if (!isFriend &&
4218 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004219 Specialization->getPrimaryTemplate(),
4220 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004221 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004222 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004223
4224 // C++ [temp.expl.spec]p6:
4225 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004226 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004227 // before the first use of that specialization that would cause an implicit
4228 // instantiation to take place, in every translation unit in which such a
4229 // use occurs; no diagnostic is required.
4230 FunctionTemplateSpecializationInfo *SpecInfo
4231 = Specialization->getTemplateSpecializationInfo();
4232 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004233
4234 bool SuppressNew = false;
John McCall816d75b2010-03-24 07:46:06 +00004235 if (!isFriend &&
4236 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004237 TSK_ExplicitSpecialization,
4238 Specialization,
4239 SpecInfo->getTemplateSpecializationKind(),
4240 SpecInfo->getPointOfInstantiation(),
4241 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004242 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004243
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004244 // Mark the prior declaration as an explicit specialization, so that later
4245 // clients know that this is an explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004246 if (!isFriend)
4247 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004248
4249 // Turn the given function declaration into a function template
4250 // specialization, with the template arguments from the previous
4251 // specialization.
Douglas Gregord5058122010-02-11 01:19:42 +00004252 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004253 new (Context) TemplateArgumentList(
4254 *Specialization->getTemplateSpecializationArgs()),
4255 /*InsertPos=*/0,
John McCall816d75b2010-03-24 07:46:06 +00004256 SpecInfo->getTemplateSpecializationKind());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004257
4258 // The "previous declaration" for this function template specialization is
4259 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004260 Previous.clear();
4261 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004262 return false;
4263}
4264
Douglas Gregor86d142a2009-10-08 07:24:58 +00004265/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004266/// specialization.
4267///
4268/// This routine performs all of the semantic analysis required for an
4269/// explicit member function specialization. On successful completion,
4270/// the function declaration \p FD will become a member function
4271/// specialization.
4272///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004273/// \param Member the member declaration, which will be updated to become a
4274/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004275///
John McCall1f82f242009-11-18 22:49:29 +00004276/// \param Previous the set of declarations, one of which may be specialized
4277/// by this function specialization; the set will be modified to contain the
4278/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004279bool
John McCall1f82f242009-11-18 22:49:29 +00004280Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004281 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
4282
4283 // Try to find the member we are instantiating.
4284 NamedDecl *Instantiation = 0;
4285 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004286 MemberSpecializationInfo *MSInfo = 0;
4287
John McCall1f82f242009-11-18 22:49:29 +00004288 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004289 // Nowhere to look anyway.
4290 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004291 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4292 I != E; ++I) {
4293 NamedDecl *D = (*I)->getUnderlyingDecl();
4294 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004295 if (Context.hasSameType(Function->getType(), Method->getType())) {
4296 Instantiation = Method;
4297 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004298 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004299 break;
4300 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004301 }
4302 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004303 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004304 VarDecl *PrevVar;
4305 if (Previous.isSingleResult() &&
4306 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004307 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004308 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004309 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004310 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004311 }
4312 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004313 CXXRecordDecl *PrevRecord;
4314 if (Previous.isSingleResult() &&
4315 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4316 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004317 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004318 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004319 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004320 }
4321
4322 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004323 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004324 // specializations are always out-of-line, the caller will complain about
4325 // this mismatch later.
4326 return false;
4327 }
4328
Douglas Gregor86d142a2009-10-08 07:24:58 +00004329 // Make sure that this is a specialization of a member.
4330 if (!InstantiatedFrom) {
4331 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4332 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004333 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4334 return true;
4335 }
4336
Douglas Gregor06db9f52009-10-12 20:18:28 +00004337 // C++ [temp.expl.spec]p6:
4338 // If a template, a member template or the member of a class template is
4339 // explicitly specialized then that spe- cialization shall be declared
4340 // before the first use of that specialization that would cause an implicit
4341 // instantiation to take place, in every translation unit in which such a
4342 // use occurs; no diagnostic is required.
4343 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004344
4345 bool SuppressNew = false;
4346 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4347 TSK_ExplicitSpecialization,
4348 Instantiation,
4349 MSInfo->getTemplateSpecializationKind(),
4350 MSInfo->getPointOfInstantiation(),
4351 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004352 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004353
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004354 // Check the scope of this explicit specialization.
4355 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004356 InstantiatedFrom,
4357 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004358 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004359 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004360
Douglas Gregor86d142a2009-10-08 07:24:58 +00004361 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004362 // the original declaration to note that it is an explicit specialization
4363 // (if it was previously an implicit instantiation). This latter step
4364 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004365 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004366 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4367 if (InstantiationFunction->getTemplateSpecializationKind() ==
4368 TSK_ImplicitInstantiation) {
4369 InstantiationFunction->setTemplateSpecializationKind(
4370 TSK_ExplicitSpecialization);
4371 InstantiationFunction->setLocation(Member->getLocation());
4372 }
4373
Douglas Gregor86d142a2009-10-08 07:24:58 +00004374 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4375 cast<CXXMethodDecl>(InstantiatedFrom),
4376 TSK_ExplicitSpecialization);
4377 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004378 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4379 if (InstantiationVar->getTemplateSpecializationKind() ==
4380 TSK_ImplicitInstantiation) {
4381 InstantiationVar->setTemplateSpecializationKind(
4382 TSK_ExplicitSpecialization);
4383 InstantiationVar->setLocation(Member->getLocation());
4384 }
4385
Douglas Gregor86d142a2009-10-08 07:24:58 +00004386 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4387 cast<VarDecl>(InstantiatedFrom),
4388 TSK_ExplicitSpecialization);
4389 } else {
4390 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004391 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4392 if (InstantiationClass->getTemplateSpecializationKind() ==
4393 TSK_ImplicitInstantiation) {
4394 InstantiationClass->setTemplateSpecializationKind(
4395 TSK_ExplicitSpecialization);
4396 InstantiationClass->setLocation(Member->getLocation());
4397 }
4398
Douglas Gregor86d142a2009-10-08 07:24:58 +00004399 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004400 cast<CXXRecordDecl>(InstantiatedFrom),
4401 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004402 }
4403
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004404 // Save the caller the trouble of having to figure out which declaration
4405 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004406 Previous.clear();
4407 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004408 return false;
4409}
4410
Douglas Gregore47f5a72009-10-14 23:41:34 +00004411/// \brief Check the scope of an explicit instantiation.
4412static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4413 SourceLocation InstLoc,
4414 bool WasQualifiedName) {
4415 DeclContext *ExpectedContext
4416 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4417 DeclContext *CurContext = S.CurContext->getLookupContext();
4418
4419 // C++0x [temp.explicit]p2:
4420 // An explicit instantiation shall appear in an enclosing namespace of its
4421 // template.
4422 //
4423 // This is DR275, which we do not retroactively apply to C++98/03.
4424 if (S.getLangOptions().CPlusPlus0x &&
4425 !CurContext->Encloses(ExpectedContext)) {
4426 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4427 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4428 << D << NS;
4429 else
4430 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4431 << D;
4432 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4433 return;
4434 }
4435
4436 // C++0x [temp.explicit]p2:
4437 // If the name declared in the explicit instantiation is an unqualified
4438 // name, the explicit instantiation shall appear in the namespace where
4439 // its template is declared or, if that namespace is inline (7.3.1), any
4440 // namespace from its enclosing namespace set.
4441 if (WasQualifiedName)
4442 return;
4443
4444 if (CurContext->Equals(ExpectedContext))
4445 return;
4446
4447 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4448 << D << ExpectedContext;
4449 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4450}
4451
4452/// \brief Determine whether the given scope specifier has a template-id in it.
4453static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4454 if (!SS.isSet())
4455 return false;
4456
4457 // C++0x [temp.explicit]p2:
4458 // If the explicit instantiation is for a member function, a member class
4459 // or a static data member of a class template specialization, the name of
4460 // the class template specialization in the qualified-id for the member
4461 // name shall be a simple-template-id.
4462 //
4463 // C++98 has the same restriction, just worded differently.
4464 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4465 NNS; NNS = NNS->getPrefix())
4466 if (Type *T = NNS->getAsType())
4467 if (isa<TemplateSpecializationType>(T))
4468 return true;
4469
4470 return false;
4471}
4472
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004473// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004474// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004475Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004476Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004477 SourceLocation ExternLoc,
4478 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004479 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004480 SourceLocation KWLoc,
4481 const CXXScopeSpec &SS,
4482 TemplateTy TemplateD,
4483 SourceLocation TemplateNameLoc,
4484 SourceLocation LAngleLoc,
4485 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004486 SourceLocation RAngleLoc,
4487 AttributeList *Attr) {
4488 // Find the class template we're specializing
4489 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004490 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004491 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4492
4493 // Check that the specialization uses the same tag kind as the
4494 // original template.
4495 TagDecl::TagKind Kind;
4496 switch (TagSpec) {
4497 default: assert(0 && "Unknown tag type!");
4498 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4499 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4500 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4501 }
Douglas Gregord9034f02009-05-14 16:41:31 +00004502 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004503 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004504 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004505 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004506 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004507 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004508 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004509 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004510 diag::note_previous_use);
4511 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4512 }
4513
Douglas Gregore47f5a72009-10-14 23:41:34 +00004514 // C++0x [temp.explicit]p2:
4515 // There are two forms of explicit instantiation: an explicit instantiation
4516 // definition and an explicit instantiation declaration. An explicit
4517 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004518 TemplateSpecializationKind TSK
4519 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4520 : TSK_ExplicitInstantiationDeclaration;
4521
Douglas Gregora1f49972009-05-13 00:25:59 +00004522 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004523 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004524 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004525
4526 // Check that the template argument list is well-formed for this
4527 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004528 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4529 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004530 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4531 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004532 return true;
4533
Mike Stump11289f42009-09-09 15:08:12 +00004534 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004535 ClassTemplate->getTemplateParameters()->size()) &&
4536 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004537
Douglas Gregora1f49972009-05-13 00:25:59 +00004538 // Find the class template specialization declaration that
4539 // corresponds to these arguments.
4540 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004541 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004542 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004543 Converted.flatSize(),
4544 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004545 void *InsertPos = 0;
4546 ClassTemplateSpecializationDecl *PrevDecl
4547 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4548
Douglas Gregor54888652009-10-07 00:13:32 +00004549 // C++0x [temp.explicit]p2:
4550 // [...] An explicit instantiation shall appear in an enclosing
4551 // namespace of its template. [...]
4552 //
4553 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004554 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4555 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004556
Douglas Gregora1f49972009-05-13 00:25:59 +00004557 ClassTemplateSpecializationDecl *Specialization = 0;
4558
Douglas Gregor0681a352009-11-25 06:01:46 +00004559 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004560 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004561 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004562 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004563 PrevDecl,
4564 PrevDecl->getSpecializationKind(),
4565 PrevDecl->getPointOfInstantiation(),
4566 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004567 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004568
Douglas Gregor12e49d32009-10-15 22:53:21 +00004569 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004570 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004571
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004572 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4573 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4574 // Since the only prior class template specialization with these
4575 // arguments was referenced but not declared, reuse that
4576 // declaration node as our own, updating its source location to
4577 // reflect our new declaration.
4578 Specialization = PrevDecl;
4579 Specialization->setLocation(TemplateNameLoc);
4580 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004581 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004582 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004583 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004584
4585 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004586 // Create a new class template specialization declaration node for
4587 // this explicit specialization.
4588 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00004589 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00004590 ClassTemplate->getDeclContext(),
4591 TemplateNameLoc,
4592 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004593 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004594 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004595
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004596 if (PrevDecl) {
4597 // Remove the previous declaration from the folding set, since we want
4598 // to introduce a new declaration.
4599 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4600 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4601 }
4602
4603 // Insert the new specialization.
4604 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004605 }
4606
4607 // Build the fully-sugared type for this explicit instantiation as
4608 // the user wrote in the explicit instantiation itself. This means
4609 // that we'll pretty-print the type retrieved from the
4610 // specialization's declaration the way that the user actually wrote
4611 // the explicit instantiation, rather than formatting the name based
4612 // on the "canonical" representation used to store the template
4613 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004614 TypeSourceInfo *WrittenTy
4615 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4616 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004617 Context.getTypeDeclType(Specialization));
4618 Specialization->setTypeAsWritten(WrittenTy);
4619 TemplateArgsIn.release();
4620
Douglas Gregor0681a352009-11-25 06:01:46 +00004621 if (!ReusedDecl) {
4622 // Add the explicit instantiation into its lexical context. However,
4623 // since explicit instantiations are never found by name lookup, we
4624 // just put it into the declaration context directly.
4625 Specialization->setLexicalDeclContext(CurContext);
4626 CurContext->addDecl(Specialization);
4627 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004628
4629 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004630 // A definition of a class template or class member template
4631 // shall be in scope at the point of the explicit instantiation of
4632 // the class template or class member template.
4633 //
4634 // This check comes when we actually try to perform the
4635 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004636 ClassTemplateSpecializationDecl *Def
4637 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004638 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004639 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004640 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004641
4642 // Instantiate the members of this class template specialization.
4643 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004644 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004645 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004646 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4647
4648 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4649 // TSK_ExplicitInstantiationDefinition
4650 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4651 TSK == TSK_ExplicitInstantiationDefinition)
4652 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004653
Douglas Gregor12e49d32009-10-15 22:53:21 +00004654 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004655 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004656
4657 return DeclPtrTy::make(Specialization);
4658}
4659
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004660// Explicit instantiation of a member class of a class template.
4661Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004662Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004663 SourceLocation ExternLoc,
4664 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004665 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004666 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004667 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004668 IdentifierInfo *Name,
4669 SourceLocation NameLoc,
4670 AttributeList *Attr) {
4671
Douglas Gregord6ab8742009-05-28 23:31:59 +00004672 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004673 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004674 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004675 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004676 MultiTemplateParamsArg(*this, 0, 0),
4677 Owned, IsDependent);
4678 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4679
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004680 if (!TagD)
4681 return true;
4682
4683 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4684 if (Tag->isEnum()) {
4685 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4686 << Context.getTypeDeclType(Tag);
4687 return true;
4688 }
4689
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004690 if (Tag->isInvalidDecl())
4691 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004692
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004693 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4694 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4695 if (!Pattern) {
4696 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4697 << Context.getTypeDeclType(Record);
4698 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4699 return true;
4700 }
4701
Douglas Gregore47f5a72009-10-14 23:41:34 +00004702 // C++0x [temp.explicit]p2:
4703 // If the explicit instantiation is for a class or member class, the
4704 // elaborated-type-specifier in the declaration shall include a
4705 // simple-template-id.
4706 //
4707 // C++98 has the same restriction, just worded differently.
4708 if (!ScopeSpecifierHasTemplateId(SS))
4709 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4710 << Record << SS.getRange();
4711
4712 // C++0x [temp.explicit]p2:
4713 // There are two forms of explicit instantiation: an explicit instantiation
4714 // definition and an explicit instantiation declaration. An explicit
4715 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004716 TemplateSpecializationKind TSK
4717 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4718 : TSK_ExplicitInstantiationDeclaration;
4719
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004720 // C++0x [temp.explicit]p2:
4721 // [...] An explicit instantiation shall appear in an enclosing
4722 // namespace of its template. [...]
4723 //
4724 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004725 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004726
4727 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004728 CXXRecordDecl *PrevDecl
4729 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004730 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004731 PrevDecl = Record;
4732 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004733 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4734 bool SuppressNew = false;
4735 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004736 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004737 PrevDecl,
4738 MSInfo->getTemplateSpecializationKind(),
4739 MSInfo->getPointOfInstantiation(),
4740 SuppressNew))
4741 return true;
4742 if (SuppressNew)
4743 return TagD;
4744 }
4745
Douglas Gregor12e49d32009-10-15 22:53:21 +00004746 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004747 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004748 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004749 // C++ [temp.explicit]p3:
4750 // A definition of a member class of a class template shall be in scope
4751 // at the point of an explicit instantiation of the member class.
4752 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004753 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004754 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004755 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4756 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004757 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4758 << Pattern;
4759 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004760 } else {
4761 if (InstantiateClass(NameLoc, Record, Def,
4762 getTemplateInstantiationArgs(Record),
4763 TSK))
4764 return true;
4765
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004766 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004767 if (!RecordDef)
4768 return true;
4769 }
4770 }
4771
4772 // Instantiate all of the members of the class.
4773 InstantiateClassMembers(NameLoc, RecordDef,
4774 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004775
Mike Stump87c57ac2009-05-16 07:39:55 +00004776 // FIXME: We don't have any representation for explicit instantiations of
4777 // member classes. Such a representation is not needed for compilation, but it
4778 // should be available for clients that want to see all of the declarations in
4779 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004780 return TagD;
4781}
4782
Douglas Gregor450f00842009-09-25 18:43:00 +00004783Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4784 SourceLocation ExternLoc,
4785 SourceLocation TemplateLoc,
4786 Declarator &D) {
4787 // Explicit instantiations always require a name.
4788 DeclarationName Name = GetNameForDeclarator(D);
4789 if (!Name) {
4790 if (!D.isInvalidType())
4791 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4792 diag::err_explicit_instantiation_requires_name)
4793 << D.getDeclSpec().getSourceRange()
4794 << D.getSourceRange();
4795
4796 return true;
4797 }
4798
4799 // The scope passed in may not be a decl scope. Zip up the scope tree until
4800 // we find one that is.
4801 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4802 (S->getFlags() & Scope::TemplateParamScope) != 0)
4803 S = S->getParent();
4804
4805 // Determine the type of the declaration.
4806 QualType R = GetTypeForDeclarator(D, S, 0);
4807 if (R.isNull())
4808 return true;
4809
4810 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4811 // Cannot explicitly instantiate a typedef.
4812 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4813 << Name;
4814 return true;
4815 }
4816
Douglas Gregor3c74d412009-10-14 20:14:33 +00004817 // C++0x [temp.explicit]p1:
4818 // [...] An explicit instantiation of a function template shall not use the
4819 // inline or constexpr specifiers.
4820 // Presumably, this also applies to member functions of class templates as
4821 // well.
4822 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4823 Diag(D.getDeclSpec().getInlineSpecLoc(),
4824 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00004825 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004826
4827 // FIXME: check for constexpr specifier.
4828
Douglas Gregore47f5a72009-10-14 23:41:34 +00004829 // C++0x [temp.explicit]p2:
4830 // There are two forms of explicit instantiation: an explicit instantiation
4831 // definition and an explicit instantiation declaration. An explicit
4832 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004833 TemplateSpecializationKind TSK
4834 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4835 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004836
John McCall27b18f82009-11-17 02:14:36 +00004837 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4838 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004839
4840 if (!R->isFunctionType()) {
4841 // C++ [temp.explicit]p1:
4842 // A [...] static data member of a class template can be explicitly
4843 // instantiated from the member definition associated with its class
4844 // template.
John McCall27b18f82009-11-17 02:14:36 +00004845 if (Previous.isAmbiguous())
4846 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004847
John McCall67c00872009-12-02 08:25:40 +00004848 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00004849 if (!Prev || !Prev->isStaticDataMember()) {
4850 // We expect to see a data data member here.
4851 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4852 << Name;
4853 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4854 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004855 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004856 return true;
4857 }
4858
4859 if (!Prev->getInstantiatedFromStaticDataMember()) {
4860 // FIXME: Check for explicit specialization?
4861 Diag(D.getIdentifierLoc(),
4862 diag::err_explicit_instantiation_data_member_not_instantiated)
4863 << Prev;
4864 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4865 // FIXME: Can we provide a note showing where this was declared?
4866 return true;
4867 }
4868
Douglas Gregore47f5a72009-10-14 23:41:34 +00004869 // C++0x [temp.explicit]p2:
4870 // If the explicit instantiation is for a member function, a member class
4871 // or a static data member of a class template specialization, the name of
4872 // the class template specialization in the qualified-id for the member
4873 // name shall be a simple-template-id.
4874 //
4875 // C++98 has the same restriction, just worded differently.
4876 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4877 Diag(D.getIdentifierLoc(),
4878 diag::err_explicit_instantiation_without_qualified_id)
4879 << Prev << D.getCXXScopeSpec().getRange();
4880
4881 // Check the scope of this explicit instantiation.
4882 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4883
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004884 // Verify that it is okay to explicitly instantiate here.
4885 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4886 assert(MSInfo && "Missing static data member specialization info?");
4887 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004888 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004889 MSInfo->getTemplateSpecializationKind(),
4890 MSInfo->getPointOfInstantiation(),
4891 SuppressNew))
4892 return true;
4893 if (SuppressNew)
4894 return DeclPtrTy();
4895
Douglas Gregor450f00842009-09-25 18:43:00 +00004896 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004897 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004898 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004899 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4900 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004901
4902 // FIXME: Create an ExplicitInstantiation node?
4903 return DeclPtrTy();
4904 }
4905
Douglas Gregor0e876e02009-09-25 23:53:26 +00004906 // If the declarator is a template-id, translate the parser's template
4907 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004908 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004909 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004910 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4911 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004912 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4913 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004914 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4915 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004916 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004917 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004918 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004919 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004920 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004921
Douglas Gregor450f00842009-09-25 18:43:00 +00004922 // C++ [temp.explicit]p1:
4923 // A [...] function [...] can be explicitly instantiated from its template.
4924 // A member function [...] of a class template can be explicitly
4925 // instantiated from the member definition associated with its class
4926 // template.
John McCall58cc69d2010-01-27 01:50:18 +00004927 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00004928 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4929 P != PEnd; ++P) {
4930 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004931 if (!HasExplicitTemplateArgs) {
4932 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4933 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4934 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004935
John McCall58cc69d2010-01-27 01:50:18 +00004936 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004937 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
4938 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00004939 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004940 }
4941 }
4942
4943 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4944 if (!FunTmpl)
4945 continue;
4946
John McCallbc077cf2010-02-08 23:07:23 +00004947 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004948 FunctionDecl *Specialization = 0;
4949 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004950 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00004951 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004952 R, Specialization, Info)) {
4953 // FIXME: Keep track of almost-matches?
4954 (void)TDK;
4955 continue;
4956 }
4957
John McCall58cc69d2010-01-27 01:50:18 +00004958 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00004959 }
4960
4961 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004962 UnresolvedSetIterator Result
4963 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00004964 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00004965 PDiag(diag::err_explicit_instantiation_not_known) << Name,
4966 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
4967 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00004968
John McCall58cc69d2010-01-27 01:50:18 +00004969 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00004970 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004971
4972 // Ignore access control bits, we don't need them for redeclaration checking.
4973 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00004974
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004975 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004976 Diag(D.getIdentifierLoc(),
4977 diag::err_explicit_instantiation_member_function_not_instantiated)
4978 << Specialization
4979 << (Specialization->getTemplateSpecializationKind() ==
4980 TSK_ExplicitSpecialization);
4981 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4982 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004983 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004984
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004985 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004986 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4987 PrevDecl = Specialization;
4988
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004989 if (PrevDecl) {
4990 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004991 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004992 PrevDecl,
4993 PrevDecl->getTemplateSpecializationKind(),
4994 PrevDecl->getPointOfInstantiation(),
4995 SuppressNew))
4996 return true;
4997
4998 // FIXME: We may still want to build some representation of this
4999 // explicit specialization.
5000 if (SuppressNew)
5001 return DeclPtrTy();
5002 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005003
5004 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005005
5006 if (TSK == TSK_ExplicitInstantiationDefinition)
5007 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5008 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005009
Douglas Gregore47f5a72009-10-14 23:41:34 +00005010 // C++0x [temp.explicit]p2:
5011 // If the explicit instantiation is for a member function, a member class
5012 // or a static data member of a class template specialization, the name of
5013 // the class template specialization in the qualified-id for the member
5014 // name shall be a simple-template-id.
5015 //
5016 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005017 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005018 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005019 D.getCXXScopeSpec().isSet() &&
5020 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5021 Diag(D.getIdentifierLoc(),
5022 diag::err_explicit_instantiation_without_qualified_id)
5023 << Specialization << D.getCXXScopeSpec().getRange();
5024
5025 CheckExplicitInstantiationScope(*this,
5026 FunTmpl? (NamedDecl *)FunTmpl
5027 : Specialization->getInstantiatedFromMemberFunction(),
5028 D.getIdentifierLoc(),
5029 D.getCXXScopeSpec().isSet());
5030
Douglas Gregor450f00842009-09-25 18:43:00 +00005031 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5032 return DeclPtrTy();
5033}
5034
Douglas Gregor333489b2009-03-27 23:10:48 +00005035Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005036Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5037 const CXXScopeSpec &SS, IdentifierInfo *Name,
5038 SourceLocation TagLoc, SourceLocation NameLoc) {
5039 // This has to hold, because SS is expected to be defined.
5040 assert(Name && "Expected a name in a dependent tag");
5041
5042 NestedNameSpecifier *NNS
5043 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5044 if (!NNS)
5045 return true;
5046
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005047 ElaboratedTypeKeyword Keyword = ETK_None;
Douglas Gregore677daf2010-03-31 22:19:08 +00005048 switch (TagDecl::getTagKindForTypeSpec(TagSpec)) {
5049 case TagDecl::TK_struct: Keyword = ETK_Struct; break;
5050 case TagDecl::TK_class: Keyword = ETK_Class; break;
5051 case TagDecl::TK_union: Keyword = ETK_Union; break;
5052 case TagDecl::TK_enum: Keyword = ETK_Enum; break;
5053 }
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005054 assert(Keyword != ETK_None && "Invalid tag kind!");
5055
Douglas Gregore677daf2010-03-31 22:19:08 +00005056 return Context.getDependentNameType(Keyword, NNS, Name).getAsOpaquePtr();
John McCall7f41d982009-09-11 04:59:25 +00005057}
5058
5059Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00005060Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5061 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005062 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005063 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5064 if (!NNS)
5065 return true;
5066
5067 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005068 if (T.isNull())
5069 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00005070 return T.getAsOpaquePtr();
5071}
5072
Douglas Gregordce2b622009-04-01 00:28:59 +00005073Sema::TypeResult
5074Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5075 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005076 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005077 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00005078 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00005079 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00005080 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00005081 assert(TemplateId && "Expected a template specialization type");
5082
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005083 if (computeDeclContext(SS, false)) {
5084 // If we can compute a declaration context, then the "typename"
5085 // keyword was superfluous. Just build a QualifiedNameType to keep
5086 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00005087
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005088 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
5089 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
5090 }
Mike Stump11289f42009-09-09 15:08:12 +00005091
Douglas Gregor02085352010-03-31 20:19:30 +00005092 return Context.getDependentNameType(ETK_Typename, NNS, TemplateId)
5093 .getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00005094}
5095
Douglas Gregor333489b2009-03-27 23:10:48 +00005096/// \brief Build the type that describes a C++ typename specifier,
5097/// e.g., "typename T::type".
5098QualType
5099Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
5100 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005101 CXXRecordDecl *CurrentInstantiation = 0;
5102 if (NNS->isDependent()) {
5103 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00005104
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005105 // If the nested-name-specifier does not refer to the current
5106 // instantiation, then build a typename type.
5107 if (!CurrentInstantiation)
Douglas Gregor02085352010-03-31 20:19:30 +00005108 return Context.getDependentNameType(ETK_Typename, NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00005109
Douglas Gregorc707da62009-09-02 13:12:51 +00005110 // The nested-name-specifier refers to the current instantiation, so the
5111 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00005112 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00005113 // extraneous "typename" keywords, and we retroactively apply this DR to
5114 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005115 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005116
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005117 DeclContext *Ctx = 0;
5118
5119 if (CurrentInstantiation)
5120 Ctx = CurrentInstantiation;
5121 else {
5122 CXXScopeSpec SS;
5123 SS.setScopeRep(NNS);
5124 SS.setRange(Range);
5125 if (RequireCompleteDeclContext(SS))
5126 return QualType();
5127
5128 Ctx = computeDeclContext(SS);
5129 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005130 assert(Ctx && "No declaration context?");
5131
5132 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00005133 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
5134 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005135 unsigned DiagID = 0;
5136 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005137 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005138 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005139 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005140 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005141
5142 case LookupResult::NotFoundInCurrentInstantiation:
5143 // Okay, it's a member of an unknown instantiation.
Douglas Gregor02085352010-03-31 20:19:30 +00005144 return Context.getDependentNameType(ETK_Typename, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005145
5146 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00005147 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005148 // We found a type. Build a QualifiedNameType, since the
5149 // typename-specifier was just sugar. FIXME: Tell
5150 // QualifiedNameType that it has a "typename" prefix.
5151 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
5152 }
5153
5154 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005155 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005156 break;
5157
John McCalle61f2ba2009-11-18 02:36:19 +00005158 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005159 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005160 return QualType();
5161
Douglas Gregor333489b2009-03-27 23:10:48 +00005162 case LookupResult::FoundOverloaded:
5163 DiagID = diag::err_typename_nested_not_type;
5164 Referenced = *Result.begin();
5165 break;
5166
John McCall6538c932009-10-10 05:48:19 +00005167 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005168 return QualType();
5169 }
5170
5171 // If we get here, it's because name lookup did not find a
5172 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00005173 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005174 if (Referenced)
5175 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5176 << Name;
5177 return QualType();
5178}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005179
5180namespace {
5181 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005182 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005183 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005184 SourceLocation Loc;
5185 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005186
Douglas Gregor15acfb92009-08-06 16:20:37 +00005187 public:
Mike Stump11289f42009-09-09 15:08:12 +00005188 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005189 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005190 DeclarationName Entity)
5191 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005192 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005193
5194 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005195 /// transformed.
5196 ///
5197 /// For the purposes of type reconstruction, a type has already been
5198 /// transformed if it is NULL or if it is not dependent.
5199 bool AlreadyTransformed(QualType T) {
5200 return T.isNull() || !T->isDependentType();
5201 }
Mike Stump11289f42009-09-09 15:08:12 +00005202
5203 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005204 /// rebuilt.
5205 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005206
Douglas Gregor15acfb92009-08-06 16:20:37 +00005207 /// \brief Returns the name of the entity whose type is being rebuilt.
5208 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005209
Douglas Gregoref6ab412009-10-27 06:26:26 +00005210 /// \brief Sets the "base" location and entity when that
5211 /// information is known based on another transformation.
5212 void setBase(SourceLocation Loc, DeclarationName Entity) {
5213 this->Loc = Loc;
5214 this->Entity = Entity;
5215 }
5216
Douglas Gregor15acfb92009-08-06 16:20:37 +00005217 /// \brief Transforms an expression by returning the expression itself
5218 /// (an identity function).
5219 ///
5220 /// FIXME: This is completely unsafe; we will need to actually clone the
5221 /// expressions.
5222 Sema::OwningExprResult TransformExpr(Expr *E) {
5223 return getSema().Owned(E);
5224 }
Mike Stump11289f42009-09-09 15:08:12 +00005225
Douglas Gregor15acfb92009-08-06 16:20:37 +00005226 /// \brief Transforms a typename type by determining whether the type now
5227 /// refers to a member of the current instantiation, and then
5228 /// type-checking and building a QualifiedNameType (when possible).
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005229 QualType TransformDependentNameType(TypeLocBuilder &TLB, DependentNameTypeLoc TL,
Douglas Gregorfe17d252010-02-16 19:09:40 +00005230 QualType ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00005231 };
5232}
5233
Mike Stump11289f42009-09-09 15:08:12 +00005234QualType
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005235CurrentInstantiationRebuilder::TransformDependentNameType(TypeLocBuilder &TLB,
5236 DependentNameTypeLoc TL,
Douglas Gregorfe17d252010-02-16 19:09:40 +00005237 QualType ObjectType) {
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005238 DependentNameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00005239
Douglas Gregor15acfb92009-08-06 16:20:37 +00005240 NestedNameSpecifier *NNS
5241 = TransformNestedNameSpecifier(T->getQualifier(),
Douglas Gregorfe17d252010-02-16 19:09:40 +00005242 /*FIXME:*/SourceRange(getBaseLocation()),
5243 ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00005244 if (!NNS)
5245 return QualType();
5246
5247 // If the nested-name-specifier did not change, and we cannot compute the
5248 // context corresponding to the nested-name-specifier, then this
5249 // typename type will not change; exit early.
5250 CXXScopeSpec SS;
5251 SS.setRange(SourceRange(getBaseLocation()));
5252 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00005253
5254 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005255 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00005256 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00005257
5258 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00005259 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00005260 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00005261 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00005262 = TransformType(QualType(TemplateId, 0));
5263 if (NewTemplateId.isNull())
5264 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005265
Douglas Gregor15acfb92009-08-06 16:20:37 +00005266 if (NNS == T->getQualifier() &&
5267 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00005268 Result = QualType(T, 0);
5269 else
Douglas Gregor02085352010-03-31 20:19:30 +00005270 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
5271 NNS, NewTemplateId);
John McCall0ad16662009-10-29 08:12:44 +00005272 } else
Douglas Gregor02085352010-03-31 20:19:30 +00005273 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
5274 NNS, T->getIdentifier(),
5275 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00005276
Douglas Gregor281c4862010-03-07 23:26:22 +00005277 if (Result.isNull())
5278 return QualType();
5279
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005280 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
John McCall0ad16662009-10-29 08:12:44 +00005281 NewTL.setNameLoc(TL.getNameLoc());
5282 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005283}
5284
5285/// \brief Rebuilds a type within the context of the current instantiation.
5286///
Mike Stump11289f42009-09-09 15:08:12 +00005287/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005288/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005289/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005290/// partial specialization thereof). This routine will rebuild that type now
5291/// that we have entered the declarator's scope, which may produce different
5292/// canonical types, e.g.,
5293///
5294/// \code
5295/// template<typename T>
5296/// struct X {
5297/// typedef T* pointer;
5298/// pointer data();
5299/// };
5300///
5301/// template<typename T>
5302/// typename X<T>::pointer X<T>::data() { ... }
5303/// \endcode
5304///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005305/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005306/// since we do not know that we can look into X<T> when we parsed the type.
5307/// This function will rebuild the type, performing the lookup of "pointer"
5308/// in X<T> and returning a QualifiedNameType whose canonical type is the same
5309/// as the canonical type of T*, allowing the return types of the out-of-line
5310/// definition and the declaration to match.
5311QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
5312 DeclarationName Name) {
5313 if (T.isNull() || !T->isDependentType())
5314 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005315
Douglas Gregor15acfb92009-08-06 16:20:37 +00005316 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5317 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005318}
Douglas Gregorbe999392009-09-15 16:23:51 +00005319
5320/// \brief Produces a formatted string that describes the binding of
5321/// template parameters to template arguments.
5322std::string
5323Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5324 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005325 // FIXME: For variadic templates, we'll need to get the structured list.
5326 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5327 Args.flat_size());
5328}
5329
5330std::string
5331Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5332 const TemplateArgument *Args,
5333 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005334 std::string Result;
5335
Douglas Gregore62e6a02009-11-11 19:13:48 +00005336 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005337 return Result;
5338
5339 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005340 if (I >= NumArgs)
5341 break;
5342
Douglas Gregorbe999392009-09-15 16:23:51 +00005343 if (I == 0)
5344 Result += "[with ";
5345 else
5346 Result += ", ";
5347
5348 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5349 Result += Id->getName();
5350 } else {
5351 Result += '$';
5352 Result += llvm::utostr(I);
5353 }
5354
5355 Result += " = ";
5356
5357 switch (Args[I].getKind()) {
5358 case TemplateArgument::Null:
5359 Result += "<no value>";
5360 break;
5361
5362 case TemplateArgument::Type: {
5363 std::string TypeStr;
5364 Args[I].getAsType().getAsStringInternal(TypeStr,
5365 Context.PrintingPolicy);
5366 Result += TypeStr;
5367 break;
5368 }
5369
5370 case TemplateArgument::Declaration: {
5371 bool Unnamed = true;
5372 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5373 if (ND->getDeclName()) {
5374 Unnamed = false;
5375 Result += ND->getNameAsString();
5376 }
5377 }
5378
5379 if (Unnamed) {
5380 Result += "<anonymous>";
5381 }
5382 break;
5383 }
5384
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005385 case TemplateArgument::Template: {
5386 std::string Str;
5387 llvm::raw_string_ostream OS(Str);
5388 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5389 Result += OS.str();
5390 break;
5391 }
5392
Douglas Gregorbe999392009-09-15 16:23:51 +00005393 case TemplateArgument::Integral: {
5394 Result += Args[I].getAsIntegral()->toString(10);
5395 break;
5396 }
5397
5398 case TemplateArgument::Expression: {
5399 assert(false && "No expressions in deduced template arguments!");
5400 Result += "<expression>";
5401 break;
5402 }
5403
5404 case TemplateArgument::Pack:
5405 // FIXME: Format template argument packs
5406 Result += "<template argument pack>";
5407 break;
5408 }
5409 }
5410
5411 Result += ']';
5412 return Result;
5413}