blob: 0f3f86dbfd4e414ed8534fc752d9e05504f9b086 [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) {
Douglas Gregor41f90302010-04-12 20:54:26 +000066 // The set of class templates we've already seen.
67 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000068 LookupResult::Filter filter = R.makeFilter();
69 while (filter.hasNext()) {
70 NamedDecl *Orig = filter.next();
71 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
72 if (!Repl)
73 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000074 else if (Repl != Orig) {
75
76 // C++ [temp.local]p3:
77 // A lookup that finds an injected-class-name (10.2) can result in an
78 // ambiguity in certain cases (for example, if it is found in more than
79 // one base class). If all of the injected-class-names that are found
80 // refer to specializations of the same class template, and if the name
81 // is followed by a template-argument-list, the reference refers to the
82 // class template itself and not a specialization thereof, and is not
83 // ambiguous.
84 //
85 // FIXME: Will we eventually have to do the same for alias templates?
86 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
87 if (!ClassTemplates.insert(ClassTmpl)) {
88 filter.erase();
89 continue;
90 }
91
John McCalle66edc12009-11-24 19:00:30 +000092 filter.replace(Repl);
Douglas Gregor41f90302010-04-12 20:54:26 +000093 }
John McCalle66edc12009-11-24 19:00:30 +000094 }
95 filter.done();
96}
97
Douglas Gregorb7bfe792009-09-02 22:59:36 +000098TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000099 CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000100 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000101 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000102 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000103 TemplateTy &TemplateResult) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000104 assert(getLangOptions().CPlusPlus && "No template names in C!");
105
Douglas Gregor3cf81312009-11-03 23:16:33 +0000106 DeclarationName TName;
107
108 switch (Name.getKind()) {
109 case UnqualifiedId::IK_Identifier:
110 TName = DeclarationName(Name.Identifier);
111 break;
112
113 case UnqualifiedId::IK_OperatorFunctionId:
114 TName = Context.DeclarationNames.getCXXOperatorName(
115 Name.OperatorFunctionId.Operator);
116 break;
117
Alexis Hunted0530f2009-11-28 08:58:14 +0000118 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000119 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
120 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000121
Douglas Gregor3cf81312009-11-03 23:16:33 +0000122 default:
123 return TNK_Non_template;
124 }
Mike Stump11289f42009-09-09 15:08:12 +0000125
John McCalle66edc12009-11-24 19:00:30 +0000126 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000127
Douglas Gregorff18cc12009-12-31 08:11:17 +0000128 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
129 LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +0000130 R.suppressDiagnostics();
131 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
Douglas Gregor41f90302010-04-12 20:54:26 +0000132 if (R.empty() || R.isAmbiguous())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000133 return TNK_Non_template;
134
John McCalld28ae272009-12-02 08:04:21 +0000135 TemplateName Template;
136 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000137
John McCalld28ae272009-12-02 08:04:21 +0000138 unsigned ResultCount = R.end() - R.begin();
139 if (ResultCount > 1) {
140 // We assume that we'll preserve the qualifier from a function
141 // template name in other ways.
142 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
143 TemplateKind = TNK_Function_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000144 } else {
John McCalld28ae272009-12-02 08:04:21 +0000145 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
146
147 if (SS.isSet() && !SS.isInvalid()) {
148 NestedNameSpecifier *Qualifier
149 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
150 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
151 } else {
152 Template = TemplateName(TD);
153 }
154
155 if (isa<FunctionTemplateDecl>(TD))
156 TemplateKind = TNK_Function_template;
157 else {
158 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
159 TemplateKind = TNK_Type_template;
160 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000161 }
Mike Stump11289f42009-09-09 15:08:12 +0000162
John McCalld28ae272009-12-02 08:04:21 +0000163 TemplateResult = TemplateTy::make(Template);
164 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000165}
166
Douglas Gregor18473f32010-01-12 21:28:44 +0000167bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
168 SourceLocation IILoc,
169 Scope *S,
170 const CXXScopeSpec *SS,
171 TemplateTy &SuggestedTemplate,
172 TemplateNameKind &SuggestedKind) {
173 // We can't recover unless there's a dependent scope specifier preceding the
174 // template name.
175 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
176 computeDeclContext(*SS))
177 return false;
178
179 // The code is missing a 'template' keyword prior to the dependent template
180 // name.
181 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
182 Diag(IILoc, diag::err_template_kw_missing)
183 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000184 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000185 SuggestedTemplate
186 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
187 SuggestedKind = TNK_Dependent_template_name;
188 return true;
189}
190
John McCalle66edc12009-11-24 19:00:30 +0000191void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000192 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000193 QualType ObjectType,
194 bool EnteringContext) {
195 // Determine where to perform name lookup
196 DeclContext *LookupCtx = 0;
197 bool isDependent = false;
198 if (!ObjectType.isNull()) {
199 // This nested-name-specifier occurs in a member access expression, e.g.,
200 // x->B::f, and we are looking into the type of the object.
201 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
202 LookupCtx = computeDeclContext(ObjectType);
203 isDependent = ObjectType->isDependentType();
204 assert((isDependent || !ObjectType->isIncompleteType()) &&
205 "Caller should have completed object type");
206 } else if (SS.isSet()) {
207 // This nested-name-specifier occurs after another nested-name-specifier,
208 // so long into the context associated with the prior nested-name-specifier.
209 LookupCtx = computeDeclContext(SS, EnteringContext);
210 isDependent = isDependentScopeSpecifier(SS);
211
212 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000213 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000214 return;
215 }
216
217 bool ObjectTypeSearchedInScope = false;
218 if (LookupCtx) {
219 // Perform "qualified" name lookup into the declaration context we
220 // computed, which is either the type of the base of a member access
221 // expression or the declaration context associated with a prior
222 // nested-name-specifier.
223 LookupQualifiedName(Found, LookupCtx);
224
225 if (!ObjectType.isNull() && Found.empty()) {
226 // C++ [basic.lookup.classref]p1:
227 // In a class member access expression (5.2.5), if the . or -> token is
228 // immediately followed by an identifier followed by a <, the
229 // identifier must be looked up to determine whether the < is the
230 // beginning of a template argument list (14.2) or a less-than operator.
231 // The identifier is first looked up in the class of the object
232 // expression. If the identifier is not found, it is then looked up in
233 // the context of the entire postfix-expression and shall name a class
234 // or function template.
235 //
236 // FIXME: When we're instantiating a template, do we actually have to
237 // look in the scope of the template? Seems fishy...
238 if (S) LookupName(Found, S);
239 ObjectTypeSearchedInScope = true;
240 }
241 } else if (isDependent) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000242 // We cannot look into a dependent object type or nested nme
243 // specifier.
John McCalle66edc12009-11-24 19:00:30 +0000244 return;
245 } else {
246 // Perform unqualified name lookup in the current scope.
247 LookupName(Found, S);
248 }
249
Douglas Gregorc119dd52010-01-12 17:06:20 +0000250 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000251 // If we did not find any names, attempt to correct any typos.
252 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000253 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
254 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000255 FilterAcceptableTemplateNames(Context, Found);
256 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
257 if (LookupCtx)
258 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
259 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000260 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000261 Found.getLookupName().getAsString());
262 else
263 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
264 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000265 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000266 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000267 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
268 Diag(Template->getLocation(), diag::note_previous_decl)
269 << Template->getDeclName();
Douglas Gregorff18cc12009-12-31 08:11:17 +0000270 } else
271 Found.clear();
272 } else {
273 Found.clear();
274 }
275 }
276
John McCalle66edc12009-11-24 19:00:30 +0000277 FilterAcceptableTemplateNames(Context, Found);
278 if (Found.empty())
279 return;
280
281 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
282 // C++ [basic.lookup.classref]p1:
283 // [...] If the lookup in the class of the object expression finds a
284 // template, the name is also looked up in the context of the entire
285 // postfix-expression and [...]
286 //
287 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
288 LookupOrdinaryName);
289 LookupName(FoundOuter, S);
290 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000291
John McCalle66edc12009-11-24 19:00:30 +0000292 if (FoundOuter.empty()) {
293 // - if the name is not found, the name found in the class of the
294 // object expression is used, otherwise
295 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
296 // - if the name is found in the context of the entire
297 // postfix-expression and does not name a class template, the name
298 // found in the class of the object expression is used, otherwise
299 } else {
300 // - if the name found is a class template, it must refer to the same
301 // entity as the one found in the class of the object expression,
302 // otherwise the program is ill-formed.
303 if (!Found.isSingleResult() ||
304 Found.getFoundDecl()->getCanonicalDecl()
305 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
306 Diag(Found.getNameLoc(),
307 diag::err_nested_name_member_ref_lookup_ambiguous)
308 << Found.getLookupName();
309 Diag(Found.getRepresentativeDecl()->getLocation(),
310 diag::note_ambig_member_ref_object_type)
311 << ObjectType;
312 Diag(FoundOuter.getFoundDecl()->getLocation(),
313 diag::note_ambig_member_ref_scope);
314
315 // Recover by taking the template that we found in the object
316 // expression's type.
317 }
318 }
319 }
320}
321
John McCallcd4b4772009-12-02 03:53:29 +0000322/// ActOnDependentIdExpression - Handle a dependent id-expression that
323/// was just parsed. This is only possible with an explicit scope
324/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000325Sema::OwningExprResult
326Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
327 DeclarationName Name,
328 SourceLocation NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000329 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000330 const TemplateArgumentListInfo *TemplateArgs) {
331 NestedNameSpecifier *Qualifier
332 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
333
John McCallcd4b4772009-12-02 03:53:29 +0000334 if (!isAddressOfOperand &&
335 isa<CXXMethodDecl>(CurContext) &&
336 cast<CXXMethodDecl>(CurContext)->isInstance()) {
337 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
338
John McCalle66edc12009-11-24 19:00:30 +0000339 // Since the 'this' expression is synthesized, we don't need to
340 // perform the double-lookup check.
341 NamedDecl *FirstQualifierInScope = 0;
342
John McCall2d74de92009-12-01 22:10:20 +0000343 return Owned(CXXDependentScopeMemberExpr::Create(Context,
344 /*This*/ 0, ThisType,
345 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000346 /*Op*/ SourceLocation(),
347 Qualifier, SS.getRange(),
348 FirstQualifierInScope,
349 Name, NameLoc,
350 TemplateArgs));
351 }
352
353 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
354}
355
356Sema::OwningExprResult
357Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
358 DeclarationName Name,
359 SourceLocation NameLoc,
360 const TemplateArgumentListInfo *TemplateArgs) {
361 return Owned(DependentScopeDeclRefExpr::Create(Context,
362 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
363 SS.getRange(),
364 Name, NameLoc,
365 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000366}
367
Douglas Gregor5101c242008-12-05 18:15:24 +0000368/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
369/// that the template parameter 'PrevDecl' is being shadowed by a new
370/// declaration at location Loc. Returns true to indicate that this is
371/// an error, and false otherwise.
372bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000373 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000374
375 // Microsoft Visual C++ permits template parameters to be shadowed.
376 if (getLangOptions().Microsoft)
377 return false;
378
379 // C++ [temp.local]p4:
380 // A template-parameter shall not be redeclared within its
381 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000382 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000383 << cast<NamedDecl>(PrevDecl)->getDeclName();
384 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
385 return true;
386}
387
Douglas Gregor463421d2009-03-03 04:44:36 +0000388/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000389/// the parameter D to reference the templated declaration and return a pointer
390/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000391TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000392 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000393 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000394 return Temp;
395 }
396 return 0;
397}
398
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000399static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
400 const ParsedTemplateArgument &Arg) {
401
402 switch (Arg.getKind()) {
403 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000404 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000405 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
406 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000407 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000408 return TemplateArgumentLoc(TemplateArgument(T), DI);
409 }
410
411 case ParsedTemplateArgument::NonType: {
412 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
413 return TemplateArgumentLoc(TemplateArgument(E), E);
414 }
415
416 case ParsedTemplateArgument::Template: {
417 TemplateName Template
418 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
419 return TemplateArgumentLoc(TemplateArgument(Template),
420 Arg.getScopeSpec().getRange(),
421 Arg.getLocation());
422 }
423 }
424
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000425 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000426 return TemplateArgumentLoc();
427}
428
429/// \brief Translates template arguments as provided by the parser
430/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000431void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
432 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000433 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000434 TemplateArgs.addArgument(translateTemplateArgument(*this,
435 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000436}
437
Douglas Gregor5101c242008-12-05 18:15:24 +0000438/// ActOnTypeParameter - Called when a C++ template type parameter
439/// (e.g., "typename T") has been parsed. Typename specifies whether
440/// the keyword "typename" was used to declare the type parameter
441/// (otherwise, "class" was used), and KeyLoc is the location of the
442/// "class" or "typename" keyword. ParamName is the name of the
443/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000444/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000445/// If the type parameter has a default argument, it will be added
446/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000447Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000448 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000449 SourceLocation KeyLoc,
450 IdentifierInfo *ParamName,
451 SourceLocation ParamNameLoc,
452 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000453 assert(S->isTemplateParamScope() &&
454 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000455 bool Invalid = false;
456
457 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000458 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000459 LookupOrdinaryName,
460 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000461 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000462 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000463 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000464 }
465
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000466 SourceLocation Loc = ParamNameLoc;
467 if (!ParamName)
468 Loc = KeyLoc;
469
Douglas Gregor5101c242008-12-05 18:15:24 +0000470 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000471 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
472 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000473 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000474 if (Invalid)
475 Param->setInvalidDecl();
476
477 if (ParamName) {
478 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000479 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000480 IdResolver.AddDecl(Param);
481 }
482
Chris Lattner83f095c2009-03-28 19:18:32 +0000483 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000484}
485
Douglas Gregordba32632009-02-10 19:49:53 +0000486/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000487/// Default) to the given template type parameter (TypeParam).
488void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000489 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000490 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000491 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000492 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000493 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000494
John McCallbcd03502009-12-07 02:54:59 +0000495 TypeSourceInfo *DefaultTInfo;
496 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall0ad16662009-10-29 08:12:44 +0000497
John McCallbcd03502009-12-07 02:54:59 +0000498 assert(DefaultTInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000499
Anders Carlssond3824352009-06-12 22:30:13 +0000500 // C++0x [temp.param]p9:
501 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000502 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000503 if (Parm->isParameterPack()) {
504 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000505 return;
506 }
Mike Stump11289f42009-09-09 15:08:12 +0000507
Douglas Gregordba32632009-02-10 19:49:53 +0000508 // C++ [temp.param]p14:
509 // A template-parameter shall not be used in its own default argument.
510 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000511
Douglas Gregordba32632009-02-10 19:49:53 +0000512 // Check the template argument itself.
John McCallbcd03502009-12-07 02:54:59 +0000513 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000514 Parm->setInvalidDecl();
515 return;
516 }
517
John McCallbcd03502009-12-07 02:54:59 +0000518 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000519}
520
Douglas Gregor463421d2009-03-03 04:44:36 +0000521/// \brief Check that the type of a non-type template parameter is
522/// well-formed.
523///
524/// \returns the (possibly-promoted) parameter type if valid;
525/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000526QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000527Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
528 // C++ [temp.param]p4:
529 //
530 // A non-type template-parameter shall have one of the following
531 // (optionally cv-qualified) types:
532 //
533 // -- integral or enumeration type,
534 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000535 // -- pointer to object or pointer to function,
536 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000537 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
538 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000539 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000540 T->isReferenceType() ||
541 // -- pointer to member.
542 T->isMemberPointerType() ||
543 // If T is a dependent type, we can't do the check now, so we
544 // assume that it is well-formed.
545 T->isDependentType())
546 return T;
547 // C++ [temp.param]p8:
548 //
549 // A non-type template-parameter of type "array of T" or
550 // "function returning T" is adjusted to be of type "pointer to
551 // T" or "pointer to function returning T", respectively.
552 else if (T->isArrayType())
553 // FIXME: Keep the type prior to promotion?
554 return Context.getArrayDecayedType(T);
555 else if (T->isFunctionType())
556 // FIXME: Keep the type prior to promotion?
557 return Context.getPointerType(T);
558
559 Diag(Loc, diag::err_template_nontype_parm_bad_type)
560 << T;
561
562 return QualType();
563}
564
Douglas Gregor5101c242008-12-05 18:15:24 +0000565/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
566/// template parameter (e.g., "int Size" in "template<int Size>
567/// class Array") has been parsed. S is the current scope and D is
568/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000569Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000570 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000571 unsigned Position) {
John McCallbcd03502009-12-07 02:54:59 +0000572 TypeSourceInfo *TInfo = 0;
573 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000574
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000575 assert(S->isTemplateParamScope() &&
576 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000577 bool Invalid = false;
578
579 IdentifierInfo *ParamName = D.getIdentifier();
580 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000581 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000582 LookupOrdinaryName,
583 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000584 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000585 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000586 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000587 }
588
Douglas Gregor463421d2009-03-03 04:44:36 +0000589 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000590 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000591 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000592 Invalid = true;
593 }
Douglas Gregor81338792009-02-10 17:43:50 +0000594
Douglas Gregor5101c242008-12-05 18:15:24 +0000595 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000596 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
597 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000598 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000599 if (Invalid)
600 Param->setInvalidDecl();
601
602 if (D.getIdentifier()) {
603 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000604 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000605 IdResolver.AddDecl(Param);
606 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000607 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000608}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000609
Douglas Gregordba32632009-02-10 19:49:53 +0000610/// \brief Adds a default argument to the given non-type template
611/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000612void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000613 SourceLocation EqualLoc,
614 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000615 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000616 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000617 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000618
Douglas Gregordba32632009-02-10 19:49:53 +0000619 // C++ [temp.param]p14:
620 // A template-parameter shall not be used in its own default argument.
621 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000622
Douglas Gregordba32632009-02-10 19:49:53 +0000623 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000624 TemplateArgument Converted;
625 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
626 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000627 TemplateParm->setInvalidDecl();
628 return;
629 }
630
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000631 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000632}
633
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000634
635/// ActOnTemplateTemplateParameter - Called when a C++ template template
636/// parameter (e.g. T in template <template <typename> class T> class array)
637/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000638Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
639 SourceLocation TmpLoc,
640 TemplateParamsTy *Params,
641 IdentifierInfo *Name,
642 SourceLocation NameLoc,
643 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000644 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000645 assert(S->isTemplateParamScope() &&
646 "Template template parameter not in template parameter scope!");
647
648 // Construct the parameter object.
649 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000650 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
651 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000652 (TemplateParameterList*)Params);
653
654 // Make sure the parameter is valid.
655 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
656 // do anything yet. However, if the template parameter list or (eventual)
657 // default value is ever invalidated, that will propagate here.
658 bool Invalid = false;
659 if (Invalid) {
660 Param->setInvalidDecl();
661 }
662
663 // If the tt-param has a name, then link the identifier into the scope
664 // and lookup mechanisms.
665 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000666 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000667 IdResolver.AddDecl(Param);
668 }
669
Chris Lattner83f095c2009-03-28 19:18:32 +0000670 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000671}
672
Douglas Gregordba32632009-02-10 19:49:53 +0000673/// \brief Adds a default argument to the given template template
674/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000675void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000676 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000677 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000678 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000679 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000680
Douglas Gregordba32632009-02-10 19:49:53 +0000681 // C++ [temp.param]p14:
682 // A template-parameter shall not be used in its own default argument.
683 // FIXME: Implement this check! Needs a recursive walk over the types.
684
Douglas Gregore62e6a02009-11-11 19:13:48 +0000685 // Check only that we have a template template argument. We don't want to
686 // try to check well-formedness now, because our template template parameter
687 // might have dependent types in its template parameters, which we wouldn't
688 // be able to match now.
689 //
690 // If none of the template template parameter's template arguments mention
691 // other template parameters, we could actually perform more checking here.
692 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000693 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000694 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
695 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
696 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000697 return;
698 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000699
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000700 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000701}
702
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000703/// ActOnTemplateParameterList - Builds a TemplateParameterList that
704/// contains the template parameters in Params/NumParams.
705Sema::TemplateParamsTy *
706Sema::ActOnTemplateParameterList(unsigned Depth,
707 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000708 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000709 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000710 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000711 SourceLocation RAngleLoc) {
712 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000713 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000714
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000715 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000716 (NamedDecl**)Params, NumParams,
717 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000718}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000719
John McCall3e11ebe2010-03-15 10:12:16 +0000720static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
721 if (SS.isSet())
722 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
723 SS.getRange());
724}
725
Douglas Gregorc08f4892009-03-25 00:13:59 +0000726Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000727Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000728 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000729 IdentifierInfo *Name, SourceLocation NameLoc,
730 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000731 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000732 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000733 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000734 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000735 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000736 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000737
738 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000739 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000740 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000741
Abramo Bagnara6150c882010-05-11 21:36:43 +0000742 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
743 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000744
745 // There is no such thing as an unnamed class template.
746 if (!Name) {
747 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000748 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000749 }
750
751 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000752 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000753 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000754 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000755 if (SS.isNotEmpty() && !SS.isInvalid()) {
756 SemanticContext = computeDeclContext(SS, true);
757 if (!SemanticContext) {
758 // FIXME: Produce a reasonable diagnostic here
759 return true;
760 }
Mike Stump11289f42009-09-09 15:08:12 +0000761
John McCall0b66eb32010-05-01 00:40:08 +0000762 if (RequireCompleteDeclContext(SS, SemanticContext))
763 return true;
764
John McCall27b18f82009-11-17 02:14:36 +0000765 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000766 } else {
767 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000768 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000769 }
Mike Stump11289f42009-09-09 15:08:12 +0000770
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000771 if (Previous.isAmbiguous())
772 return true;
773
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000774 NamedDecl *PrevDecl = 0;
775 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000776 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000777
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000778 // If there is a previous declaration with the same name, check
779 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000780 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000781 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000782
783 // We may have found the injected-class-name of a class template,
784 // class template partial specialization, or class template specialization.
785 // In these cases, grab the template that is being defined or specialized.
786 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
787 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
788 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
789 PrevClassTemplate
790 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
791 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
792 PrevClassTemplate
793 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
794 ->getSpecializedTemplate();
795 }
796 }
797
John McCalld43784f2009-12-18 11:25:59 +0000798 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000799 // C++ [namespace.memdef]p3:
800 // [...] When looking for a prior declaration of a class or a function
801 // declared as a friend, and when the name of the friend class or
802 // function is neither a qualified name nor a template-id, scopes outside
803 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000804 if (!SS.isSet()) {
805 DeclContext *OutermostContext = CurContext;
806 while (!OutermostContext->isFileContext())
807 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000808
Douglas Gregorb74b1032010-04-18 17:37:40 +0000809 if (PrevDecl &&
810 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
811 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
812 SemanticContext = PrevDecl->getDeclContext();
813 } else {
814 // Declarations in outer scopes don't matter. However, the outermost
815 // context we computed is the semantic context for our new
816 // declaration.
817 PrevDecl = PrevClassTemplate = 0;
818 SemanticContext = OutermostContext;
819 }
John McCall90d3bb92009-12-17 23:21:11 +0000820 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000821
John McCall90d3bb92009-12-17 23:21:11 +0000822 if (CurContext->isDependentContext()) {
823 // If this is a dependent context, we don't want to link the friend
824 // class template to the template in scope, because that would perform
825 // checking of the template parameter lists that can't be performed
826 // until the outer context is instantiated.
827 PrevDecl = PrevClassTemplate = 0;
828 }
829 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
830 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000831
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000832 if (PrevClassTemplate) {
833 // Ensure that the template parameter lists are compatible.
834 if (!TemplateParameterListsAreEqual(TemplateParams,
835 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000836 /*Complain=*/true,
837 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000838 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000839
840 // C++ [temp.class]p4:
841 // In a redeclaration, partial specialization, explicit
842 // specialization or explicit instantiation of a class template,
843 // the class-key shall agree in kind with the original class
844 // template declaration (7.1.5.3).
845 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000846 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000847 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000848 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000849 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000850 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000851 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000852 }
853
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000854 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000855 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000856 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000857 Diag(NameLoc, diag::err_redefinition) << Name;
858 Diag(Def->getLocation(), diag::note_previous_definition);
859 // FIXME: Would it make sense to try to "forget" the previous
860 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000861 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000862 }
863 }
864 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
865 // Maybe we will complain about the shadowed template parameter.
866 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
867 // Just pretend that we didn't see the previous declaration.
868 PrevDecl = 0;
869 } else if (PrevDecl) {
870 // C++ [temp]p5:
871 // A class template shall not have the same name as any other
872 // template, class, function, object, enumeration, enumerator,
873 // namespace, or type in the same scope (3.3), except as specified
874 // in (14.5.4).
875 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
876 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000877 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000878 }
879
Douglas Gregordba32632009-02-10 19:49:53 +0000880 // Check the template parameter list of this declaration, possibly
881 // merging in the template parameter list from the previous class
882 // template declaration.
883 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000884 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
885 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000886 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000887
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000888 if (SS.isSet()) {
889 // If the name of the template was qualified, we must be defining the
890 // template out-of-line.
891 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
892 !(TUK == TUK_Friend && CurContext->isDependentContext()))
893 Diag(NameLoc, diag::err_member_def_does_not_match)
894 << Name << SemanticContext << SS.getRange();
895 }
896
Mike Stump11289f42009-09-09 15:08:12 +0000897 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000898 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000899 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000900 PrevClassTemplate->getTemplatedDecl() : 0,
901 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000902 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000903
904 ClassTemplateDecl *NewTemplate
905 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
906 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000907 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000908 NewClass->setDescribedClassTemplate(NewTemplate);
909
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000910 // Build the type for the class template declaration now.
John McCalle78aac42010-03-10 03:28:59 +0000911 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
912 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000913 assert(T->isDependentType() && "Class template type is not dependent?");
914 (void)T;
915
Douglas Gregorcf915552009-10-13 16:30:37 +0000916 // If we are providing an explicit specialization of a member that is a
917 // class template, make a note of that.
918 if (PrevClassTemplate &&
919 PrevClassTemplate->getInstantiatedFromMemberTemplate())
920 PrevClassTemplate->setMemberSpecialization();
921
Anders Carlsson137108d2009-03-26 01:24:28 +0000922 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000923 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000924 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000925
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000926 // Set the lexical context of these templates
927 NewClass->setLexicalDeclContext(CurContext);
928 NewTemplate->setLexicalDeclContext(CurContext);
929
John McCall9bb74a52009-07-31 02:45:11 +0000930 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000931 NewClass->startDefinition();
932
933 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000934 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000935
John McCall27b5c252009-09-14 21:59:20 +0000936 if (TUK != TUK_Friend)
937 PushOnScopeChains(NewTemplate, S);
938 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000939 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000940 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000941 NewClass->setAccess(PrevClassTemplate->getAccess());
942 }
John McCall27b5c252009-09-14 21:59:20 +0000943
Douglas Gregor3dad8422009-09-26 06:47:28 +0000944 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
945 PrevClassTemplate != NULL);
946
John McCall27b5c252009-09-14 21:59:20 +0000947 // Friend templates are visible in fairly strange ways.
948 if (!CurContext->isDependentContext()) {
949 DeclContext *DC = SemanticContext->getLookupContext();
950 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
951 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
952 PushOnScopeChains(NewTemplate, EnclosingScope,
953 /* AddToContext = */ false);
954 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000955
956 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
957 NewClass->getLocation(),
958 NewTemplate,
959 /*FIXME:*/NewClass->getLocation());
960 Friend->setAccess(AS_public);
961 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000962 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000963
Douglas Gregordba32632009-02-10 19:49:53 +0000964 if (Invalid) {
965 NewTemplate->setInvalidDecl();
966 NewClass->setInvalidDecl();
967 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000968 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000969}
970
Douglas Gregored5731f2009-11-25 17:50:39 +0000971/// \brief Diagnose the presence of a default template argument on a
972/// template parameter, which is ill-formed in certain contexts.
973///
974/// \returns true if the default template argument should be dropped.
975static bool DiagnoseDefaultTemplateArgument(Sema &S,
976 Sema::TemplateParamListContext TPC,
977 SourceLocation ParamLoc,
978 SourceRange DefArgRange) {
979 switch (TPC) {
980 case Sema::TPC_ClassTemplate:
981 return false;
982
983 case Sema::TPC_FunctionTemplate:
984 // C++ [temp.param]p9:
985 // A default template-argument shall not be specified in a
986 // function template declaration or a function template
987 // definition [...]
988 // (This sentence is not in C++0x, per DR226).
989 if (!S.getLangOptions().CPlusPlus0x)
990 S.Diag(ParamLoc,
991 diag::err_template_parameter_default_in_function_template)
992 << DefArgRange;
993 return false;
994
995 case Sema::TPC_ClassTemplateMember:
996 // C++0x [temp.param]p9:
997 // A default template-argument shall not be specified in the
998 // template-parameter-lists of the definition of a member of a
999 // class template that appears outside of the member's class.
1000 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1001 << DefArgRange;
1002 return true;
1003
1004 case Sema::TPC_FriendFunctionTemplate:
1005 // C++ [temp.param]p9:
1006 // A default template-argument shall not be specified in a
1007 // friend template declaration.
1008 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1009 << DefArgRange;
1010 return true;
1011
1012 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1013 // for friend function templates if there is only a single
1014 // declaration (and it is a definition). Strange!
1015 }
1016
1017 return false;
1018}
1019
Douglas Gregordba32632009-02-10 19:49:53 +00001020/// \brief Checks the validity of a template parameter list, possibly
1021/// considering the template parameter list from a previous
1022/// declaration.
1023///
1024/// If an "old" template parameter list is provided, it must be
1025/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1026/// template parameter list.
1027///
1028/// \param NewParams Template parameter list for a new template
1029/// declaration. This template parameter list will be updated with any
1030/// default arguments that are carried through from the previous
1031/// template parameter list.
1032///
1033/// \param OldParams If provided, template parameter list from a
1034/// previous declaration of the same template. Default template
1035/// arguments will be merged from the old template parameter list to
1036/// the new template parameter list.
1037///
Douglas Gregored5731f2009-11-25 17:50:39 +00001038/// \param TPC Describes the context in which we are checking the given
1039/// template parameter list.
1040///
Douglas Gregordba32632009-02-10 19:49:53 +00001041/// \returns true if an error occurred, false otherwise.
1042bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001043 TemplateParameterList *OldParams,
1044 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001045 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001046
Douglas Gregordba32632009-02-10 19:49:53 +00001047 // C++ [temp.param]p10:
1048 // The set of default template-arguments available for use with a
1049 // template declaration or definition is obtained by merging the
1050 // default arguments from the definition (if in scope) and all
1051 // declarations in scope in the same way default function
1052 // arguments are (8.3.6).
1053 bool SawDefaultArgument = false;
1054 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001055
Anders Carlsson327865d2009-06-12 23:20:15 +00001056 bool SawParameterPack = false;
1057 SourceLocation ParameterPackLoc;
1058
Mike Stumpc89c8e32009-02-11 23:03:27 +00001059 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001060 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001061 if (OldParams)
1062 OldParam = OldParams->begin();
1063
1064 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1065 NewParamEnd = NewParams->end();
1066 NewParam != NewParamEnd; ++NewParam) {
1067 // Variables used to diagnose redundant default arguments
1068 bool RedundantDefaultArg = false;
1069 SourceLocation OldDefaultLoc;
1070 SourceLocation NewDefaultLoc;
1071
1072 // Variables used to diagnose missing default arguments
1073 bool MissingDefaultArg = false;
1074
Anders Carlsson327865d2009-06-12 23:20:15 +00001075 // C++0x [temp.param]p11:
1076 // If a template parameter of a class template is a template parameter pack,
1077 // it must be the last template parameter.
1078 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001079 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001080 diag::err_template_param_pack_must_be_last_template_parameter);
1081 Invalid = true;
1082 }
1083
Douglas Gregordba32632009-02-10 19:49:53 +00001084 if (TemplateTypeParmDecl *NewTypeParm
1085 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001086 // Check the presence of a default argument here.
1087 if (NewTypeParm->hasDefaultArgument() &&
1088 DiagnoseDefaultTemplateArgument(*this, TPC,
1089 NewTypeParm->getLocation(),
1090 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1091 .getFullSourceRange()))
1092 NewTypeParm->removeDefaultArgument();
1093
1094 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001095 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001096 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001097
Anders Carlsson327865d2009-06-12 23:20:15 +00001098 if (NewTypeParm->isParameterPack()) {
1099 assert(!NewTypeParm->hasDefaultArgument() &&
1100 "Parameter packs can't have a default argument!");
1101 SawParameterPack = true;
1102 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001103 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001104 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001105 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1106 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1107 SawDefaultArgument = true;
1108 RedundantDefaultArg = true;
1109 PreviousDefaultArgLoc = NewDefaultLoc;
1110 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1111 // Merge the default argument from the old declaration to the
1112 // new declaration.
1113 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001114 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001115 true);
1116 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1117 } else if (NewTypeParm->hasDefaultArgument()) {
1118 SawDefaultArgument = true;
1119 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1120 } else if (SawDefaultArgument)
1121 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001122 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001123 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001124 // Check the presence of a default argument here.
1125 if (NewNonTypeParm->hasDefaultArgument() &&
1126 DiagnoseDefaultTemplateArgument(*this, TPC,
1127 NewNonTypeParm->getLocation(),
1128 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1129 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1130 NewNonTypeParm->setDefaultArgument(0);
1131 }
1132
Mike Stump12b8ce12009-08-04 21:02:39 +00001133 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001134 NonTypeTemplateParmDecl *OldNonTypeParm
1135 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001136 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001137 NewNonTypeParm->hasDefaultArgument()) {
1138 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1139 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1140 SawDefaultArgument = true;
1141 RedundantDefaultArg = true;
1142 PreviousDefaultArgLoc = NewDefaultLoc;
1143 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1144 // Merge the default argument from the old declaration to the
1145 // new declaration.
1146 SawDefaultArgument = true;
1147 // FIXME: We need to create a new kind of "default argument"
1148 // expression that points to a previous template template
1149 // parameter.
1150 NewNonTypeParm->setDefaultArgument(
1151 OldNonTypeParm->getDefaultArgument());
1152 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1153 } else if (NewNonTypeParm->hasDefaultArgument()) {
1154 SawDefaultArgument = true;
1155 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1156 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001157 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001158 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001159 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001160 TemplateTemplateParmDecl *NewTemplateParm
1161 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001162 if (NewTemplateParm->hasDefaultArgument() &&
1163 DiagnoseDefaultTemplateArgument(*this, TPC,
1164 NewTemplateParm->getLocation(),
1165 NewTemplateParm->getDefaultArgument().getSourceRange()))
1166 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1167
1168 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001169 TemplateTemplateParmDecl *OldTemplateParm
1170 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001171 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001172 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001173 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1174 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001175 SawDefaultArgument = true;
1176 RedundantDefaultArg = true;
1177 PreviousDefaultArgLoc = NewDefaultLoc;
1178 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1179 // Merge the default argument from the old declaration to the
1180 // new declaration.
1181 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001182 // FIXME: We need to create a new kind of "default argument" expression
1183 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001184 NewTemplateParm->setDefaultArgument(
1185 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001186 PreviousDefaultArgLoc
1187 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001188 } else if (NewTemplateParm->hasDefaultArgument()) {
1189 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001190 PreviousDefaultArgLoc
1191 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001192 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001193 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001194 }
1195
1196 if (RedundantDefaultArg) {
1197 // C++ [temp.param]p12:
1198 // A template-parameter shall not be given default arguments
1199 // by two different declarations in the same scope.
1200 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1201 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1202 Invalid = true;
1203 } else if (MissingDefaultArg) {
1204 // C++ [temp.param]p11:
1205 // If a template-parameter has a default template-argument,
1206 // all subsequent template-parameters shall have a default
1207 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001208 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001209 diag::err_template_param_default_arg_missing);
1210 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1211 Invalid = true;
1212 }
1213
1214 // If we have an old template parameter list that we're merging
1215 // in, move on to the next parameter.
1216 if (OldParams)
1217 ++OldParam;
1218 }
1219
1220 return Invalid;
1221}
Douglas Gregord32e0282009-02-09 23:23:08 +00001222
Mike Stump11289f42009-09-09 15:08:12 +00001223/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001224/// specifier, returning the template parameter list that applies to the
1225/// name.
1226///
1227/// \param DeclStartLoc the start of the declaration that has a scope
1228/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001229///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001230/// \param SS the scope specifier that will be matched to the given template
1231/// parameter lists. This scope specifier precedes a qualified name that is
1232/// being declared.
1233///
1234/// \param ParamLists the template parameter lists, from the outermost to the
1235/// innermost template parameter lists.
1236///
1237/// \param NumParamLists the number of template parameter lists in ParamLists.
1238///
John McCalle820e5e2010-04-13 20:37:33 +00001239/// \param IsFriend Whether to apply the slightly different rules for
1240/// matching template parameters to scope specifiers in friend
1241/// declarations.
1242///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001243/// \param IsExplicitSpecialization will be set true if the entity being
1244/// declared is an explicit specialization, false otherwise.
1245///
Mike Stump11289f42009-09-09 15:08:12 +00001246/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001247/// name that is preceded by the scope specifier @p SS. This template
1248/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001249/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001250/// template specialization), or may be NULL (if we were's declaring isn't
1251/// itself a template).
1252TemplateParameterList *
1253Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1254 const CXXScopeSpec &SS,
1255 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001256 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001257 bool IsFriend,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001258 bool &IsExplicitSpecialization) {
1259 IsExplicitSpecialization = false;
1260
Douglas Gregord8d297c2009-07-21 23:53:31 +00001261 // Find the template-ids that occur within the nested-name-specifier. These
1262 // template-ids will match up with the template parameter lists.
1263 llvm::SmallVector<const TemplateSpecializationType *, 4>
1264 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001265 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1266 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001267 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1268 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001269 const Type *T = NNS->getAsType();
1270 if (!T) break;
1271
1272 // C++0x [temp.expl.spec]p17:
1273 // A member or a member template may be nested within many
1274 // enclosing class templates. In an explicit specialization for
1275 // such a member, the member declaration shall be preceded by a
1276 // template<> for each enclosing class template that is
1277 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001278 //
1279 // Following the existing practice of GNU and EDG, we allow a typedef of a
1280 // template specialization type.
1281 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1282 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001283
Mike Stump11289f42009-09-09 15:08:12 +00001284 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001285 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001286 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1287 if (!Template)
1288 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001289
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001290 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001291 ClassTemplateSpecializationDecl *SpecDecl
1292 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1293 // If the nested name specifier refers to an explicit specialization,
1294 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001295 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1296 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001297 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001298 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001299 }
Mike Stump11289f42009-09-09 15:08:12 +00001300
Douglas Gregord8d297c2009-07-21 23:53:31 +00001301 TemplateIdsInSpecifier.push_back(SpecType);
1302 }
1303 }
Mike Stump11289f42009-09-09 15:08:12 +00001304
Douglas Gregord8d297c2009-07-21 23:53:31 +00001305 // Reverse the list of template-ids in the scope specifier, so that we can
1306 // more easily match up the template-ids and the template parameter lists.
1307 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001308
Douglas Gregord8d297c2009-07-21 23:53:31 +00001309 SourceLocation FirstTemplateLoc = DeclStartLoc;
1310 if (NumParamLists)
1311 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001312
Douglas Gregord8d297c2009-07-21 23:53:31 +00001313 // Match the template-ids found in the specifier to the template parameter
1314 // lists.
1315 unsigned Idx = 0;
1316 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1317 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001318 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1319 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001320 if (Idx >= NumParamLists) {
1321 // We have a template-id without a corresponding template parameter
1322 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001323
1324 // ...which is fine if this is a friend declaration.
1325 if (IsFriend) {
1326 IsExplicitSpecialization = true;
1327 break;
1328 }
1329
Douglas Gregord8d297c2009-07-21 23:53:31 +00001330 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001331 // FIXME: the location information here isn't great.
1332 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001333 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001334 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001335 << SS.getRange();
1336 } else {
1337 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1338 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001339 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001340 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001341 }
1342 return 0;
1343 }
Mike Stump11289f42009-09-09 15:08:12 +00001344
Douglas Gregord8d297c2009-07-21 23:53:31 +00001345 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001346 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001347 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001348
John McCall2408e322010-04-27 00:57:59 +00001349 // Are there cases in (e.g.) friends where this won't match?
1350 if (const InjectedClassNameType *Injected
1351 = TemplateId->getAs<InjectedClassNameType>()) {
1352 CXXRecordDecl *Record = Injected->getDecl();
1353 if (ClassTemplatePartialSpecializationDecl *Partial =
1354 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1355 ExpectedTemplateParams = Partial->getTemplateParameters();
1356 else
1357 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1358 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001359 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001360
John McCall2408e322010-04-27 00:57:59 +00001361 if (ExpectedTemplateParams)
1362 TemplateParameterListsAreEqual(ParamLists[Idx],
1363 ExpectedTemplateParams,
1364 true, TPL_TemplateMatch);
1365
Douglas Gregored5731f2009-11-25 17:50:39 +00001366 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001367 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001368 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001369 diag::err_template_param_list_matches_nontemplate)
1370 << TemplateId
1371 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001372 else
1373 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001374 }
Mike Stump11289f42009-09-09 15:08:12 +00001375
Douglas Gregord8d297c2009-07-21 23:53:31 +00001376 // If there were at least as many template-ids as there were template
1377 // parameter lists, then there are no template parameter lists remaining for
1378 // the declaration itself.
1379 if (Idx >= NumParamLists)
1380 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001381
Douglas Gregord8d297c2009-07-21 23:53:31 +00001382 // If there were too many template parameter lists, complain about that now.
1383 if (Idx != NumParamLists - 1) {
1384 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001385 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001386 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001387 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1388 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001389 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1390 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001391
1392 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1393 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1394 diag::note_explicit_template_spec_does_not_need_header)
1395 << ExplicitSpecializationsInSpecifier.back();
1396 ExplicitSpecializationsInSpecifier.pop_back();
1397 }
1398
Douglas Gregord8d297c2009-07-21 23:53:31 +00001399 ++Idx;
1400 }
1401 }
Mike Stump11289f42009-09-09 15:08:12 +00001402
Douglas Gregord8d297c2009-07-21 23:53:31 +00001403 // Return the last template parameter list, which corresponds to the
1404 // entity being declared.
1405 return ParamLists[NumParamLists - 1];
1406}
1407
Douglas Gregordc572a32009-03-30 22:58:21 +00001408QualType Sema::CheckTemplateIdType(TemplateName Name,
1409 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001410 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001411 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001412 if (!Template) {
1413 // The template name does not resolve to a template, so we just
1414 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001415 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001416 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001417
Douglas Gregorc40290e2009-03-09 23:48:35 +00001418 // Check that the template argument list is well-formed for this
1419 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001420 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001421 TemplateArgs.size());
1422 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001423 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001424 return QualType();
1425
Mike Stump11289f42009-09-09 15:08:12 +00001426 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001427 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001428 "Converted template argument list is too short!");
1429
1430 QualType CanonType;
John McCall2408e322010-04-27 00:57:59 +00001431 bool IsCurrentInstantiation = false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001432
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001433 if (Name.isDependent() ||
1434 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001435 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001436 // This class template specialization is a dependent
1437 // type. Therefore, its canonical type is another class template
1438 // specialization type that contains all of the converted
1439 // arguments in canonical form. This ensures that, e.g., A<T> and
1440 // A<T, T> have identical types when A is declared as:
1441 //
1442 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001443 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001444 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001445 Converted.getFlatArguments(),
1446 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001447
Douglas Gregora8e02e72009-07-28 23:00:59 +00001448 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001449 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001450 // In the future, we need to teach getTemplateSpecializationType to only
1451 // build the canonical type and return that to us.
1452 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001453
1454 // This might work out to be a current instantiation, in which
1455 // case the canonical type needs to be the InjectedClassNameType.
1456 //
1457 // TODO: in theory this could be a simple hashtable lookup; most
1458 // changes to CurContext don't change the set of current
1459 // instantiations.
1460 if (isa<ClassTemplateDecl>(Template)) {
1461 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1462 // If we get out to a namespace, we're done.
1463 if (Ctx->isFileContext()) break;
1464
1465 // If this isn't a record, keep looking.
1466 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1467 if (!Record) continue;
1468
1469 // Look for one of the two cases with InjectedClassNameTypes
1470 // and check whether it's the same template.
1471 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1472 !Record->getDescribedClassTemplate())
1473 continue;
1474
1475 // Fetch the injected class name type and check whether its
1476 // injected type is equal to the type we just built.
1477 QualType ICNT = Context.getTypeDeclType(Record);
1478 QualType Injected = cast<InjectedClassNameType>(ICNT)
1479 ->getInjectedSpecializationType();
1480
1481 if (CanonType != Injected->getCanonicalTypeInternal())
1482 continue;
1483
1484 // If so, the canonical type of this TST is the injected
1485 // class name type of the record we just found.
1486 assert(ICNT.isCanonical());
1487 CanonType = ICNT;
1488 IsCurrentInstantiation = true;
1489 break;
1490 }
1491 }
Mike Stump11289f42009-09-09 15:08:12 +00001492 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001493 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001494 // Find the class template specialization declaration that
1495 // corresponds to these arguments.
1496 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001497 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001498 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001499 Converted.flatSize(),
1500 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001501 void *InsertPos = 0;
1502 ClassTemplateSpecializationDecl *Decl
1503 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1504 if (!Decl) {
1505 // This is the first time we have referenced this class template
1506 // specialization. Create the canonical declaration and add it to
1507 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001508 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001509 ClassTemplate->getTemplatedDecl()->getTagKind(),
1510 ClassTemplate->getDeclContext(),
1511 ClassTemplate->getLocation(),
1512 ClassTemplate,
1513 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001514 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1515 Decl->setLexicalDeclContext(CurContext);
1516 }
1517
1518 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001519 assert(isa<RecordType>(CanonType) &&
1520 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001521 }
Mike Stump11289f42009-09-09 15:08:12 +00001522
Douglas Gregorc40290e2009-03-09 23:48:35 +00001523 // Build the fully-sugared type for this class template
1524 // specialization, which refers back to the class template
1525 // specialization we created or found.
John McCall2408e322010-04-27 00:57:59 +00001526 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType,
1527 IsCurrentInstantiation);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001528}
1529
Douglas Gregor67a65642009-02-17 23:15:12 +00001530Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001531Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001532 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001533 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001534 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001535 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001536
Douglas Gregorc40290e2009-03-09 23:48:35 +00001537 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001538 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001539 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001540
John McCall6b51f282009-11-23 01:53:49 +00001541 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001542 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001543
1544 if (Result.isNull())
1545 return true;
1546
John McCallbcd03502009-12-07 02:54:59 +00001547 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001548 TemplateSpecializationTypeLoc TL
1549 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1550 TL.setTemplateNameLoc(TemplateLoc);
1551 TL.setLAngleLoc(LAngleLoc);
1552 TL.setRAngleLoc(RAngleLoc);
1553 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1554 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1555
1556 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001557}
John McCall06f6fe8d2009-09-04 01:14:41 +00001558
John McCalld8fe9af2009-09-08 17:47:29 +00001559Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1560 TagUseKind TUK,
1561 DeclSpec::TST TagSpec,
1562 SourceLocation TagLoc) {
1563 if (TypeResult.isInvalid())
1564 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001565
John McCall0ad16662009-10-29 08:12:44 +00001566 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001567 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001568 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001569
John McCalld8fe9af2009-09-08 17:47:29 +00001570 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001571 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001572
John McCalld8fe9af2009-09-08 17:47:29 +00001573 if (const RecordType *RT = Type->getAs<RecordType>()) {
1574 RecordDecl *D = RT->getDecl();
1575
1576 IdentifierInfo *Id = D->getIdentifier();
1577 assert(Id && "templated class must have an identifier");
1578
1579 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1580 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001581 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001582 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001583 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001584 }
1585 }
1586
Abramo Bagnara6150c882010-05-11 21:36:43 +00001587 ElaboratedTypeKeyword Keyword
1588 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1589 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001590
1591 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001592}
1593
John McCalle66edc12009-11-24 19:00:30 +00001594Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1595 LookupResult &R,
1596 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001597 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001598 // FIXME: Can we do any checking at this point? I guess we could check the
1599 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001600 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001601 // though.
John McCalle66edc12009-11-24 19:00:30 +00001602
1603 // These should be filtered out by our callers.
1604 assert(!R.empty() && "empty lookup results when building templateid");
1605 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1606
1607 NestedNameSpecifier *Qualifier = 0;
1608 SourceRange QualifierRange;
1609 if (SS.isSet()) {
1610 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1611 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001612 }
John McCall58cc69d2010-01-27 01:50:18 +00001613
1614 // We don't want lookup warnings at this point.
1615 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001616
John McCalle66edc12009-11-24 19:00:30 +00001617 bool Dependent
1618 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1619 &TemplateArgs);
1620 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001621 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001622 Qualifier, QualifierRange,
1623 R.getLookupName(), R.getNameLoc(),
1624 RequiresADL, TemplateArgs);
John McCall58cc69d2010-01-27 01:50:18 +00001625 ULE->addDecls(R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001626
1627 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001628}
1629
John McCalle66edc12009-11-24 19:00:30 +00001630// We actually only call this from template instantiation.
1631Sema::OwningExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001632Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001633 DeclarationName Name,
1634 SourceLocation NameLoc,
1635 const TemplateArgumentListInfo &TemplateArgs) {
1636 DeclContext *DC;
1637 if (!(DC = computeDeclContext(SS, false)) ||
1638 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001639 RequireCompleteDeclContext(SS, DC))
John McCalle66edc12009-11-24 19:00:30 +00001640 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001641
John McCalle66edc12009-11-24 19:00:30 +00001642 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1643 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00001644
John McCalle66edc12009-11-24 19:00:30 +00001645 if (R.isAmbiguous())
1646 return ExprError();
1647
1648 if (R.empty()) {
1649 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1650 << Name << SS.getRange();
1651 return ExprError();
1652 }
1653
1654 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1655 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1656 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1657 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1658 return ExprError();
1659 }
1660
1661 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001662}
1663
Douglas Gregorb67535d2009-03-31 00:43:58 +00001664/// \brief Form a dependent template name.
1665///
1666/// This action forms a dependent template name given the template
1667/// name and its (presumably dependent) scope specifier. For
1668/// example, given "MetaFun::template apply", the scope specifier \p
1669/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1670/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001671Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001672Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001673 CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001674 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001675 TypeTy *ObjectType,
1676 bool EnteringContext) {
Douglas Gregor9abe2372010-01-19 16:01:07 +00001677 DeclContext *LookupCtx = 0;
1678 if (SS.isSet())
1679 LookupCtx = computeDeclContext(SS, EnteringContext);
1680 if (!LookupCtx && ObjectType)
1681 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1682 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001683 // C++0x [temp.names]p5:
1684 // If a name prefixed by the keyword template is not the name of
1685 // a template, the program is ill-formed. [Note: the keyword
1686 // template may not be applied to non-template members of class
1687 // templates. -end note ] [ Note: as is the case with the
1688 // typename prefix, the template prefix is allowed in cases
1689 // where it is not strictly necessary; i.e., when the
1690 // nested-name-specifier or the expression on the left of the ->
1691 // or . is not dependent on a template-parameter, or the use
1692 // does not appear in the scope of a template. -end note]
1693 //
1694 // Note: C++03 was more strict here, because it banned the use of
1695 // the "template" keyword prior to a template-name that was not a
1696 // dependent name. C++ DR468 relaxed this requirement (the
1697 // "template" keyword is now permitted). We follow the C++0x
1698 // rules, even in C++03 mode, retroactively applying the DR.
1699 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001700 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001701 EnteringContext, Template);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001702 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1703 isa<CXXRecordDecl>(LookupCtx) &&
1704 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00001705 // This is a dependent template.
1706 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001707 Diag(Name.getSourceRange().getBegin(),
1708 diag::err_template_kw_refers_to_non_template)
1709 << GetNameFromUnqualifiedId(Name)
Douglas Gregorb22ee882010-05-05 05:58:24 +00001710 << Name.getSourceRange()
1711 << TemplateKWLoc;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001712 return TemplateTy();
Douglas Gregord2e6a452010-01-14 17:47:39 +00001713 } else {
1714 // We found something; return it.
1715 return Template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001716 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001717 }
1718
Mike Stump11289f42009-09-09 15:08:12 +00001719 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001720 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001721
1722 switch (Name.getKind()) {
1723 case UnqualifiedId::IK_Identifier:
1724 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1725 Name.Identifier));
1726
Douglas Gregor71395fa2009-11-04 00:56:37 +00001727 case UnqualifiedId::IK_OperatorFunctionId:
1728 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1729 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001730
1731 case UnqualifiedId::IK_LiteralOperatorId:
1732 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1733
Douglas Gregor3cf81312009-11-03 23:16:33 +00001734 default:
1735 break;
1736 }
1737
1738 Diag(Name.getSourceRange().getBegin(),
1739 diag::err_template_kw_refers_to_non_template)
1740 << GetNameFromUnqualifiedId(Name)
Douglas Gregorb22ee882010-05-05 05:58:24 +00001741 << Name.getSourceRange()
1742 << TemplateKWLoc;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001743 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001744}
1745
Mike Stump11289f42009-09-09 15:08:12 +00001746bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001747 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001748 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001749 const TemplateArgument &Arg = AL.getArgument();
1750
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001751 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001752 switch(Arg.getKind()) {
1753 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001754 // C++ [temp.arg.type]p1:
1755 // A template-argument for a template-parameter which is a
1756 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001757 break;
1758 case TemplateArgument::Template: {
1759 // We have a template type parameter but the template argument
1760 // is a template without any arguments.
1761 SourceRange SR = AL.getSourceRange();
1762 TemplateName Name = Arg.getAsTemplate();
1763 Diag(SR.getBegin(), diag::err_template_missing_args)
1764 << Name << SR;
1765 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1766 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001767
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001768 return true;
1769 }
1770 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001771 // We have a template type parameter but the template argument
1772 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001773 SourceRange SR = AL.getSourceRange();
1774 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001775 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001776
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001777 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001778 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001779 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001780
John McCallbcd03502009-12-07 02:54:59 +00001781 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001782 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001783
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001784 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001785 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001786 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001787 return false;
1788}
1789
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001790/// \brief Substitute template arguments into the default template argument for
1791/// the given template type parameter.
1792///
1793/// \param SemaRef the semantic analysis object for which we are performing
1794/// the substitution.
1795///
1796/// \param Template the template that we are synthesizing template arguments
1797/// for.
1798///
1799/// \param TemplateLoc the location of the template name that started the
1800/// template-id we are checking.
1801///
1802/// \param RAngleLoc the location of the right angle bracket ('>') that
1803/// terminates the template-id.
1804///
1805/// \param Param the template template parameter whose default we are
1806/// substituting into.
1807///
1808/// \param Converted the list of template arguments provided for template
1809/// parameters that precede \p Param in the template parameter list.
1810///
1811/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001812static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001813SubstDefaultTemplateArgument(Sema &SemaRef,
1814 TemplateDecl *Template,
1815 SourceLocation TemplateLoc,
1816 SourceLocation RAngleLoc,
1817 TemplateTypeParmDecl *Param,
1818 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001819 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001820
1821 // If the argument type is dependent, instantiate it now based
1822 // on the previously-computed template arguments.
1823 if (ArgType->getType()->isDependentType()) {
1824 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1825 /*TakeArgs=*/false);
1826
1827 MultiLevelTemplateArgumentList AllTemplateArgs
1828 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1829
1830 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1831 Template, Converted.getFlatArguments(),
1832 Converted.flatSize(),
1833 SourceRange(TemplateLoc, RAngleLoc));
1834
1835 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1836 Param->getDefaultArgumentLoc(),
1837 Param->getDeclName());
1838 }
1839
1840 return ArgType;
1841}
1842
1843/// \brief Substitute template arguments into the default template argument for
1844/// the given non-type template parameter.
1845///
1846/// \param SemaRef the semantic analysis object for which we are performing
1847/// the substitution.
1848///
1849/// \param Template the template that we are synthesizing template arguments
1850/// for.
1851///
1852/// \param TemplateLoc the location of the template name that started the
1853/// template-id we are checking.
1854///
1855/// \param RAngleLoc the location of the right angle bracket ('>') that
1856/// terminates the template-id.
1857///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001858/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001859/// substituting into.
1860///
1861/// \param Converted the list of template arguments provided for template
1862/// parameters that precede \p Param in the template parameter list.
1863///
1864/// \returns the substituted template argument, or NULL if an error occurred.
1865static Sema::OwningExprResult
1866SubstDefaultTemplateArgument(Sema &SemaRef,
1867 TemplateDecl *Template,
1868 SourceLocation TemplateLoc,
1869 SourceLocation RAngleLoc,
1870 NonTypeTemplateParmDecl *Param,
1871 TemplateArgumentListBuilder &Converted) {
1872 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1873 /*TakeArgs=*/false);
1874
1875 MultiLevelTemplateArgumentList AllTemplateArgs
1876 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1877
1878 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1879 Template, Converted.getFlatArguments(),
1880 Converted.flatSize(),
1881 SourceRange(TemplateLoc, RAngleLoc));
1882
1883 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1884}
1885
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001886/// \brief Substitute template arguments into the default template argument for
1887/// the given template template parameter.
1888///
1889/// \param SemaRef the semantic analysis object for which we are performing
1890/// the substitution.
1891///
1892/// \param Template the template that we are synthesizing template arguments
1893/// for.
1894///
1895/// \param TemplateLoc the location of the template name that started the
1896/// template-id we are checking.
1897///
1898/// \param RAngleLoc the location of the right angle bracket ('>') that
1899/// terminates the template-id.
1900///
1901/// \param Param the template template parameter whose default we are
1902/// substituting into.
1903///
1904/// \param Converted the list of template arguments provided for template
1905/// parameters that precede \p Param in the template parameter list.
1906///
1907/// \returns the substituted template argument, or NULL if an error occurred.
1908static TemplateName
1909SubstDefaultTemplateArgument(Sema &SemaRef,
1910 TemplateDecl *Template,
1911 SourceLocation TemplateLoc,
1912 SourceLocation RAngleLoc,
1913 TemplateTemplateParmDecl *Param,
1914 TemplateArgumentListBuilder &Converted) {
1915 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1916 /*TakeArgs=*/false);
1917
1918 MultiLevelTemplateArgumentList AllTemplateArgs
1919 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1920
1921 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1922 Template, Converted.getFlatArguments(),
1923 Converted.flatSize(),
1924 SourceRange(TemplateLoc, RAngleLoc));
1925
1926 return SemaRef.SubstTemplateName(
1927 Param->getDefaultArgument().getArgument().getAsTemplate(),
1928 Param->getDefaultArgument().getTemplateNameLoc(),
1929 AllTemplateArgs);
1930}
1931
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001932/// \brief If the given template parameter has a default template
1933/// argument, substitute into that default template argument and
1934/// return the corresponding template argument.
1935TemplateArgumentLoc
1936Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1937 SourceLocation TemplateLoc,
1938 SourceLocation RAngleLoc,
1939 Decl *Param,
1940 TemplateArgumentListBuilder &Converted) {
1941 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1942 if (!TypeParm->hasDefaultArgument())
1943 return TemplateArgumentLoc();
1944
John McCallbcd03502009-12-07 02:54:59 +00001945 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001946 TemplateLoc,
1947 RAngleLoc,
1948 TypeParm,
1949 Converted);
1950 if (DI)
1951 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1952
1953 return TemplateArgumentLoc();
1954 }
1955
1956 if (NonTypeTemplateParmDecl *NonTypeParm
1957 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1958 if (!NonTypeParm->hasDefaultArgument())
1959 return TemplateArgumentLoc();
1960
1961 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1962 TemplateLoc,
1963 RAngleLoc,
1964 NonTypeParm,
1965 Converted);
1966 if (Arg.isInvalid())
1967 return TemplateArgumentLoc();
1968
1969 Expr *ArgE = Arg.takeAs<Expr>();
1970 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1971 }
1972
1973 TemplateTemplateParmDecl *TempTempParm
1974 = cast<TemplateTemplateParmDecl>(Param);
1975 if (!TempTempParm->hasDefaultArgument())
1976 return TemplateArgumentLoc();
1977
1978 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1979 TemplateLoc,
1980 RAngleLoc,
1981 TempTempParm,
1982 Converted);
1983 if (TName.isNull())
1984 return TemplateArgumentLoc();
1985
1986 return TemplateArgumentLoc(TemplateArgument(TName),
1987 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1988 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1989}
1990
Douglas Gregorda0fb532009-11-11 19:31:23 +00001991/// \brief Check that the given template argument corresponds to the given
1992/// template parameter.
1993bool Sema::CheckTemplateArgument(NamedDecl *Param,
1994 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001995 TemplateDecl *Template,
1996 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001997 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001998 TemplateArgumentListBuilder &Converted,
1999 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00002000 // Check template type parameters.
2001 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002002 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002003
Douglas Gregoreebed722009-11-11 19:41:09 +00002004 // Check non-type template parameters.
2005 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002006 // Do substitution on the type of the non-type template parameter
2007 // with the template arguments we've seen thus far.
2008 QualType NTTPType = NTTP->getType();
2009 if (NTTPType->isDependentType()) {
2010 // Do substitution on the type of the non-type template parameter.
2011 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2012 NTTP, Converted.getFlatArguments(),
2013 Converted.flatSize(),
2014 SourceRange(TemplateLoc, RAngleLoc));
2015
2016 TemplateArgumentList TemplateArgs(Context, Converted,
2017 /*TakeArgs=*/false);
2018 NTTPType = SubstType(NTTPType,
2019 MultiLevelTemplateArgumentList(TemplateArgs),
2020 NTTP->getLocation(),
2021 NTTP->getDeclName());
2022 // If that worked, check the non-type template parameter type
2023 // for validity.
2024 if (!NTTPType.isNull())
2025 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2026 NTTP->getLocation());
2027 if (NTTPType.isNull())
2028 return true;
2029 }
2030
2031 switch (Arg.getArgument().getKind()) {
2032 case TemplateArgument::Null:
2033 assert(false && "Should never see a NULL template argument here");
2034 return true;
2035
2036 case TemplateArgument::Expression: {
2037 Expr *E = Arg.getArgument().getAsExpr();
2038 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002039 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002040 return true;
2041
2042 Converted.Append(Result);
2043 break;
2044 }
2045
2046 case TemplateArgument::Declaration:
2047 case TemplateArgument::Integral:
2048 // We've already checked this template argument, so just copy
2049 // it to the list of converted arguments.
2050 Converted.Append(Arg.getArgument());
2051 break;
2052
2053 case TemplateArgument::Template:
2054 // We were given a template template argument. It may not be ill-formed;
2055 // see below.
2056 if (DependentTemplateName *DTN
2057 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2058 // We have a template argument such as \c T::template X, which we
2059 // parsed as a template template argument. However, since we now
2060 // know that we need a non-type template argument, convert this
2061 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00002062 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2063 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002064 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00002065 DTN->getIdentifier(),
2066 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002067
2068 TemplateArgument Result;
2069 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2070 return true;
2071
2072 Converted.Append(Result);
2073 break;
2074 }
2075
2076 // We have a template argument that actually does refer to a class
2077 // template, template alias, or template template parameter, and
2078 // therefore cannot be a non-type template argument.
2079 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2080 << Arg.getSourceRange();
2081
2082 Diag(Param->getLocation(), diag::note_template_param_here);
2083 return true;
2084
2085 case TemplateArgument::Type: {
2086 // We have a non-type template parameter but the template
2087 // argument is a type.
2088
2089 // C++ [temp.arg]p2:
2090 // In a template-argument, an ambiguity between a type-id and
2091 // an expression is resolved to a type-id, regardless of the
2092 // form of the corresponding template-parameter.
2093 //
2094 // We warn specifically about this case, since it can be rather
2095 // confusing for users.
2096 QualType T = Arg.getArgument().getAsType();
2097 SourceRange SR = Arg.getSourceRange();
2098 if (T->isFunctionType())
2099 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2100 else
2101 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2102 Diag(Param->getLocation(), diag::note_template_param_here);
2103 return true;
2104 }
2105
2106 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002107 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002108 break;
2109 }
2110
2111 return false;
2112 }
2113
2114
2115 // Check template template parameters.
2116 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2117
2118 // Substitute into the template parameter list of the template
2119 // template parameter, since previously-supplied template arguments
2120 // may appear within the template template parameter.
2121 {
2122 // Set up a template instantiation context.
2123 LocalInstantiationScope Scope(*this);
2124 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2125 TempParm, Converted.getFlatArguments(),
2126 Converted.flatSize(),
2127 SourceRange(TemplateLoc, RAngleLoc));
2128
2129 TemplateArgumentList TemplateArgs(Context, Converted,
2130 /*TakeArgs=*/false);
2131 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2132 SubstDecl(TempParm, CurContext,
2133 MultiLevelTemplateArgumentList(TemplateArgs)));
2134 if (!TempParm)
2135 return true;
2136
2137 // FIXME: TempParam is leaked.
2138 }
2139
2140 switch (Arg.getArgument().getKind()) {
2141 case TemplateArgument::Null:
2142 assert(false && "Should never see a NULL template argument here");
2143 return true;
2144
2145 case TemplateArgument::Template:
2146 if (CheckTemplateArgument(TempParm, Arg))
2147 return true;
2148
2149 Converted.Append(Arg.getArgument());
2150 break;
2151
2152 case TemplateArgument::Expression:
2153 case TemplateArgument::Type:
2154 // We have a template template parameter but the template
2155 // argument does not refer to a template.
2156 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2157 return true;
2158
2159 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002160 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002161 "Declaration argument with template template parameter");
2162 break;
2163 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002164 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002165 "Integral argument with template template parameter");
2166 break;
2167
2168 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002169 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002170 break;
2171 }
2172
2173 return false;
2174}
2175
Douglas Gregord32e0282009-02-09 23:23:08 +00002176/// \brief Check that the given template argument list is well-formed
2177/// for specializing the given template.
2178bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2179 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002180 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002181 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002182 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002183 TemplateParameterList *Params = Template->getTemplateParameters();
2184 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002185 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002186 bool Invalid = false;
2187
John McCall6b51f282009-11-23 01:53:49 +00002188 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2189
Mike Stump11289f42009-09-09 15:08:12 +00002190 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002191 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002192
Anders Carlsson15201f12009-06-13 02:08:00 +00002193 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002194 (NumArgs < Params->getMinRequiredArguments() &&
2195 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002196 // FIXME: point at either the first arg beyond what we can handle,
2197 // or the '>', depending on whether we have too many or too few
2198 // arguments.
2199 SourceRange Range;
2200 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002201 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002202 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2203 << (NumArgs > NumParams)
2204 << (isa<ClassTemplateDecl>(Template)? 0 :
2205 isa<FunctionTemplateDecl>(Template)? 1 :
2206 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2207 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002208 Diag(Template->getLocation(), diag::note_template_decl_here)
2209 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002210 Invalid = true;
2211 }
Mike Stump11289f42009-09-09 15:08:12 +00002212
2213 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002214 // [...] The type and form of each template-argument specified in
2215 // a template-id shall match the type and form specified for the
2216 // corresponding parameter declared by the template in its
2217 // template-parameter-list.
2218 unsigned ArgIdx = 0;
2219 for (TemplateParameterList::iterator Param = Params->begin(),
2220 ParamEnd = Params->end();
2221 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002222 if (ArgIdx > NumArgs && PartialTemplateArgs)
2223 break;
Mike Stump11289f42009-09-09 15:08:12 +00002224
Douglas Gregoreebed722009-11-11 19:41:09 +00002225 // If we have a template parameter pack, check every remaining template
2226 // argument against that template parameter pack.
2227 if ((*Param)->isTemplateParameterPack()) {
2228 Converted.BeginPack();
2229 for (; ArgIdx < NumArgs; ++ArgIdx) {
2230 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2231 TemplateLoc, RAngleLoc, Converted)) {
2232 Invalid = true;
2233 break;
2234 }
2235 }
2236 Converted.EndPack();
2237 continue;
2238 }
2239
Douglas Gregor84d49a22009-11-11 21:54:23 +00002240 if (ArgIdx < NumArgs) {
2241 // Check the template argument we were given.
2242 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2243 TemplateLoc, RAngleLoc, Converted))
2244 return true;
2245
2246 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002247 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002248
Douglas Gregor84d49a22009-11-11 21:54:23 +00002249 // We have a default template argument that we will use.
2250 TemplateArgumentLoc Arg;
2251
2252 // Retrieve the default template argument from the template
2253 // parameter. For each kind of template parameter, we substitute the
2254 // template arguments provided thus far and any "outer" template arguments
2255 // (when the template parameter was part of a nested template) into
2256 // the default argument.
2257 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2258 if (!TTP->hasDefaultArgument()) {
2259 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2260 break;
2261 }
2262
John McCallbcd03502009-12-07 02:54:59 +00002263 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002264 Template,
2265 TemplateLoc,
2266 RAngleLoc,
2267 TTP,
2268 Converted);
2269 if (!ArgType)
2270 return true;
2271
2272 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2273 ArgType);
2274 } else if (NonTypeTemplateParmDecl *NTTP
2275 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2276 if (!NTTP->hasDefaultArgument()) {
2277 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2278 break;
2279 }
2280
2281 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2282 TemplateLoc,
2283 RAngleLoc,
2284 NTTP,
2285 Converted);
2286 if (E.isInvalid())
2287 return true;
2288
2289 Expr *Ex = E.takeAs<Expr>();
2290 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2291 } else {
2292 TemplateTemplateParmDecl *TempParm
2293 = cast<TemplateTemplateParmDecl>(*Param);
2294
2295 if (!TempParm->hasDefaultArgument()) {
2296 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2297 break;
2298 }
2299
2300 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2301 TemplateLoc,
2302 RAngleLoc,
2303 TempParm,
2304 Converted);
2305 if (Name.isNull())
2306 return true;
2307
2308 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2309 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2310 TempParm->getDefaultArgument().getTemplateNameLoc());
2311 }
2312
2313 // Introduce an instantiation record that describes where we are using
2314 // the default template argument.
2315 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2316 Converted.getFlatArguments(),
2317 Converted.flatSize(),
2318 SourceRange(TemplateLoc, RAngleLoc));
2319
2320 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002321 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002322 RAngleLoc, Converted))
2323 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002324 }
2325
2326 return Invalid;
2327}
2328
2329/// \brief Check a template argument against its corresponding
2330/// template type parameter.
2331///
2332/// This routine implements the semantics of C++ [temp.arg.type]. It
2333/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002334bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002335 TypeSourceInfo *ArgInfo) {
2336 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002337 QualType Arg = ArgInfo->getType();
2338
Douglas Gregord32e0282009-02-09 23:23:08 +00002339 // C++ [temp.arg.type]p2:
2340 // A local type, a type with no linkage, an unnamed type or a type
2341 // compounded from any of these types shall not be used as a
2342 // template-argument for a template type-parameter.
2343 //
2344 // FIXME: Perform the recursive and no-linkage type checks.
2345 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002346 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002347 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002348 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002349 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002350 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2351 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2352 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2353 << QualType(Tag, 0) << SR;
2354 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002355 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002356 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2357 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002358 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2359 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002360 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2361 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2362 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002363 }
2364
2365 return false;
2366}
2367
Douglas Gregorccb07762009-02-11 19:52:55 +00002368/// \brief Checks whether the given template argument is the address
2369/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002370static bool
2371CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2372 NonTypeTemplateParmDecl *Param,
2373 QualType ParamType,
2374 Expr *ArgIn,
2375 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002376 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002377 Expr *Arg = ArgIn;
2378 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002379
2380 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002381 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002382 Arg = Cast->getSubExpr();
2383
2384 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002385 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002386 // A template-argument for a non-type, non-template
2387 // template-parameter shall be one of: [...]
2388 //
2389 // -- the address of an object or function with external
2390 // linkage, including function templates and function
2391 // template-ids but excluding non-static class members,
2392 // expressed as & id-expression where the & is optional if
2393 // the name refers to a function or array, or if the
2394 // corresponding template-parameter is a reference; or
2395 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002396
Douglas Gregorccb07762009-02-11 19:52:55 +00002397 // Ignore (and complain about) any excess parentheses.
2398 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2399 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002400 S.Diag(Arg->getSourceRange().getBegin(),
2401 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002402 << Arg->getSourceRange();
2403 Invalid = true;
2404 }
2405
2406 Arg = Parens->getSubExpr();
2407 }
2408
Douglas Gregorb242683d2010-04-01 18:32:35 +00002409 bool AddressTaken = false;
2410 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002411 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002412 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002413 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002414 AddressTaken = true;
2415 AddrOpLoc = UnOp->getOperatorLoc();
2416 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002417 } else
2418 DRE = dyn_cast<DeclRefExpr>(Arg);
2419
Douglas Gregorb242683d2010-04-01 18:32:35 +00002420 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002421 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2422 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002423 S.Diag(Param->getLocation(), diag::note_template_param_here);
2424 return true;
2425 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002426
2427 // Stop checking the precise nature of the argument if it is value dependent,
2428 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002429 if (Arg->isValueDependent()) {
2430 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002431 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002432 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002433
Douglas Gregorb242683d2010-04-01 18:32:35 +00002434 if (!isa<ValueDecl>(DRE->getDecl())) {
2435 S.Diag(Arg->getSourceRange().getBegin(),
2436 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002437 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002438 S.Diag(Param->getLocation(), diag::note_template_param_here);
2439 return true;
2440 }
2441
2442 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002443
2444 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002445 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2446 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002447 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002448 S.Diag(Param->getLocation(), diag::note_template_param_here);
2449 return true;
2450 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002451
2452 // Cannot refer to non-static member functions
2453 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002454 if (!Method->isStatic()) {
2455 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002456 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002457 S.Diag(Param->getLocation(), diag::note_template_param_here);
2458 return true;
2459 }
Mike Stump11289f42009-09-09 15:08:12 +00002460
Douglas Gregorccb07762009-02-11 19:52:55 +00002461 // Functions must have external linkage.
2462 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002463 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002464 S.Diag(Arg->getSourceRange().getBegin(),
2465 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002466 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002467 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002468 << true;
2469 return true;
2470 }
2471
2472 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002473 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002474
Douglas Gregorb242683d2010-04-01 18:32:35 +00002475 // If the template parameter has pointer type, the function decays.
2476 if (ParamType->isPointerType() && !AddressTaken)
2477 ArgType = S.Context.getPointerType(Func->getType());
2478 else if (AddressTaken && ParamType->isReferenceType()) {
2479 // If we originally had an address-of operator, but the
2480 // parameter has reference type, complain and (if things look
2481 // like they will work) drop the address-of operator.
2482 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2483 ParamType.getNonReferenceType())) {
2484 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2485 << ParamType;
2486 S.Diag(Param->getLocation(), diag::note_template_param_here);
2487 return true;
2488 }
2489
2490 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2491 << ParamType
2492 << FixItHint::CreateRemoval(AddrOpLoc);
2493 S.Diag(Param->getLocation(), diag::note_template_param_here);
2494
2495 ArgType = Func->getType();
2496 }
2497 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002498 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002499 S.Diag(Arg->getSourceRange().getBegin(),
2500 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002501 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002502 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002503 << true;
2504 return true;
2505 }
2506
Douglas Gregorb242683d2010-04-01 18:32:35 +00002507 // A value of reference type is not an object.
2508 if (Var->getType()->isReferenceType()) {
2509 S.Diag(Arg->getSourceRange().getBegin(),
2510 diag::err_template_arg_reference_var)
2511 << Var->getType() << Arg->getSourceRange();
2512 S.Diag(Param->getLocation(), diag::note_template_param_here);
2513 return true;
2514 }
2515
Douglas Gregorccb07762009-02-11 19:52:55 +00002516 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002517 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002518
2519 // If the template parameter has pointer type, we must have taken
2520 // the address of this object.
2521 if (ParamType->isReferenceType()) {
2522 if (AddressTaken) {
2523 // If we originally had an address-of operator, but the
2524 // parameter has reference type, complain and (if things look
2525 // like they will work) drop the address-of operator.
2526 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2527 ParamType.getNonReferenceType())) {
2528 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2529 << ParamType;
2530 S.Diag(Param->getLocation(), diag::note_template_param_here);
2531 return true;
2532 }
2533
2534 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2535 << ParamType
2536 << FixItHint::CreateRemoval(AddrOpLoc);
2537 S.Diag(Param->getLocation(), diag::note_template_param_here);
2538
2539 ArgType = Var->getType();
2540 }
2541 } else if (!AddressTaken && ParamType->isPointerType()) {
2542 if (Var->getType()->isArrayType()) {
2543 // Array-to-pointer decay.
2544 ArgType = S.Context.getArrayDecayedType(Var->getType());
2545 } else {
2546 // If the template parameter has pointer type but the address of
2547 // this object was not taken, complain and (possibly) recover by
2548 // taking the address of the entity.
2549 ArgType = S.Context.getPointerType(Var->getType());
2550 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2551 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2552 << ParamType;
2553 S.Diag(Param->getLocation(), diag::note_template_param_here);
2554 return true;
2555 }
2556
2557 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2558 << ParamType
2559 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2560
2561 S.Diag(Param->getLocation(), diag::note_template_param_here);
2562 }
2563 }
2564 } else {
2565 // We found something else, but we don't know specifically what it is.
2566 S.Diag(Arg->getSourceRange().getBegin(),
2567 diag::err_template_arg_not_object_or_func)
2568 << Arg->getSourceRange();
2569 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2570 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002571 }
Mike Stump11289f42009-09-09 15:08:12 +00002572
Douglas Gregorb242683d2010-04-01 18:32:35 +00002573 if (ParamType->isPointerType() &&
2574 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2575 S.IsQualificationConversion(ArgType, ParamType)) {
2576 // For pointer-to-object types, qualification conversions are
2577 // permitted.
2578 } else {
2579 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2580 if (!ParamRef->getPointeeType()->isFunctionType()) {
2581 // C++ [temp.arg.nontype]p5b3:
2582 // For a non-type template-parameter of type reference to
2583 // object, no conversions apply. The type referred to by the
2584 // reference may be more cv-qualified than the (otherwise
2585 // identical) type of the template- argument. The
2586 // template-parameter is bound directly to the
2587 // template-argument, which shall be an lvalue.
2588
2589 // FIXME: Other qualifiers?
2590 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2591 unsigned ArgQuals = ArgType.getCVRQualifiers();
2592
2593 if ((ParamQuals | ArgQuals) != ParamQuals) {
2594 S.Diag(Arg->getSourceRange().getBegin(),
2595 diag::err_template_arg_ref_bind_ignores_quals)
2596 << ParamType << Arg->getType()
2597 << Arg->getSourceRange();
2598 S.Diag(Param->getLocation(), diag::note_template_param_here);
2599 return true;
2600 }
2601 }
2602 }
2603
2604 // At this point, the template argument refers to an object or
2605 // function with external linkage. We now need to check whether the
2606 // argument and parameter types are compatible.
2607 if (!S.Context.hasSameUnqualifiedType(ArgType,
2608 ParamType.getNonReferenceType())) {
2609 // We can't perform this conversion or binding.
2610 if (ParamType->isReferenceType())
2611 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2612 << ParamType << Arg->getType() << Arg->getSourceRange();
2613 else
2614 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2615 << Arg->getType() << ParamType << Arg->getSourceRange();
2616 S.Diag(Param->getLocation(), diag::note_template_param_here);
2617 return true;
2618 }
2619 }
2620
2621 // Create the template argument.
2622 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002623 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002624 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002625}
2626
2627/// \brief Checks whether the given template argument is a pointer to
2628/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002629bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2630 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002631 bool Invalid = false;
2632
2633 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002634 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002635 Arg = Cast->getSubExpr();
2636
2637 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002638 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002639 // A template-argument for a non-type, non-template
2640 // template-parameter shall be one of: [...]
2641 //
2642 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002643 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002644
2645 // Ignore (and complain about) any excess parentheses.
2646 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2647 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002648 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002649 diag::err_template_arg_extra_parens)
2650 << Arg->getSourceRange();
2651 Invalid = true;
2652 }
2653
2654 Arg = Parens->getSubExpr();
2655 }
2656
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002657 // A pointer-to-member constant written &Class::member.
2658 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002659 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2660 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2661 if (DRE && !DRE->getQualifier())
2662 DRE = 0;
2663 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002664 }
2665 // A constant of pointer-to-member type.
2666 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2667 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2668 if (VD->getType()->isMemberPointerType()) {
2669 if (isa<NonTypeTemplateParmDecl>(VD) ||
2670 (isa<VarDecl>(VD) &&
2671 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2672 if (Arg->isTypeDependent() || Arg->isValueDependent())
2673 Converted = TemplateArgument(Arg->Retain());
2674 else
2675 Converted = TemplateArgument(VD->getCanonicalDecl());
2676 return Invalid;
2677 }
2678 }
2679 }
2680
2681 DRE = 0;
2682 }
2683
Douglas Gregorccb07762009-02-11 19:52:55 +00002684 if (!DRE)
2685 return Diag(Arg->getSourceRange().getBegin(),
2686 diag::err_template_arg_not_pointer_to_member_form)
2687 << Arg->getSourceRange();
2688
2689 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2690 assert((isa<FieldDecl>(DRE->getDecl()) ||
2691 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2692 "Only non-static member pointers can make it here");
2693
2694 // Okay: this is the address of a non-static member, and therefore
2695 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002696 if (Arg->isTypeDependent() || Arg->isValueDependent())
2697 Converted = TemplateArgument(Arg->Retain());
2698 else
2699 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002700 return Invalid;
2701 }
2702
2703 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002704 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002705 diag::err_template_arg_not_pointer_to_member_form)
2706 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002707 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002708 diag::note_template_arg_refers_here);
2709 return true;
2710}
2711
Douglas Gregord32e0282009-02-09 23:23:08 +00002712/// \brief Check a template argument against its corresponding
2713/// non-type template parameter.
2714///
Douglas Gregor463421d2009-03-03 04:44:36 +00002715/// This routine implements the semantics of C++ [temp.arg.nontype].
2716/// It returns true if an error occurred, and false otherwise. \p
2717/// InstantiatedParamType is the type of the non-type template
2718/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002719///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002720/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002721bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002722 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002723 TemplateArgument &Converted,
2724 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002725 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2726
Douglas Gregor86560402009-02-10 23:36:10 +00002727 // If either the parameter has a dependent type or the argument is
2728 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002729 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2730 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002731 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002732 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002733 }
Douglas Gregor86560402009-02-10 23:36:10 +00002734
2735 // C++ [temp.arg.nontype]p5:
2736 // The following conversions are performed on each expression used
2737 // as a non-type template-argument. If a non-type
2738 // template-argument cannot be converted to the type of the
2739 // corresponding template-parameter then the program is
2740 // ill-formed.
2741 //
2742 // -- for a non-type template-parameter of integral or
2743 // enumeration type, integral promotions (4.5) and integral
2744 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002745 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002746 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002747 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002748 // C++ [temp.arg.nontype]p1:
2749 // A template-argument for a non-type, non-template
2750 // template-parameter shall be one of:
2751 //
2752 // -- an integral constant-expression of integral or enumeration
2753 // type; or
2754 // -- the name of a non-type template-parameter; or
2755 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002756 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002757 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002758 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002759 diag::err_template_arg_not_integral_or_enumeral)
2760 << ArgType << Arg->getSourceRange();
2761 Diag(Param->getLocation(), diag::note_template_param_here);
2762 return true;
2763 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002764 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002765 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2766 << ArgType << Arg->getSourceRange();
2767 return true;
2768 }
2769
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002770 // From here on out, all we care about are the unqualified forms
2771 // of the parameter and argument types.
2772 ParamType = ParamType.getUnqualifiedType();
2773 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002774
2775 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002776 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002777 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002778 } else if (CTAK == CTAK_Deduced) {
2779 // C++ [temp.deduct.type]p17:
2780 // If, in the declaration of a function template with a non-type
2781 // template-parameter, the non-type template- parameter is used
2782 // in an expression in the function parameter-list and, if the
2783 // corresponding template-argument is deduced, the
2784 // template-argument type shall match the type of the
2785 // template-parameter exactly, except that a template-argument
2786 // deduced from an array bound may be of any integral type.
2787 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2788 << ArgType << ParamType;
2789 Diag(Param->getLocation(), diag::note_template_param_here);
2790 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002791 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2792 !ParamType->isEnumeralType()) {
2793 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002794 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002795 } else {
2796 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002797 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002798 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002799 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002800 Diag(Param->getLocation(), diag::note_template_param_here);
2801 return true;
2802 }
2803
Douglas Gregor52aba872009-03-14 00:20:21 +00002804 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002805 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002806 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002807
2808 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002809 llvm::APSInt OldValue = Value;
2810
2811 // Coerce the template argument's value to the value it will have
2812 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002813 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002814 if (Value.getBitWidth() != AllowedBits)
2815 Value.extOrTrunc(AllowedBits);
2816 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002817
2818 // Complain if an unsigned parameter received a negative value.
2819 if (IntegerType->isUnsignedIntegerType()
2820 && (OldValue.isSigned() && OldValue.isNegative())) {
2821 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2822 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2823 << Arg->getSourceRange();
2824 Diag(Param->getLocation(), diag::note_template_param_here);
2825 }
2826
2827 // Complain if we overflowed the template parameter's type.
2828 unsigned RequiredBits;
2829 if (IntegerType->isUnsignedIntegerType())
2830 RequiredBits = OldValue.getActiveBits();
2831 else if (OldValue.isUnsigned())
2832 RequiredBits = OldValue.getActiveBits() + 1;
2833 else
2834 RequiredBits = OldValue.getMinSignedBits();
2835 if (RequiredBits > AllowedBits) {
2836 Diag(Arg->getSourceRange().getBegin(),
2837 diag::warn_template_arg_too_large)
2838 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2839 << Arg->getSourceRange();
2840 Diag(Param->getLocation(), diag::note_template_param_here);
2841 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002842 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002843
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002844 // Add the value of this argument to the list of converted
2845 // arguments. We use the bitwidth and signedness of the template
2846 // parameter.
2847 if (Arg->isValueDependent()) {
2848 // The argument is value-dependent. Create a new
2849 // TemplateArgument with the converted expression.
2850 Converted = TemplateArgument(Arg);
2851 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002852 }
2853
John McCall0ad16662009-10-29 08:12:44 +00002854 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002855 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002856 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002857 return false;
2858 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002859
John McCall16df1e52010-03-30 21:47:33 +00002860 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2861
Douglas Gregorb242683d2010-04-01 18:32:35 +00002862 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2863 // from a template argument of type std::nullptr_t to a non-type
2864 // template parameter of type pointer to object, pointer to
2865 // function, or pointer-to-member, respectively.
2866 if (ArgType->isNullPtrType() &&
2867 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2868 Converted = TemplateArgument((NamedDecl *)0);
2869 return false;
2870 }
2871
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002872 // Handle pointer-to-function, reference-to-function, and
2873 // pointer-to-member-function all in (roughly) the same way.
2874 if (// -- For a non-type template-parameter of type pointer to
2875 // function, only the function-to-pointer conversion (4.3) is
2876 // applied. If the template-argument represents a set of
2877 // overloaded functions (or a pointer to such), the matching
2878 // function is selected from the set (13.4).
2879 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002880 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002881 // -- For a non-type template-parameter of type reference to
2882 // function, no conversions apply. If the template-argument
2883 // represents a set of overloaded functions, the matching
2884 // function is selected from the set (13.4).
2885 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002886 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002887 // -- For a non-type template-parameter of type pointer to
2888 // member function, no conversions apply. If the
2889 // template-argument represents a set of overloaded member
2890 // functions, the matching member function is selected from
2891 // the set (13.4).
2892 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002893 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002894 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002895
Douglas Gregor064fdb22010-04-14 23:11:21 +00002896 if (Arg->getType() == Context.OverloadTy) {
2897 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2898 true,
2899 FoundResult)) {
2900 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2901 return true;
2902
2903 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2904 ArgType = Arg->getType();
2905 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002906 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002907 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002908
Douglas Gregorb242683d2010-04-01 18:32:35 +00002909 if (!ParamType->isMemberPointerType())
2910 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2911 ParamType,
2912 Arg, Converted);
2913
2914 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2915 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2916 Arg->isLvalue(Context) == Expr::LV_Valid);
2917 } else if (!Context.hasSameUnqualifiedType(ArgType,
2918 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002919 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002920 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002921 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002922 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002923 Diag(Param->getLocation(), diag::note_template_param_here);
2924 return true;
2925 }
Mike Stump11289f42009-09-09 15:08:12 +00002926
Douglas Gregorb242683d2010-04-01 18:32:35 +00002927 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002928 }
2929
Chris Lattner696197c2009-02-20 21:37:53 +00002930 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002931 // -- for a non-type template-parameter of type pointer to
2932 // object, qualification conversions (4.4) and the
2933 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002934 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002935 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002936 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002937
Douglas Gregorb242683d2010-04-01 18:32:35 +00002938 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2939 ParamType,
2940 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002941 }
Mike Stump11289f42009-09-09 15:08:12 +00002942
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002943 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002944 // -- For a non-type template-parameter of type reference to
2945 // object, no conversions apply. The type referred to by the
2946 // reference may be more cv-qualified than the (otherwise
2947 // identical) type of the template-argument. The
2948 // template-parameter is bound directly to the
2949 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002950 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002951 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002952
Douglas Gregor064fdb22010-04-14 23:11:21 +00002953 if (Arg->getType() == Context.OverloadTy) {
2954 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2955 ParamRefType->getPointeeType(),
2956 true,
2957 FoundResult)) {
2958 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2959 return true;
2960
2961 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2962 ArgType = Arg->getType();
2963 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002964 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002965 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002966
Douglas Gregorb242683d2010-04-01 18:32:35 +00002967 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2968 ParamType,
2969 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002970 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002971
2972 // -- For a non-type template-parameter of type pointer to data
2973 // member, qualification conversions (4.4) are applied.
2974 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2975
Douglas Gregor1515f762009-02-11 18:22:40 +00002976 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002977 // Types match exactly: nothing more to do here.
2978 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002979 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2980 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor0e558532009-02-11 16:16:59 +00002981 } else {
2982 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002983 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002984 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002985 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002986 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002987 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002988 }
2989
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002990 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002991}
2992
2993/// \brief Check a template argument against its corresponding
2994/// template template parameter.
2995///
2996/// This routine implements the semantics of C++ [temp.arg.template].
2997/// It returns true if an error occurred, and false otherwise.
2998bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002999 const TemplateArgumentLoc &Arg) {
3000 TemplateName Name = Arg.getArgument().getAsTemplate();
3001 TemplateDecl *Template = Name.getAsTemplateDecl();
3002 if (!Template) {
3003 // Any dependent template name is fine.
3004 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3005 return false;
3006 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003007
3008 // C++ [temp.arg.template]p1:
3009 // A template-argument for a template template-parameter shall be
3010 // the name of a class template, expressed as id-expression. Only
3011 // primary class templates are considered when matching the
3012 // template template argument with the corresponding parameter;
3013 // partial specializations are not considered even if their
3014 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003015 //
3016 // Note that we also allow template template parameters here, which
3017 // will happen when we are dealing with, e.g., class template
3018 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003019 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003020 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003021 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003022 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003023 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003024 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003025 << Template;
3026 }
3027
3028 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3029 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003030 true,
3031 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003032 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003033}
3034
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003035/// \brief Given a non-type template argument that refers to a
3036/// declaration and the type of its corresponding non-type template
3037/// parameter, produce an expression that properly refers to that
3038/// declaration.
3039Sema::OwningExprResult
3040Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3041 QualType ParamType,
3042 SourceLocation Loc) {
3043 assert(Arg.getKind() == TemplateArgument::Declaration &&
3044 "Only declaration template arguments permitted here");
3045 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3046
3047 if (VD->getDeclContext()->isRecord() &&
3048 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3049 // If the value is a class member, we might have a pointer-to-member.
3050 // Determine whether the non-type template template parameter is of
3051 // pointer-to-member type. If so, we need to build an appropriate
3052 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3053 // would refer to the member itself.
3054 if (ParamType->isMemberPointerType()) {
3055 QualType ClassType
3056 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3057 NestedNameSpecifier *Qualifier
3058 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3059 CXXScopeSpec SS;
3060 SS.setScopeRep(Qualifier);
3061 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3062 VD->getType().getNonReferenceType(),
3063 Loc,
3064 &SS);
3065 if (RefExpr.isInvalid())
3066 return ExprError();
3067
3068 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003069
3070 // We might need to perform a trailing qualification conversion, since
3071 // the element type on the parameter could be more qualified than the
3072 // element type in the expression we constructed.
3073 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3074 ParamType.getUnqualifiedType())) {
3075 Expr *RefE = RefExpr.takeAs<Expr>();
3076 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3077 CastExpr::CK_NoOp);
3078 RefExpr = Owned(RefE);
3079 }
3080
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003081 assert(!RefExpr.isInvalid() &&
3082 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003083 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003084 return move(RefExpr);
3085 }
3086 }
3087
3088 QualType T = VD->getType().getNonReferenceType();
3089 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003090 // When the non-type template parameter is a pointer, take the
3091 // address of the declaration.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003092 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3093 if (RefExpr.isInvalid())
3094 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003095
3096 if (T->isFunctionType() || T->isArrayType()) {
3097 // Decay functions and arrays.
3098 Expr *RefE = (Expr *)RefExpr.get();
3099 DefaultFunctionArrayConversion(RefE);
3100 if (RefE != RefExpr.get()) {
3101 RefExpr.release();
3102 RefExpr = Owned(RefE);
3103 }
3104
3105 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003106 }
3107
Douglas Gregorb242683d2010-04-01 18:32:35 +00003108 // Take the address of everything else
3109 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003110 }
3111
3112 // If the non-type template parameter has reference type, qualify the
3113 // resulting declaration reference with the extra qualifiers on the
3114 // type that the reference refers to.
3115 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3116 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3117
3118 return BuildDeclRefExpr(VD, T, Loc);
3119}
3120
3121/// \brief Construct a new expression that refers to the given
3122/// integral template argument with the given source-location
3123/// information.
3124///
3125/// This routine takes care of the mapping from an integral template
3126/// argument (which may have any integral type) to the appropriate
3127/// literal value.
3128Sema::OwningExprResult
3129Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3130 SourceLocation Loc) {
3131 assert(Arg.getKind() == TemplateArgument::Integral &&
3132 "Operation is only value for integral template arguments");
3133 QualType T = Arg.getIntegralType();
3134 if (T->isCharType() || T->isWideCharType())
3135 return Owned(new (Context) CharacterLiteral(
3136 Arg.getAsIntegral()->getZExtValue(),
3137 T->isWideCharType(),
3138 T,
3139 Loc));
3140 if (T->isBooleanType())
3141 return Owned(new (Context) CXXBoolLiteralExpr(
3142 Arg.getAsIntegral()->getBoolValue(),
3143 T,
3144 Loc));
3145
3146 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3147}
3148
3149
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003150/// \brief Determine whether the given template parameter lists are
3151/// equivalent.
3152///
Mike Stump11289f42009-09-09 15:08:12 +00003153/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003154/// source code as part of a new template declaration.
3155///
3156/// \param Old The old template parameter list, typically found via
3157/// name lookup of the template declared with this template parameter
3158/// list.
3159///
3160/// \param Complain If true, this routine will produce a diagnostic if
3161/// the template parameter lists are not equivalent.
3162///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003163/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003164///
3165/// \param TemplateArgLoc If this source location is valid, then we
3166/// are actually checking the template parameter list of a template
3167/// argument (New) against the template parameter list of its
3168/// corresponding template template parameter (Old). We produce
3169/// slightly different diagnostics in this scenario.
3170///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003171/// \returns True if the template parameter lists are equal, false
3172/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003173bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003174Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3175 TemplateParameterList *Old,
3176 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003177 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003178 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003179 if (Old->size() != New->size()) {
3180 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003181 unsigned NextDiag = diag::err_template_param_list_different_arity;
3182 if (TemplateArgLoc.isValid()) {
3183 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3184 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003185 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003186 Diag(New->getTemplateLoc(), NextDiag)
3187 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003188 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003189 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003190 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003191 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003192 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3193 }
3194
3195 return false;
3196 }
3197
3198 for (TemplateParameterList::iterator OldParm = Old->begin(),
3199 OldParmEnd = Old->end(), NewParm = New->begin();
3200 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3201 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003202 if (Complain) {
3203 unsigned NextDiag = diag::err_template_param_different_kind;
3204 if (TemplateArgLoc.isValid()) {
3205 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3206 NextDiag = diag::note_template_param_different_kind;
3207 }
3208 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003209 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003210 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003211 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003212 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003213 return false;
3214 }
3215
3216 if (isa<TemplateTypeParmDecl>(*OldParm)) {
3217 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00003218 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00003219 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003220 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3221 // The types of non-type template parameters must agree.
3222 NonTypeTemplateParmDecl *NewNTTP
3223 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003224
3225 // If we are matching a template template argument to a template
3226 // template parameter and one of the non-type template parameter types
3227 // is dependent, then we must wait until template instantiation time
3228 // to actually compare the arguments.
3229 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3230 (OldNTTP->getType()->isDependentType() ||
3231 NewNTTP->getType()->isDependentType()))
3232 continue;
3233
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003234 if (Context.getCanonicalType(OldNTTP->getType()) !=
3235 Context.getCanonicalType(NewNTTP->getType())) {
3236 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003237 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3238 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003239 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003240 diag::err_template_arg_template_params_mismatch);
3241 NextDiag = diag::note_template_nontype_parm_different_type;
3242 }
3243 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003244 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003245 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003246 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003247 diag::note_template_nontype_parm_prev_declaration)
3248 << OldNTTP->getType();
3249 }
3250 return false;
3251 }
3252 } else {
3253 // The template parameter lists of template template
3254 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003255 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003256 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003257 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003258 = cast<TemplateTemplateParmDecl>(*OldParm);
3259 TemplateTemplateParmDecl *NewTTP
3260 = cast<TemplateTemplateParmDecl>(*NewParm);
3261 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3262 OldTTP->getTemplateParameters(),
3263 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003264 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003265 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003266 return false;
3267 }
3268 }
3269
3270 return true;
3271}
3272
3273/// \brief Check whether a template can be declared within this scope.
3274///
3275/// If the template declaration is valid in this scope, returns
3276/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003277bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003278Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003279 // Find the nearest enclosing declaration scope.
3280 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3281 (S->getFlags() & Scope::TemplateParamScope) != 0)
3282 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003283
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003284 // C++ [temp]p2:
3285 // A template-declaration can appear only as a namespace scope or
3286 // class scope declaration.
3287 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003288 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3289 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003290 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003291 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003292
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003293 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003294 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003295
3296 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3297 return false;
3298
Mike Stump11289f42009-09-09 15:08:12 +00003299 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003300 diag::err_template_outside_namespace_or_class_scope)
3301 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003302}
Douglas Gregor67a65642009-02-17 23:15:12 +00003303
Douglas Gregor54888652009-10-07 00:13:32 +00003304/// \brief Determine what kind of template specialization the given declaration
3305/// is.
3306static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3307 if (!D)
3308 return TSK_Undeclared;
3309
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003310 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3311 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003312 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3313 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003314 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3315 return Var->getTemplateSpecializationKind();
3316
Douglas Gregor54888652009-10-07 00:13:32 +00003317 return TSK_Undeclared;
3318}
3319
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003320/// \brief Check whether a specialization is well-formed in the current
3321/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003322///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003323/// This routine determines whether a template specialization can be declared
3324/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003325///
3326/// \param S the semantic analysis object for which this check is being
3327/// performed.
3328///
3329/// \param Specialized the entity being specialized or instantiated, which
3330/// may be a kind of template (class template, function template, etc.) or
3331/// a member of a class template (member function, static data member,
3332/// member class).
3333///
3334/// \param PrevDecl the previous declaration of this entity, if any.
3335///
3336/// \param Loc the location of the explicit specialization or instantiation of
3337/// this entity.
3338///
3339/// \param IsPartialSpecialization whether this is a partial specialization of
3340/// a class template.
3341///
Douglas Gregor54888652009-10-07 00:13:32 +00003342/// \returns true if there was an error that we cannot recover from, false
3343/// otherwise.
3344static bool CheckTemplateSpecializationScope(Sema &S,
3345 NamedDecl *Specialized,
3346 NamedDecl *PrevDecl,
3347 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003348 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003349 // Keep these "kind" numbers in sync with the %select statements in the
3350 // various diagnostics emitted by this routine.
3351 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003352 bool isTemplateSpecialization = false;
3353 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003354 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003355 isTemplateSpecialization = true;
3356 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003357 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003358 isTemplateSpecialization = true;
3359 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003360 EntityKind = 3;
3361 else if (isa<VarDecl>(Specialized))
3362 EntityKind = 4;
3363 else if (isa<RecordDecl>(Specialized))
3364 EntityKind = 5;
3365 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003366 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3367 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003368 return true;
3369 }
3370
Douglas Gregorf47b9112009-02-25 22:02:03 +00003371 // C++ [temp.expl.spec]p2:
3372 // An explicit specialization shall be declared in the namespace
3373 // of which the template is a member, or, for member templates, in
3374 // the namespace of which the enclosing class or enclosing class
3375 // template is a member. An explicit specialization of a member
3376 // function, member class or static data member of a class
3377 // template shall be declared in the namespace of which the class
3378 // template is a member. Such a declaration may also be a
3379 // definition. If the declaration is not a definition, the
3380 // specialization may be defined later in the name- space in which
3381 // the explicit specialization was declared, or in a namespace
3382 // that encloses the one in which the explicit specialization was
3383 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003384 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3385 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003386 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003387 return true;
3388 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003389
Douglas Gregor40fb7442009-10-07 17:30:37 +00003390 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3391 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003392 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003393 return true;
3394 }
3395
Douglas Gregore4b05162009-10-07 17:21:34 +00003396 // C++ [temp.class.spec]p6:
3397 // A class template partial specialization may be declared or redeclared
3398 // in any namespace scope in which its definition may be defined (14.5.1
3399 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003400 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003401 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003402 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003403 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003404 if ((!PrevDecl ||
3405 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3406 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3407 // There is no prior declaration of this entity, so this
3408 // specialization must be in the same context as the template
3409 // itself.
3410 if (!DC->Equals(SpecializedContext)) {
3411 if (isa<TranslationUnitDecl>(SpecializedContext))
3412 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3413 << EntityKind << Specialized;
3414 else if (isa<NamespaceDecl>(SpecializedContext))
3415 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3416 << EntityKind << Specialized
3417 << cast<NamedDecl>(SpecializedContext);
3418
3419 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3420 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003421 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003422 }
Douglas Gregor54888652009-10-07 00:13:32 +00003423
3424 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003425 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003426 // Note that HandleDeclarator() performs this check for explicit
3427 // specializations of function templates, static data members, and member
3428 // functions, so we skip the check here for those kinds of entities.
3429 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003430 // Should we refactor that check, so that it occurs later?
3431 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003432 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3433 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003434 if (isa<TranslationUnitDecl>(SpecializedContext))
3435 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3436 << EntityKind << Specialized;
3437 else if (isa<NamespaceDecl>(SpecializedContext))
3438 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3439 << EntityKind << Specialized
3440 << cast<NamedDecl>(SpecializedContext);
3441
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003442 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003443 }
Douglas Gregor54888652009-10-07 00:13:32 +00003444
3445 // FIXME: check for specialization-after-instantiation errors and such.
3446
Douglas Gregorf47b9112009-02-25 22:02:03 +00003447 return false;
3448}
Douglas Gregor54888652009-10-07 00:13:32 +00003449
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003450/// \brief Check the non-type template arguments of a class template
3451/// partial specialization according to C++ [temp.class.spec]p9.
3452///
Douglas Gregor09a30232009-06-12 22:08:06 +00003453/// \param TemplateParams the template parameters of the primary class
3454/// template.
3455///
3456/// \param TemplateArg the template arguments of the class template
3457/// partial specialization.
3458///
3459/// \param MirrorsPrimaryTemplate will be set true if the class
3460/// template partial specialization arguments are identical to the
3461/// implicit template arguments of the primary template. This is not
3462/// necessarily an error (C++0x), and it is left to the caller to diagnose
3463/// this condition when it is an error.
3464///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003465/// \returns true if there was an error, false otherwise.
3466bool Sema::CheckClassTemplatePartialSpecializationArgs(
3467 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003468 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003469 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003470 // FIXME: the interface to this function will have to change to
3471 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003472 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003473
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003474 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003475
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003476 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003477 // Determine whether the template argument list of the partial
3478 // specialization is identical to the implicit argument list of
3479 // the primary template. The caller may need to diagnostic this as
3480 // an error per C++ [temp.class.spec]p9b3.
3481 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003482 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003483 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3484 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003485 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003486 MirrorsPrimaryTemplate = false;
3487 } else if (TemplateTemplateParmDecl *TTP
3488 = dyn_cast<TemplateTemplateParmDecl>(
3489 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003490 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003491 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003492 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003493 if (!ArgDecl ||
3494 ArgDecl->getIndex() != TTP->getIndex() ||
3495 ArgDecl->getDepth() != TTP->getDepth())
3496 MirrorsPrimaryTemplate = false;
3497 }
3498 }
3499
Mike Stump11289f42009-09-09 15:08:12 +00003500 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003501 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003502 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003503 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003504 }
3505
Anders Carlsson40c1d492009-06-13 18:20:51 +00003506 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003507 if (!ArgExpr) {
3508 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003509 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003510 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003511
3512 // C++ [temp.class.spec]p8:
3513 // A non-type argument is non-specialized if it is the name of a
3514 // non-type parameter. All other non-type arguments are
3515 // specialized.
3516 //
3517 // Below, we check the two conditions that only apply to
3518 // specialized non-type arguments, so skip any non-specialized
3519 // arguments.
3520 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003521 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003522 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003523 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003524 (Param->getIndex() != NTTP->getIndex() ||
3525 Param->getDepth() != NTTP->getDepth()))
3526 MirrorsPrimaryTemplate = false;
3527
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003528 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003529 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003530
3531 // C++ [temp.class.spec]p9:
3532 // Within the argument list of a class template partial
3533 // specialization, the following restrictions apply:
3534 // -- A partially specialized non-type argument expression
3535 // shall not involve a template parameter of the partial
3536 // specialization except when the argument expression is a
3537 // simple identifier.
3538 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003539 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003540 diag::err_dependent_non_type_arg_in_partial_spec)
3541 << ArgExpr->getSourceRange();
3542 return true;
3543 }
3544
3545 // -- The type of a template parameter corresponding to a
3546 // specialized non-type argument shall not be dependent on a
3547 // parameter of the specialization.
3548 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003549 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003550 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3551 << Param->getType()
3552 << ArgExpr->getSourceRange();
3553 Diag(Param->getLocation(), diag::note_template_param_here);
3554 return true;
3555 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003556
3557 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003558 }
3559
3560 return false;
3561}
3562
Douglas Gregorc854c662010-02-26 06:03:23 +00003563/// \brief Retrieve the previous declaration of the given declaration.
3564static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3565 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3566 return VD->getPreviousDeclaration();
3567 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3568 return FD->getPreviousDeclaration();
3569 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3570 return TD->getPreviousDeclaration();
3571 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3572 return TD->getPreviousDeclaration();
3573 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3574 return FTD->getPreviousDeclaration();
3575 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3576 return CTD->getPreviousDeclaration();
3577 return 0;
3578}
3579
Douglas Gregorc08f4892009-03-25 00:13:59 +00003580Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003581Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3582 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003583 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003584 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003585 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003586 SourceLocation TemplateNameLoc,
3587 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003588 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003589 SourceLocation RAngleLoc,
3590 AttributeList *Attr,
3591 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003592 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003593
Douglas Gregor67a65642009-02-17 23:15:12 +00003594 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003595 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003596 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003597 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3598
3599 if (!ClassTemplate) {
3600 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3601 << (Name.getAsTemplateDecl() &&
3602 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3603 return true;
3604 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003605
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003606 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003607 bool isPartialSpecialization = false;
3608
Douglas Gregorf47b9112009-02-25 22:02:03 +00003609 // Check the validity of the template headers that introduce this
3610 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003611 // FIXME: We probably shouldn't complain about these headers for
3612 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003613 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003614 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3615 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003616 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003617 TUK == TUK_Friend,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003618 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003619 if (TemplateParams && TemplateParams->size() > 0) {
3620 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003621
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003622 // C++ [temp.class.spec]p10:
3623 // The template parameter list of a specialization shall not
3624 // contain default template argument values.
3625 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3626 Decl *Param = TemplateParams->getParam(I);
3627 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3628 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003629 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003630 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003631 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003632 }
3633 } else if (NonTypeTemplateParmDecl *NTTP
3634 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3635 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003636 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003637 diag::err_default_arg_in_partial_spec)
3638 << DefArg->getSourceRange();
3639 NTTP->setDefaultArgument(0);
3640 DefArg->Destroy(Context);
3641 }
3642 } else {
3643 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003644 if (TTP->hasDefaultArgument()) {
3645 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003646 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003647 << TTP->getDefaultArgument().getSourceRange();
3648 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003649 }
3650 }
3651 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003652 } else if (TemplateParams) {
3653 if (TUK == TUK_Friend)
3654 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003655 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003656 SourceRange(TemplateParams->getTemplateLoc(),
3657 TemplateParams->getRAngleLoc()))
3658 << SourceRange(LAngleLoc, RAngleLoc);
3659 else
3660 isExplicitSpecialization = true;
3661 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003662 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003663 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003664 isExplicitSpecialization = true;
3665 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003666
Douglas Gregor67a65642009-02-17 23:15:12 +00003667 // Check that the specialization uses the same tag kind as the
3668 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003669 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3670 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003671 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003672 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003673 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003674 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003675 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003676 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003677 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003678 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003679 diag::note_previous_use);
3680 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3681 }
3682
Douglas Gregorc40290e2009-03-09 23:48:35 +00003683 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003684 TemplateArgumentListInfo TemplateArgs;
3685 TemplateArgs.setLAngleLoc(LAngleLoc);
3686 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003687 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003688
Douglas Gregor67a65642009-02-17 23:15:12 +00003689 // Check that the template argument list is well-formed for this
3690 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003691 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3692 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003693 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3694 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003695 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003696
Mike Stump11289f42009-09-09 15:08:12 +00003697 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003698 ClassTemplate->getTemplateParameters()->size()) &&
3699 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003700
Douglas Gregor2373c592009-05-31 09:31:02 +00003701 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003702 // corresponds to these arguments.
3703 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003704 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003705 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003706 if (CheckClassTemplatePartialSpecializationArgs(
3707 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003708 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003709 return true;
3710
Douglas Gregor09a30232009-06-12 22:08:06 +00003711 if (MirrorsPrimaryTemplate) {
3712 // C++ [temp.class.spec]p9b3:
3713 //
Mike Stump11289f42009-09-09 15:08:12 +00003714 // -- The argument list of the specialization shall not be identical
3715 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003716 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003717 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003718 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003719 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003720 ClassTemplate->getIdentifier(),
3721 TemplateNameLoc,
3722 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003723 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003724 AS_none);
3725 }
3726
Douglas Gregor2208a292009-09-26 20:57:03 +00003727 // FIXME: Diagnose friend partial specializations
3728
Douglas Gregor92354b62010-02-09 00:37:32 +00003729 if (!Name.isDependent() &&
3730 !TemplateSpecializationType::anyDependentTemplateArguments(
3731 TemplateArgs.getArgumentArray(),
3732 TemplateArgs.size())) {
3733 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3734 << ClassTemplate->getDeclName();
3735 isPartialSpecialization = false;
3736 } else {
3737 // FIXME: Template parameter list matters, too
3738 ClassTemplatePartialSpecializationDecl::Profile(ID,
3739 Converted.getFlatArguments(),
3740 Converted.flatSize(),
3741 Context);
3742 }
3743 }
3744
3745 if (!isPartialSpecialization)
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003746 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003747 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003748 Converted.flatSize(),
3749 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003750 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003751 ClassTemplateSpecializationDecl *PrevDecl = 0;
3752
3753 if (isPartialSpecialization)
3754 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003755 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003756 InsertPos);
3757 else
3758 PrevDecl
3759 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003760
3761 ClassTemplateSpecializationDecl *Specialization = 0;
3762
Douglas Gregorf47b9112009-02-25 22:02:03 +00003763 // Check whether we can declare a class template specialization in
3764 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003765 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003766 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003767 TemplateNameLoc,
3768 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003769 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003770
Douglas Gregor15301382009-07-30 17:40:51 +00003771 // The canonical type
3772 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003773 if (PrevDecl &&
3774 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003775 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003776 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003777 // arguments was referenced but not declared, or we're only
3778 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003779 // declaration node as our own, updating its source location to
3780 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003781 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003782 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003783 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003784 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003785 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003786 // Build the canonical type that describes the converted template
3787 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003788 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3789 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003790 Converted.getFlatArguments(),
3791 Converted.flatSize());
3792
Douglas Gregor2373c592009-05-31 09:31:02 +00003793 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003794 ClassTemplatePartialSpecializationDecl *PrevPartial
3795 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00003796 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
3797 : ClassTemplate->getPartialSpecializations().size();
Mike Stump11289f42009-09-09 15:08:12 +00003798 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00003799 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00003800 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003801 TemplateNameLoc,
3802 TemplateParams,
3803 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003804 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003805 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003806 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00003807 PrevPartial,
3808 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00003809 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor2373c592009-05-31 09:31:02 +00003810
3811 if (PrevPartial) {
3812 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3813 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3814 } else {
3815 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3816 }
3817 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003818
Douglas Gregor21610382009-10-29 00:04:11 +00003819 // If we are providing an explicit specialization of a member class
3820 // template specialization, make a note of that.
3821 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3822 PrevPartial->setMemberSpecialization();
3823
Douglas Gregor91772d12009-06-13 00:26:55 +00003824 // Check that all of the template parameters of the class template
3825 // partial specialization are deducible from the template
3826 // arguments. If not, this class template partial specialization
3827 // will never be used.
3828 llvm::SmallVector<bool, 8> DeducibleParams;
3829 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003830 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003831 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003832 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003833 unsigned NumNonDeducible = 0;
3834 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3835 if (!DeducibleParams[I])
3836 ++NumNonDeducible;
3837
3838 if (NumNonDeducible) {
3839 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3840 << (NumNonDeducible > 1)
3841 << SourceRange(TemplateNameLoc, RAngleLoc);
3842 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3843 if (!DeducibleParams[I]) {
3844 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3845 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003846 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003847 diag::note_partial_spec_unused_parameter)
3848 << Param->getDeclName();
3849 else
Mike Stump11289f42009-09-09 15:08:12 +00003850 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003851 diag::note_partial_spec_unused_parameter)
3852 << std::string("<anonymous>");
3853 }
3854 }
3855 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003856 } else {
3857 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003858 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003859 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00003860 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00003861 ClassTemplate->getDeclContext(),
3862 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003863 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003864 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003865 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003866 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor67a65642009-02-17 23:15:12 +00003867
3868 if (PrevDecl) {
3869 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3870 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3871 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003872 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003873 InsertPos);
3874 }
Douglas Gregor15301382009-07-30 17:40:51 +00003875
3876 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003877 }
3878
Douglas Gregor06db9f52009-10-12 20:18:28 +00003879 // C++ [temp.expl.spec]p6:
3880 // If a template, a member template or the member of a class template is
3881 // explicitly specialized then that specialization shall be declared
3882 // before the first use of that specialization that would cause an implicit
3883 // instantiation to take place, in every translation unit in which such a
3884 // use occurs; no diagnostic is required.
3885 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003886 bool Okay = false;
3887 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3888 // Is there any previous explicit specialization declaration?
3889 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3890 Okay = true;
3891 break;
3892 }
3893 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003894
Douglas Gregorc854c662010-02-26 06:03:23 +00003895 if (!Okay) {
3896 SourceRange Range(TemplateNameLoc, RAngleLoc);
3897 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3898 << Context.getTypeDeclType(Specialization) << Range;
3899
3900 Diag(PrevDecl->getPointOfInstantiation(),
3901 diag::note_instantiation_required_here)
3902 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003903 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003904 return true;
3905 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003906 }
3907
Douglas Gregor2208a292009-09-26 20:57:03 +00003908 // If this is not a friend, note that this is an explicit specialization.
3909 if (TUK != TUK_Friend)
3910 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003911
3912 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003913 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003914 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003915 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003916 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003917 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003918 Diag(Def->getLocation(), diag::note_previous_definition);
3919 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003920 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003921 }
3922 }
3923
Douglas Gregord56a91e2009-02-26 22:19:44 +00003924 // Build the fully-sugared type for this class template
3925 // specialization as the user wrote in the specialization
3926 // itself. This means that we'll pretty-print the type retrieved
3927 // from the specialization's declaration the way that the user
3928 // actually wrote the specialization, rather than formatting the
3929 // name based on the "canonical" representation used to store the
3930 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003931 TypeSourceInfo *WrittenTy
3932 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3933 TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003934 if (TUK != TUK_Friend)
3935 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003936 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003937
Douglas Gregor1e249f82009-02-25 22:18:32 +00003938 // C++ [temp.expl.spec]p9:
3939 // A template explicit specialization is in the scope of the
3940 // namespace in which the template was defined.
3941 //
3942 // We actually implement this paragraph where we set the semantic
3943 // context (in the creation of the ClassTemplateSpecializationDecl),
3944 // but we also maintain the lexical context where the actual
3945 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003946 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003947
Douglas Gregor67a65642009-02-17 23:15:12 +00003948 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003949 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003950 Specialization->startDefinition();
3951
Douglas Gregor2208a292009-09-26 20:57:03 +00003952 if (TUK == TUK_Friend) {
3953 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3954 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00003955 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00003956 /*FIXME:*/KWLoc);
3957 Friend->setAccess(AS_public);
3958 CurContext->addDecl(Friend);
3959 } else {
3960 // Add the specialization into its lexical context, so that it can
3961 // be seen when iterating through the list of declarations in that
3962 // context. However, specializations are not found by name lookup.
3963 CurContext->addDecl(Specialization);
3964 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003965 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003966}
Douglas Gregor333489b2009-03-27 23:10:48 +00003967
Mike Stump11289f42009-09-09 15:08:12 +00003968Sema::DeclPtrTy
3969Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003970 MultiTemplateParamsArg TemplateParameterLists,
3971 Declarator &D) {
3972 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3973}
3974
Mike Stump11289f42009-09-09 15:08:12 +00003975Sema::DeclPtrTy
3976Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003977 MultiTemplateParamsArg TemplateParameterLists,
3978 Declarator &D) {
3979 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3980 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3981 "Not a function declarator!");
3982 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003983
Douglas Gregor17a7c122009-06-24 00:54:41 +00003984 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003985 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003986 }
Mike Stump11289f42009-09-09 15:08:12 +00003987
Douglas Gregor17a7c122009-06-24 00:54:41 +00003988 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003989
3990 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003991 move(TemplateParameterLists),
3992 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003993 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003994 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003995 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003996 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003997 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3998 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003999 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00004000}
4001
John McCall4f7ced62010-02-11 01:33:53 +00004002/// \brief Strips various properties off an implicit instantiation
4003/// that has just been explicitly specialized.
4004static void StripImplicitInstantiation(NamedDecl *D) {
4005 D->invalidateAttrs();
4006
4007 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4008 FD->setInlineSpecified(false);
4009 }
4010}
4011
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004012/// \brief Diagnose cases where we have an explicit template specialization
4013/// before/after an explicit template instantiation, producing diagnostics
4014/// for those cases where they are required and determining whether the
4015/// new specialization/instantiation will have any effect.
4016///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004017/// \param NewLoc the location of the new explicit specialization or
4018/// instantiation.
4019///
4020/// \param NewTSK the kind of the new explicit specialization or instantiation.
4021///
4022/// \param PrevDecl the previous declaration of the entity.
4023///
4024/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4025///
4026/// \param PrevPointOfInstantiation if valid, indicates where the previus
4027/// declaration was instantiated (either implicitly or explicitly).
4028///
4029/// \param SuppressNew will be set to true to indicate that the new
4030/// specialization or instantiation has no effect and should be ignored.
4031///
4032/// \returns true if there was an error that should prevent the introduction of
4033/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004034bool
4035Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4036 TemplateSpecializationKind NewTSK,
4037 NamedDecl *PrevDecl,
4038 TemplateSpecializationKind PrevTSK,
4039 SourceLocation PrevPointOfInstantiation,
4040 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004041 SuppressNew = false;
4042
4043 switch (NewTSK) {
4044 case TSK_Undeclared:
4045 case TSK_ImplicitInstantiation:
4046 assert(false && "Don't check implicit instantiations here");
4047 return false;
4048
4049 case TSK_ExplicitSpecialization:
4050 switch (PrevTSK) {
4051 case TSK_Undeclared:
4052 case TSK_ExplicitSpecialization:
4053 // Okay, we're just specializing something that is either already
4054 // explicitly specialized or has merely been mentioned without any
4055 // instantiation.
4056 return false;
4057
4058 case TSK_ImplicitInstantiation:
4059 if (PrevPointOfInstantiation.isInvalid()) {
4060 // The declaration itself has not actually been instantiated, so it is
4061 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004062 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004063 return false;
4064 }
4065 // Fall through
4066
4067 case TSK_ExplicitInstantiationDeclaration:
4068 case TSK_ExplicitInstantiationDefinition:
4069 assert((PrevTSK == TSK_ImplicitInstantiation ||
4070 PrevPointOfInstantiation.isValid()) &&
4071 "Explicit instantiation without point of instantiation?");
4072
4073 // C++ [temp.expl.spec]p6:
4074 // If a template, a member template or the member of a class template
4075 // is explicitly specialized then that specialization shall be declared
4076 // before the first use of that specialization that would cause an
4077 // implicit instantiation to take place, in every translation unit in
4078 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004079 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4080 // Is there any previous explicit specialization declaration?
4081 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4082 return false;
4083 }
4084
Douglas Gregor1d957a32009-10-27 18:42:08 +00004085 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004086 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004087 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004088 << (PrevTSK != TSK_ImplicitInstantiation);
4089
4090 return true;
4091 }
4092 break;
4093
4094 case TSK_ExplicitInstantiationDeclaration:
4095 switch (PrevTSK) {
4096 case TSK_ExplicitInstantiationDeclaration:
4097 // This explicit instantiation declaration is redundant (that's okay).
4098 SuppressNew = true;
4099 return false;
4100
4101 case TSK_Undeclared:
4102 case TSK_ImplicitInstantiation:
4103 // We're explicitly instantiating something that may have already been
4104 // implicitly instantiated; that's fine.
4105 return false;
4106
4107 case TSK_ExplicitSpecialization:
4108 // C++0x [temp.explicit]p4:
4109 // For a given set of template parameters, if an explicit instantiation
4110 // of a template appears after a declaration of an explicit
4111 // specialization for that template, the explicit instantiation has no
4112 // effect.
John McCall6b21eb52010-03-02 23:09:38 +00004113 SuppressNew = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004114 return false;
4115
4116 case TSK_ExplicitInstantiationDefinition:
4117 // C++0x [temp.explicit]p10:
4118 // If an entity is the subject of both an explicit instantiation
4119 // declaration and an explicit instantiation definition in the same
4120 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004121 Diag(NewLoc,
4122 diag::err_explicit_instantiation_declaration_after_definition);
4123 Diag(PrevPointOfInstantiation,
4124 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004125 assert(PrevPointOfInstantiation.isValid() &&
4126 "Explicit instantiation without point of instantiation?");
4127 SuppressNew = true;
4128 return false;
4129 }
4130 break;
4131
4132 case TSK_ExplicitInstantiationDefinition:
4133 switch (PrevTSK) {
4134 case TSK_Undeclared:
4135 case TSK_ImplicitInstantiation:
4136 // We're explicitly instantiating something that may have already been
4137 // implicitly instantiated; that's fine.
4138 return false;
4139
4140 case TSK_ExplicitSpecialization:
4141 // C++ DR 259, C++0x [temp.explicit]p4:
4142 // For a given set of template parameters, if an explicit
4143 // instantiation of a template appears after a declaration of
4144 // an explicit specialization for that template, the explicit
4145 // instantiation has no effect.
4146 //
4147 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004148 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004149 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004150 if (!getLangOptions().CPlusPlus0x) {
4151 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004152 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004153 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004154 diag::note_previous_template_specialization);
4155 }
4156 SuppressNew = true;
4157 return false;
4158
4159 case TSK_ExplicitInstantiationDeclaration:
4160 // We're explicity instantiating a definition for something for which we
4161 // were previously asked to suppress instantiations. That's fine.
4162 return false;
4163
4164 case TSK_ExplicitInstantiationDefinition:
4165 // C++0x [temp.spec]p5:
4166 // For a given template and a given set of template-arguments,
4167 // - an explicit instantiation definition shall appear at most once
4168 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004169 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004170 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004171 Diag(PrevPointOfInstantiation,
4172 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004173 SuppressNew = true;
4174 return false;
4175 }
4176 break;
4177 }
4178
4179 assert(false && "Missing specialization/instantiation case?");
4180
4181 return false;
4182}
4183
John McCallb9c78482010-04-08 09:05:18 +00004184/// \brief Perform semantic analysis for the given dependent function
4185/// template specialization. The only possible way to get a dependent
4186/// function template specialization is with a friend declaration,
4187/// like so:
4188///
4189/// template <class T> void foo(T);
4190/// template <class T> class A {
4191/// friend void foo<>(T);
4192/// };
4193///
4194/// There really isn't any useful analysis we can do here, so we
4195/// just store the information.
4196bool
4197Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4198 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4199 LookupResult &Previous) {
4200 // Remove anything from Previous that isn't a function template in
4201 // the correct context.
4202 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4203 LookupResult::Filter F = Previous.makeFilter();
4204 while (F.hasNext()) {
4205 NamedDecl *D = F.next()->getUnderlyingDecl();
4206 if (!isa<FunctionTemplateDecl>(D) ||
4207 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4208 F.erase();
4209 }
4210 F.done();
4211
4212 // Should this be diagnosed here?
4213 if (Previous.empty()) return true;
4214
4215 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4216 ExplicitTemplateArgs);
4217 return false;
4218}
4219
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004220/// \brief Perform semantic analysis for the given function template
4221/// specialization.
4222///
4223/// This routine performs all of the semantic analysis required for an
4224/// explicit function template specialization. On successful completion,
4225/// the function declaration \p FD will become a function template
4226/// specialization.
4227///
4228/// \param FD the function declaration, which will be updated to become a
4229/// function template specialization.
4230///
4231/// \param HasExplicitTemplateArgs whether any template arguments were
4232/// explicitly provided.
4233///
4234/// \param LAngleLoc the location of the left angle bracket ('<'), if
4235/// template arguments were explicitly provided.
4236///
4237/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4238/// if any.
4239///
4240/// \param NumExplicitTemplateArgs the number of explicitly-provided template
4241/// arguments. This number may be zero even when HasExplicitTemplateArgs is
4242/// true as in, e.g., \c void sort<>(char*, char*);
4243///
4244/// \param RAngleLoc the location of the right angle bracket ('>'), if
4245/// template arguments were explicitly provided.
4246///
4247/// \param PrevDecl the set of declarations that
4248bool
4249Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004250 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004251 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004252 // The set of function template specializations that could match this
4253 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004254 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004255
4256 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004257 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4258 I != E; ++I) {
4259 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4260 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004261 // Only consider templates found within the same semantic lookup scope as
4262 // FD.
4263 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4264 continue;
4265
4266 // C++ [temp.expl.spec]p11:
4267 // A trailing template-argument can be left unspecified in the
4268 // template-id naming an explicit function template specialization
4269 // provided it can be deduced from the function argument type.
4270 // Perform template argument deduction to determine whether we may be
4271 // specializing this template.
4272 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004273 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004274 FunctionDecl *Specialization = 0;
4275 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004276 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004277 FD->getType(),
4278 Specialization,
4279 Info)) {
4280 // FIXME: Template argument deduction failed; record why it failed, so
4281 // that we can provide nifty diagnostics.
4282 (void)TDK;
4283 continue;
4284 }
4285
4286 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004287 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004288 }
4289 }
4290
Douglas Gregor5de279c2009-09-26 03:41:46 +00004291 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004292 UnresolvedSetIterator Result
4293 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4294 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004295 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004296 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004297 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004298 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004299 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004300 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004301 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004302
4303 // Ignore access information; it doesn't figure into redeclaration checking.
4304 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004305 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004306
4307 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004308 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004309
4310 // If this is a friend declaration, then we're not really declaring
4311 // an explicit specialization.
4312 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004313
Douglas Gregor54888652009-10-07 00:13:32 +00004314 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004315 if (!isFriend &&
4316 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004317 Specialization->getPrimaryTemplate(),
4318 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004319 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004320 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004321
4322 // C++ [temp.expl.spec]p6:
4323 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004324 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004325 // before the first use of that specialization that would cause an implicit
4326 // instantiation to take place, in every translation unit in which such a
4327 // use occurs; no diagnostic is required.
4328 FunctionTemplateSpecializationInfo *SpecInfo
4329 = Specialization->getTemplateSpecializationInfo();
4330 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004331
4332 bool SuppressNew = false;
John McCall816d75b2010-03-24 07:46:06 +00004333 if (!isFriend &&
4334 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004335 TSK_ExplicitSpecialization,
4336 Specialization,
4337 SpecInfo->getTemplateSpecializationKind(),
4338 SpecInfo->getPointOfInstantiation(),
4339 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004340 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004341
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004342 // Mark the prior declaration as an explicit specialization, so that later
4343 // clients know that this is an explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004344 if (!isFriend)
4345 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004346
4347 // Turn the given function declaration into a function template
4348 // specialization, with the template arguments from the previous
4349 // specialization.
Douglas Gregord5058122010-02-11 01:19:42 +00004350 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004351 new (Context) TemplateArgumentList(
4352 *Specialization->getTemplateSpecializationArgs()),
4353 /*InsertPos=*/0,
John McCall816d75b2010-03-24 07:46:06 +00004354 SpecInfo->getTemplateSpecializationKind());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004355
4356 // The "previous declaration" for this function template specialization is
4357 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004358 Previous.clear();
4359 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004360 return false;
4361}
4362
Douglas Gregor86d142a2009-10-08 07:24:58 +00004363/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004364/// specialization.
4365///
4366/// This routine performs all of the semantic analysis required for an
4367/// explicit member function specialization. On successful completion,
4368/// the function declaration \p FD will become a member function
4369/// specialization.
4370///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004371/// \param Member the member declaration, which will be updated to become a
4372/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004373///
John McCall1f82f242009-11-18 22:49:29 +00004374/// \param Previous the set of declarations, one of which may be specialized
4375/// by this function specialization; the set will be modified to contain the
4376/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004377bool
John McCall1f82f242009-11-18 22:49:29 +00004378Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004379 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004380
Douglas Gregor86d142a2009-10-08 07:24:58 +00004381 // Try to find the member we are instantiating.
4382 NamedDecl *Instantiation = 0;
4383 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004384 MemberSpecializationInfo *MSInfo = 0;
4385
John McCall1f82f242009-11-18 22:49:29 +00004386 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004387 // Nowhere to look anyway.
4388 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004389 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4390 I != E; ++I) {
4391 NamedDecl *D = (*I)->getUnderlyingDecl();
4392 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004393 if (Context.hasSameType(Function->getType(), Method->getType())) {
4394 Instantiation = Method;
4395 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004396 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004397 break;
4398 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004399 }
4400 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004401 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004402 VarDecl *PrevVar;
4403 if (Previous.isSingleResult() &&
4404 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004405 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004406 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004407 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004408 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004409 }
4410 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004411 CXXRecordDecl *PrevRecord;
4412 if (Previous.isSingleResult() &&
4413 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4414 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004415 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004416 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004417 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004418 }
4419
4420 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004421 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004422 // specializations are always out-of-line, the caller will complain about
4423 // this mismatch later.
4424 return false;
4425 }
John McCalle820e5e2010-04-13 20:37:33 +00004426
4427 // If this is a friend, just bail out here before we start turning
4428 // things into explicit specializations.
4429 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4430 // Preserve instantiation information.
4431 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4432 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4433 cast<CXXMethodDecl>(InstantiatedFrom),
4434 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4435 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4436 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4437 cast<CXXRecordDecl>(InstantiatedFrom),
4438 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4439 }
4440
4441 Previous.clear();
4442 Previous.addDecl(Instantiation);
4443 return false;
4444 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004445
Douglas Gregor86d142a2009-10-08 07:24:58 +00004446 // Make sure that this is a specialization of a member.
4447 if (!InstantiatedFrom) {
4448 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4449 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004450 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4451 return true;
4452 }
4453
Douglas Gregor06db9f52009-10-12 20:18:28 +00004454 // C++ [temp.expl.spec]p6:
4455 // If a template, a member template or the member of a class template is
4456 // explicitly specialized then that spe- cialization shall be declared
4457 // before the first use of that specialization that would cause an implicit
4458 // instantiation to take place, in every translation unit in which such a
4459 // use occurs; no diagnostic is required.
4460 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004461
4462 bool SuppressNew = false;
4463 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4464 TSK_ExplicitSpecialization,
4465 Instantiation,
4466 MSInfo->getTemplateSpecializationKind(),
4467 MSInfo->getPointOfInstantiation(),
4468 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004469 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004470
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004471 // Check the scope of this explicit specialization.
4472 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004473 InstantiatedFrom,
4474 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004475 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004476 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004477
Douglas Gregor86d142a2009-10-08 07:24:58 +00004478 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004479 // the original declaration to note that it is an explicit specialization
4480 // (if it was previously an implicit instantiation). This latter step
4481 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004482 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004483 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4484 if (InstantiationFunction->getTemplateSpecializationKind() ==
4485 TSK_ImplicitInstantiation) {
4486 InstantiationFunction->setTemplateSpecializationKind(
4487 TSK_ExplicitSpecialization);
4488 InstantiationFunction->setLocation(Member->getLocation());
4489 }
4490
Douglas Gregor86d142a2009-10-08 07:24:58 +00004491 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4492 cast<CXXMethodDecl>(InstantiatedFrom),
4493 TSK_ExplicitSpecialization);
4494 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004495 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4496 if (InstantiationVar->getTemplateSpecializationKind() ==
4497 TSK_ImplicitInstantiation) {
4498 InstantiationVar->setTemplateSpecializationKind(
4499 TSK_ExplicitSpecialization);
4500 InstantiationVar->setLocation(Member->getLocation());
4501 }
4502
Douglas Gregor86d142a2009-10-08 07:24:58 +00004503 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4504 cast<VarDecl>(InstantiatedFrom),
4505 TSK_ExplicitSpecialization);
4506 } else {
4507 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004508 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4509 if (InstantiationClass->getTemplateSpecializationKind() ==
4510 TSK_ImplicitInstantiation) {
4511 InstantiationClass->setTemplateSpecializationKind(
4512 TSK_ExplicitSpecialization);
4513 InstantiationClass->setLocation(Member->getLocation());
4514 }
4515
Douglas Gregor86d142a2009-10-08 07:24:58 +00004516 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004517 cast<CXXRecordDecl>(InstantiatedFrom),
4518 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004519 }
4520
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004521 // Save the caller the trouble of having to figure out which declaration
4522 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004523 Previous.clear();
4524 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004525 return false;
4526}
4527
Douglas Gregore47f5a72009-10-14 23:41:34 +00004528/// \brief Check the scope of an explicit instantiation.
4529static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4530 SourceLocation InstLoc,
4531 bool WasQualifiedName) {
4532 DeclContext *ExpectedContext
4533 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4534 DeclContext *CurContext = S.CurContext->getLookupContext();
4535
4536 // C++0x [temp.explicit]p2:
4537 // An explicit instantiation shall appear in an enclosing namespace of its
4538 // template.
4539 //
4540 // This is DR275, which we do not retroactively apply to C++98/03.
4541 if (S.getLangOptions().CPlusPlus0x &&
4542 !CurContext->Encloses(ExpectedContext)) {
4543 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004544 S.Diag(InstLoc,
4545 S.getLangOptions().CPlusPlus0x?
4546 diag::err_explicit_instantiation_out_of_scope
4547 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004548 << D << NS;
4549 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004550 S.Diag(InstLoc,
4551 S.getLangOptions().CPlusPlus0x?
4552 diag::err_explicit_instantiation_must_be_global
4553 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004554 << D;
4555 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4556 return;
4557 }
4558
4559 // C++0x [temp.explicit]p2:
4560 // If the name declared in the explicit instantiation is an unqualified
4561 // name, the explicit instantiation shall appear in the namespace where
4562 // its template is declared or, if that namespace is inline (7.3.1), any
4563 // namespace from its enclosing namespace set.
4564 if (WasQualifiedName)
4565 return;
4566
4567 if (CurContext->Equals(ExpectedContext))
4568 return;
4569
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004570 S.Diag(InstLoc,
4571 S.getLangOptions().CPlusPlus0x?
4572 diag::err_explicit_instantiation_unqualified_wrong_namespace
4573 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004574 << D << ExpectedContext;
4575 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4576}
4577
4578/// \brief Determine whether the given scope specifier has a template-id in it.
4579static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4580 if (!SS.isSet())
4581 return false;
4582
4583 // C++0x [temp.explicit]p2:
4584 // If the explicit instantiation is for a member function, a member class
4585 // or a static data member of a class template specialization, the name of
4586 // the class template specialization in the qualified-id for the member
4587 // name shall be a simple-template-id.
4588 //
4589 // C++98 has the same restriction, just worded differently.
4590 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4591 NNS; NNS = NNS->getPrefix())
4592 if (Type *T = NNS->getAsType())
4593 if (isa<TemplateSpecializationType>(T))
4594 return true;
4595
4596 return false;
4597}
4598
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004599// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004600// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004601Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004602Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004603 SourceLocation ExternLoc,
4604 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004605 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004606 SourceLocation KWLoc,
4607 const CXXScopeSpec &SS,
4608 TemplateTy TemplateD,
4609 SourceLocation TemplateNameLoc,
4610 SourceLocation LAngleLoc,
4611 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004612 SourceLocation RAngleLoc,
4613 AttributeList *Attr) {
4614 // Find the class template we're specializing
4615 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004616 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004617 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4618
4619 // Check that the specialization uses the same tag kind as the
4620 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004621 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4622 assert(Kind != TTK_Enum &&
4623 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004624 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004625 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004626 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004627 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004628 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004629 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004630 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004631 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004632 diag::note_previous_use);
4633 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4634 }
4635
Douglas Gregore47f5a72009-10-14 23:41:34 +00004636 // C++0x [temp.explicit]p2:
4637 // There are two forms of explicit instantiation: an explicit instantiation
4638 // definition and an explicit instantiation declaration. An explicit
4639 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004640 TemplateSpecializationKind TSK
4641 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4642 : TSK_ExplicitInstantiationDeclaration;
4643
Douglas Gregora1f49972009-05-13 00:25:59 +00004644 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004645 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004646 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004647
4648 // Check that the template argument list is well-formed for this
4649 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004650 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4651 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004652 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4653 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004654 return true;
4655
Mike Stump11289f42009-09-09 15:08:12 +00004656 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004657 ClassTemplate->getTemplateParameters()->size()) &&
4658 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004659
Douglas Gregora1f49972009-05-13 00:25:59 +00004660 // Find the class template specialization declaration that
4661 // corresponds to these arguments.
4662 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004663 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004664 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004665 Converted.flatSize(),
4666 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004667 void *InsertPos = 0;
4668 ClassTemplateSpecializationDecl *PrevDecl
4669 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4670
Douglas Gregor54888652009-10-07 00:13:32 +00004671 // C++0x [temp.explicit]p2:
4672 // [...] An explicit instantiation shall appear in an enclosing
4673 // namespace of its template. [...]
4674 //
4675 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004676 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4677 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004678
Douglas Gregora1f49972009-05-13 00:25:59 +00004679 ClassTemplateSpecializationDecl *Specialization = 0;
4680
Douglas Gregor0681a352009-11-25 06:01:46 +00004681 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004682 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004683 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004684 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004685 PrevDecl,
4686 PrevDecl->getSpecializationKind(),
4687 PrevDecl->getPointOfInstantiation(),
4688 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004689 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004690
Douglas Gregor12e49d32009-10-15 22:53:21 +00004691 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004692 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004693
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004694 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4695 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4696 // Since the only prior class template specialization with these
4697 // arguments was referenced but not declared, reuse that
4698 // declaration node as our own, updating its source location to
4699 // reflect our new declaration.
4700 Specialization = PrevDecl;
4701 Specialization->setLocation(TemplateNameLoc);
4702 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004703 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004704 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004705 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004706
4707 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004708 // Create a new class template specialization declaration node for
4709 // this explicit specialization.
4710 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004711 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004712 ClassTemplate->getDeclContext(),
4713 TemplateNameLoc,
4714 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004715 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004716 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004717
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004718 if (PrevDecl) {
4719 // Remove the previous declaration from the folding set, since we want
4720 // to introduce a new declaration.
4721 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4722 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4723 }
4724
4725 // Insert the new specialization.
4726 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004727 }
4728
4729 // Build the fully-sugared type for this explicit instantiation as
4730 // the user wrote in the explicit instantiation itself. This means
4731 // that we'll pretty-print the type retrieved from the
4732 // specialization's declaration the way that the user actually wrote
4733 // the explicit instantiation, rather than formatting the name based
4734 // on the "canonical" representation used to store the template
4735 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004736 TypeSourceInfo *WrittenTy
4737 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4738 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004739 Context.getTypeDeclType(Specialization));
4740 Specialization->setTypeAsWritten(WrittenTy);
4741 TemplateArgsIn.release();
4742
Douglas Gregor0681a352009-11-25 06:01:46 +00004743 if (!ReusedDecl) {
4744 // Add the explicit instantiation into its lexical context. However,
4745 // since explicit instantiations are never found by name lookup, we
4746 // just put it into the declaration context directly.
4747 Specialization->setLexicalDeclContext(CurContext);
4748 CurContext->addDecl(Specialization);
4749 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004750
4751 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004752 // A definition of a class template or class member template
4753 // shall be in scope at the point of the explicit instantiation of
4754 // the class template or class member template.
4755 //
4756 // This check comes when we actually try to perform the
4757 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004758 ClassTemplateSpecializationDecl *Def
4759 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004760 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004761 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004762 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004763
4764 // Instantiate the members of this class template specialization.
4765 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004766 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004767 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004768 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4769
4770 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4771 // TSK_ExplicitInstantiationDefinition
4772 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4773 TSK == TSK_ExplicitInstantiationDefinition)
4774 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004775
Douglas Gregor12e49d32009-10-15 22:53:21 +00004776 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004777 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004778
4779 return DeclPtrTy::make(Specialization);
4780}
4781
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004782// Explicit instantiation of a member class of a class template.
4783Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004784Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004785 SourceLocation ExternLoc,
4786 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004787 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004788 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004789 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004790 IdentifierInfo *Name,
4791 SourceLocation NameLoc,
4792 AttributeList *Attr) {
4793
Douglas Gregord6ab8742009-05-28 23:31:59 +00004794 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004795 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004796 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004797 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004798 MultiTemplateParamsArg(*this, 0, 0),
4799 Owned, IsDependent);
4800 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4801
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004802 if (!TagD)
4803 return true;
4804
4805 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4806 if (Tag->isEnum()) {
4807 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4808 << Context.getTypeDeclType(Tag);
4809 return true;
4810 }
4811
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004812 if (Tag->isInvalidDecl())
4813 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004814
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004815 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4816 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4817 if (!Pattern) {
4818 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4819 << Context.getTypeDeclType(Record);
4820 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4821 return true;
4822 }
4823
Douglas Gregore47f5a72009-10-14 23:41:34 +00004824 // C++0x [temp.explicit]p2:
4825 // If the explicit instantiation is for a class or member class, the
4826 // elaborated-type-specifier in the declaration shall include a
4827 // simple-template-id.
4828 //
4829 // C++98 has the same restriction, just worded differently.
4830 if (!ScopeSpecifierHasTemplateId(SS))
4831 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4832 << Record << SS.getRange();
4833
4834 // C++0x [temp.explicit]p2:
4835 // There are two forms of explicit instantiation: an explicit instantiation
4836 // definition and an explicit instantiation declaration. An explicit
4837 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004838 TemplateSpecializationKind TSK
4839 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4840 : TSK_ExplicitInstantiationDeclaration;
4841
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004842 // C++0x [temp.explicit]p2:
4843 // [...] An explicit instantiation shall appear in an enclosing
4844 // namespace of its template. [...]
4845 //
4846 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004847 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004848
4849 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004850 CXXRecordDecl *PrevDecl
4851 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004852 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004853 PrevDecl = Record;
4854 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004855 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4856 bool SuppressNew = false;
4857 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004858 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004859 PrevDecl,
4860 MSInfo->getTemplateSpecializationKind(),
4861 MSInfo->getPointOfInstantiation(),
4862 SuppressNew))
4863 return true;
4864 if (SuppressNew)
4865 return TagD;
4866 }
4867
Douglas Gregor12e49d32009-10-15 22:53:21 +00004868 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004869 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004870 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004871 // C++ [temp.explicit]p3:
4872 // A definition of a member class of a class template shall be in scope
4873 // at the point of an explicit instantiation of the member class.
4874 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004875 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004876 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004877 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4878 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004879 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4880 << Pattern;
4881 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004882 } else {
4883 if (InstantiateClass(NameLoc, Record, Def,
4884 getTemplateInstantiationArgs(Record),
4885 TSK))
4886 return true;
4887
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004888 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004889 if (!RecordDef)
4890 return true;
4891 }
4892 }
4893
4894 // Instantiate all of the members of the class.
4895 InstantiateClassMembers(NameLoc, RecordDef,
4896 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004897
Mike Stump87c57ac2009-05-16 07:39:55 +00004898 // FIXME: We don't have any representation for explicit instantiations of
4899 // member classes. Such a representation is not needed for compilation, but it
4900 // should be available for clients that want to see all of the declarations in
4901 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004902 return TagD;
4903}
4904
Douglas Gregor450f00842009-09-25 18:43:00 +00004905Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4906 SourceLocation ExternLoc,
4907 SourceLocation TemplateLoc,
4908 Declarator &D) {
4909 // Explicit instantiations always require a name.
4910 DeclarationName Name = GetNameForDeclarator(D);
4911 if (!Name) {
4912 if (!D.isInvalidType())
4913 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4914 diag::err_explicit_instantiation_requires_name)
4915 << D.getDeclSpec().getSourceRange()
4916 << D.getSourceRange();
4917
4918 return true;
4919 }
4920
4921 // The scope passed in may not be a decl scope. Zip up the scope tree until
4922 // we find one that is.
4923 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4924 (S->getFlags() & Scope::TemplateParamScope) != 0)
4925 S = S->getParent();
4926
4927 // Determine the type of the declaration.
4928 QualType R = GetTypeForDeclarator(D, S, 0);
4929 if (R.isNull())
4930 return true;
4931
4932 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4933 // Cannot explicitly instantiate a typedef.
4934 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4935 << Name;
4936 return true;
4937 }
4938
Douglas Gregor3c74d412009-10-14 20:14:33 +00004939 // C++0x [temp.explicit]p1:
4940 // [...] An explicit instantiation of a function template shall not use the
4941 // inline or constexpr specifiers.
4942 // Presumably, this also applies to member functions of class templates as
4943 // well.
4944 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4945 Diag(D.getDeclSpec().getInlineSpecLoc(),
4946 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00004947 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004948
4949 // FIXME: check for constexpr specifier.
4950
Douglas Gregore47f5a72009-10-14 23:41:34 +00004951 // C++0x [temp.explicit]p2:
4952 // There are two forms of explicit instantiation: an explicit instantiation
4953 // definition and an explicit instantiation declaration. An explicit
4954 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004955 TemplateSpecializationKind TSK
4956 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4957 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004958
John McCall27b18f82009-11-17 02:14:36 +00004959 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4960 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004961
4962 if (!R->isFunctionType()) {
4963 // C++ [temp.explicit]p1:
4964 // A [...] static data member of a class template can be explicitly
4965 // instantiated from the member definition associated with its class
4966 // template.
John McCall27b18f82009-11-17 02:14:36 +00004967 if (Previous.isAmbiguous())
4968 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004969
John McCall67c00872009-12-02 08:25:40 +00004970 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00004971 if (!Prev || !Prev->isStaticDataMember()) {
4972 // We expect to see a data data member here.
4973 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4974 << Name;
4975 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4976 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004977 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004978 return true;
4979 }
4980
4981 if (!Prev->getInstantiatedFromStaticDataMember()) {
4982 // FIXME: Check for explicit specialization?
4983 Diag(D.getIdentifierLoc(),
4984 diag::err_explicit_instantiation_data_member_not_instantiated)
4985 << Prev;
4986 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4987 // FIXME: Can we provide a note showing where this was declared?
4988 return true;
4989 }
4990
Douglas Gregore47f5a72009-10-14 23:41:34 +00004991 // C++0x [temp.explicit]p2:
4992 // If the explicit instantiation is for a member function, a member class
4993 // or a static data member of a class template specialization, the name of
4994 // the class template specialization in the qualified-id for the member
4995 // name shall be a simple-template-id.
4996 //
4997 // C++98 has the same restriction, just worded differently.
4998 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4999 Diag(D.getIdentifierLoc(),
5000 diag::err_explicit_instantiation_without_qualified_id)
5001 << Prev << D.getCXXScopeSpec().getRange();
5002
5003 // Check the scope of this explicit instantiation.
5004 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5005
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005006 // Verify that it is okay to explicitly instantiate here.
5007 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5008 assert(MSInfo && "Missing static data member specialization info?");
5009 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005010 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005011 MSInfo->getTemplateSpecializationKind(),
5012 MSInfo->getPointOfInstantiation(),
5013 SuppressNew))
5014 return true;
5015 if (SuppressNew)
5016 return DeclPtrTy();
5017
Douglas Gregor450f00842009-09-25 18:43:00 +00005018 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005019 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005020 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00005021 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5022 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00005023
5024 // FIXME: Create an ExplicitInstantiation node?
5025 return DeclPtrTy();
5026 }
5027
Douglas Gregor0e876e02009-09-25 23:53:26 +00005028 // If the declarator is a template-id, translate the parser's template
5029 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005030 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005031 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005032 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5033 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005034 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5035 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005036 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5037 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005038 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005039 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005040 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005041 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005042 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005043
Douglas Gregor450f00842009-09-25 18:43:00 +00005044 // C++ [temp.explicit]p1:
5045 // A [...] function [...] can be explicitly instantiated from its template.
5046 // A member function [...] of a class template can be explicitly
5047 // instantiated from the member definition associated with its class
5048 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005049 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005050 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5051 P != PEnd; ++P) {
5052 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005053 if (!HasExplicitTemplateArgs) {
5054 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5055 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5056 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005057
John McCall58cc69d2010-01-27 01:50:18 +00005058 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005059 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5060 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005061 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005062 }
5063 }
5064
5065 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5066 if (!FunTmpl)
5067 continue;
5068
John McCallbc077cf2010-02-08 23:07:23 +00005069 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005070 FunctionDecl *Specialization = 0;
5071 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005072 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005073 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005074 R, Specialization, Info)) {
5075 // FIXME: Keep track of almost-matches?
5076 (void)TDK;
5077 continue;
5078 }
5079
John McCall58cc69d2010-01-27 01:50:18 +00005080 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005081 }
5082
5083 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005084 UnresolvedSetIterator Result
5085 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005086 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005087 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5088 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5089 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005090
John McCall58cc69d2010-01-27 01:50:18 +00005091 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005092 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005093
5094 // Ignore access control bits, we don't need them for redeclaration checking.
5095 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005096
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005097 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005098 Diag(D.getIdentifierLoc(),
5099 diag::err_explicit_instantiation_member_function_not_instantiated)
5100 << Specialization
5101 << (Specialization->getTemplateSpecializationKind() ==
5102 TSK_ExplicitSpecialization);
5103 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5104 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005105 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005106
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005107 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005108 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5109 PrevDecl = Specialization;
5110
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005111 if (PrevDecl) {
5112 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005113 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005114 PrevDecl,
5115 PrevDecl->getTemplateSpecializationKind(),
5116 PrevDecl->getPointOfInstantiation(),
5117 SuppressNew))
5118 return true;
5119
5120 // FIXME: We may still want to build some representation of this
5121 // explicit specialization.
5122 if (SuppressNew)
5123 return DeclPtrTy();
5124 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005125
5126 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005127
5128 if (TSK == TSK_ExplicitInstantiationDefinition)
5129 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5130 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005131
Douglas Gregore47f5a72009-10-14 23:41:34 +00005132 // C++0x [temp.explicit]p2:
5133 // If the explicit instantiation is for a member function, a member class
5134 // or a static data member of a class template specialization, the name of
5135 // the class template specialization in the qualified-id for the member
5136 // name shall be a simple-template-id.
5137 //
5138 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005139 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005140 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005141 D.getCXXScopeSpec().isSet() &&
5142 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5143 Diag(D.getIdentifierLoc(),
5144 diag::err_explicit_instantiation_without_qualified_id)
5145 << Specialization << D.getCXXScopeSpec().getRange();
5146
5147 CheckExplicitInstantiationScope(*this,
5148 FunTmpl? (NamedDecl *)FunTmpl
5149 : Specialization->getInstantiatedFromMemberFunction(),
5150 D.getIdentifierLoc(),
5151 D.getCXXScopeSpec().isSet());
5152
Douglas Gregor450f00842009-09-25 18:43:00 +00005153 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5154 return DeclPtrTy();
5155}
5156
Douglas Gregor333489b2009-03-27 23:10:48 +00005157Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005158Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5159 const CXXScopeSpec &SS, IdentifierInfo *Name,
5160 SourceLocation TagLoc, SourceLocation NameLoc) {
5161 // This has to hold, because SS is expected to be defined.
5162 assert(Name && "Expected a name in a dependent tag");
5163
5164 NestedNameSpecifier *NNS
5165 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5166 if (!NNS)
5167 return true;
5168
Abramo Bagnara6150c882010-05-11 21:36:43 +00005169 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005170
Douglas Gregorba41d012010-04-24 16:38:41 +00005171 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5172 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005173 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005174 return true;
5175 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005176
5177 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5178 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
John McCall7f41d982009-09-11 04:59:25 +00005179}
5180
John McCall99b2fe52010-04-29 23:50:39 +00005181static void FillTypeLoc(DependentNameTypeLoc TL,
5182 SourceLocation TypenameLoc,
5183 SourceRange QualifierRange) {
5184 // FIXME: typename, qualifier range
5185 TL.setNameLoc(TypenameLoc);
5186}
5187
Abramo Bagnara6150c882010-05-11 21:36:43 +00005188static void FillTypeLoc(ElaboratedTypeLoc TL,
John McCall99b2fe52010-04-29 23:50:39 +00005189 SourceLocation TypenameLoc,
5190 SourceRange QualifierRange) {
5191 // FIXME: typename, qualifier range
5192 TL.setNameLoc(TypenameLoc);
5193}
5194
John McCall7f41d982009-09-11 04:59:25 +00005195Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00005196Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5197 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005198 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005199 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5200 if (!NNS)
5201 return true;
5202
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005203 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
5204 SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005205 if (T.isNull())
5206 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005207
5208 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5209 if (isa<DependentNameType>(T)) {
5210 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
5211 // FIXME: fill inner type loc
5212 FillTypeLoc(TL, TypenameLoc, SS.getRange());
5213 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005214 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall99b2fe52010-04-29 23:50:39 +00005215 // FIXME: fill inner type loc
5216 FillTypeLoc(TL, TypenameLoc, SS.getRange());
5217 }
5218
5219 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor333489b2009-03-27 23:10:48 +00005220}
5221
Douglas Gregordce2b622009-04-01 00:28:59 +00005222Sema::TypeResult
5223Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5224 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005225 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005226 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00005227 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00005228 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00005229 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00005230 assert(TemplateId && "Expected a template specialization type");
5231
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005232 if (computeDeclContext(SS, false)) {
5233 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005234 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005235 // track of the nested-name-specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00005236 T = Context.getElaboratedType(ETK_Typename, NNS, T);
John McCall99b2fe52010-04-29 23:50:39 +00005237 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00005238 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall99b2fe52010-04-29 23:50:39 +00005239 // FIXME: fill inner type loc
5240 FillTypeLoc(TL, TypenameLoc, SS.getRange());
5241 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005242 }
Mike Stump11289f42009-09-09 15:08:12 +00005243
John McCall99b2fe52010-04-29 23:50:39 +00005244 T = Context.getDependentNameType(ETK_Typename, NNS, TemplateId);
5245 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5246 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
5247 // FIXME: fill inner type loc
5248 FillTypeLoc(TL, TypenameLoc, SS.getRange());
5249 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00005250}
5251
Douglas Gregor333489b2009-03-27 23:10:48 +00005252/// \brief Build the type that describes a C++ typename specifier,
5253/// e.g., "typename T::type".
5254QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005255Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5256 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Douglas Gregor333489b2009-03-27 23:10:48 +00005257 SourceRange Range) {
John McCall0b66eb32010-05-01 00:40:08 +00005258 CXXScopeSpec SS;
5259 SS.setScopeRep(NNS);
5260 SS.setRange(Range);
Douglas Gregor333489b2009-03-27 23:10:48 +00005261
John McCall0b66eb32010-05-01 00:40:08 +00005262 DeclContext *Ctx = computeDeclContext(SS);
5263 if (!Ctx) {
5264 // If the nested-name-specifier is dependent and couldn't be
5265 // resolved to a type, build a typename type.
5266 assert(NNS->isDependent());
5267 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005268 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005269
John McCall0b66eb32010-05-01 00:40:08 +00005270 // If the nested-name-specifier refers to the current instantiation,
5271 // the "typename" keyword itself is superfluous. In C++03, the
5272 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5273 // allows such extraneous "typename" keywords, and we retroactively
5274 // apply this DR to C++03 code. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005275
John McCall0b66eb32010-05-01 00:40:08 +00005276 if (RequireCompleteDeclContext(SS, Ctx))
5277 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005278
5279 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00005280 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
5281 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005282 unsigned DiagID = 0;
5283 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005284 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005285 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005286 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005287 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005288
5289 case LookupResult::NotFoundInCurrentInstantiation:
5290 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005291 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005292
5293 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00005294 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005295 // We found a type. Build an ElaboratedType, since the
5296 // typename-specifier was just sugar.
5297 return Context.getElaboratedType(ETK_Typename, NNS,
5298 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005299 }
5300
5301 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005302 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005303 break;
5304
John McCalle61f2ba2009-11-18 02:36:19 +00005305 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005306 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005307 return QualType();
5308
Douglas Gregor333489b2009-03-27 23:10:48 +00005309 case LookupResult::FoundOverloaded:
5310 DiagID = diag::err_typename_nested_not_type;
5311 Referenced = *Result.begin();
5312 break;
5313
John McCall6538c932009-10-10 05:48:19 +00005314 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005315 return QualType();
5316 }
5317
5318 // If we get here, it's because name lookup did not find a
5319 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00005320 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005321 if (Referenced)
5322 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5323 << Name;
5324 return QualType();
5325}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005326
5327namespace {
5328 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005329 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005330 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005331 SourceLocation Loc;
5332 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005333
Douglas Gregor15acfb92009-08-06 16:20:37 +00005334 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005335 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5336
Mike Stump11289f42009-09-09 15:08:12 +00005337 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005338 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005339 DeclarationName Entity)
5340 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005341 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005342
5343 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005344 /// transformed.
5345 ///
5346 /// For the purposes of type reconstruction, a type has already been
5347 /// transformed if it is NULL or if it is not dependent.
5348 bool AlreadyTransformed(QualType T) {
5349 return T.isNull() || !T->isDependentType();
5350 }
Mike Stump11289f42009-09-09 15:08:12 +00005351
5352 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005353 /// rebuilt.
5354 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005355
Douglas Gregor15acfb92009-08-06 16:20:37 +00005356 /// \brief Returns the name of the entity whose type is being rebuilt.
5357 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005358
Douglas Gregoref6ab412009-10-27 06:26:26 +00005359 /// \brief Sets the "base" location and entity when that
5360 /// information is known based on another transformation.
5361 void setBase(SourceLocation Loc, DeclarationName Entity) {
5362 this->Loc = Loc;
5363 this->Entity = Entity;
5364 }
5365
Douglas Gregor15acfb92009-08-06 16:20:37 +00005366 /// \brief Transforms an expression by returning the expression itself
5367 /// (an identity function).
5368 ///
5369 /// FIXME: This is completely unsafe; we will need to actually clone the
5370 /// expressions.
5371 Sema::OwningExprResult TransformExpr(Expr *E) {
Douglas Gregor14cf7522010-04-30 18:55:50 +00005372 return getSema().Owned(E->Retain());
Douglas Gregor15acfb92009-08-06 16:20:37 +00005373 }
Mike Stump11289f42009-09-09 15:08:12 +00005374
Douglas Gregor15acfb92009-08-06 16:20:37 +00005375 /// \brief Transforms a typename type by determining whether the type now
5376 /// refers to a member of the current instantiation, and then
Abramo Bagnara6150c882010-05-11 21:36:43 +00005377 /// type-checking and building an ElaboratedType (when possible).
5378 QualType TransformDependentNameType(TypeLocBuilder &TLB,
5379 DependentNameTypeLoc TL,
5380 QualType ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00005381 };
5382}
5383
Mike Stump11289f42009-09-09 15:08:12 +00005384QualType
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005385CurrentInstantiationRebuilder::TransformDependentNameType(TypeLocBuilder &TLB,
5386 DependentNameTypeLoc TL,
Douglas Gregorfe17d252010-02-16 19:09:40 +00005387 QualType ObjectType) {
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005388 DependentNameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00005389
Douglas Gregor15acfb92009-08-06 16:20:37 +00005390 NestedNameSpecifier *NNS
5391 = TransformNestedNameSpecifier(T->getQualifier(),
Douglas Gregorfe17d252010-02-16 19:09:40 +00005392 /*FIXME:*/SourceRange(getBaseLocation()),
5393 ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00005394 if (!NNS)
5395 return QualType();
5396
5397 // If the nested-name-specifier did not change, and we cannot compute the
5398 // context corresponding to the nested-name-specifier, then this
5399 // typename type will not change; exit early.
5400 CXXScopeSpec SS;
5401 SS.setRange(SourceRange(getBaseLocation()));
5402 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00005403
5404 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005405 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00005406 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00005407
5408 // Rebuild the typename type, which will probably turn into a
Abramo Bagnara6150c882010-05-11 21:36:43 +00005409 // ElaboratedType.
John McCall0ad16662009-10-29 08:12:44 +00005410 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00005411 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00005412 = TransformType(QualType(TemplateId, 0));
5413 if (NewTemplateId.isNull())
5414 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005415
Douglas Gregor15acfb92009-08-06 16:20:37 +00005416 if (NNS == T->getQualifier() &&
5417 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00005418 Result = QualType(T, 0);
5419 else
Douglas Gregor02085352010-03-31 20:19:30 +00005420 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
5421 NNS, NewTemplateId);
John McCall0ad16662009-10-29 08:12:44 +00005422 } else
Douglas Gregor02085352010-03-31 20:19:30 +00005423 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
5424 NNS, T->getIdentifier(),
5425 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00005426
Douglas Gregor281c4862010-03-07 23:26:22 +00005427 if (Result.isNull())
5428 return QualType();
5429
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005430 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
John McCall0ad16662009-10-29 08:12:44 +00005431 NewTL.setNameLoc(TL.getNameLoc());
5432 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005433}
5434
5435/// \brief Rebuilds a type within the context of the current instantiation.
5436///
Mike Stump11289f42009-09-09 15:08:12 +00005437/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005438/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005439/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005440/// partial specialization thereof). This routine will rebuild that type now
5441/// that we have entered the declarator's scope, which may produce different
5442/// canonical types, e.g.,
5443///
5444/// \code
5445/// template<typename T>
5446/// struct X {
5447/// typedef T* pointer;
5448/// pointer data();
5449/// };
5450///
5451/// template<typename T>
5452/// typename X<T>::pointer X<T>::data() { ... }
5453/// \endcode
5454///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005455/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005456/// since we do not know that we can look into X<T> when we parsed the type.
5457/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005458/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005459/// as the canonical type of T*, allowing the return types of the out-of-line
5460/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005461TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5462 SourceLocation Loc,
5463 DeclarationName Name) {
5464 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005465 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005466
Douglas Gregor15acfb92009-08-06 16:20:37 +00005467 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5468 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005469}
Douglas Gregorbe999392009-09-15 16:23:51 +00005470
John McCall99b2fe52010-04-29 23:50:39 +00005471bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5472 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005473
5474 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5475 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5476 DeclarationName());
5477 NestedNameSpecifier *Rebuilt =
5478 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005479 if (!Rebuilt) return true;
5480
5481 SS.setScopeRep(Rebuilt);
5482 return false;
John McCall2408e322010-04-27 00:57:59 +00005483}
5484
Douglas Gregorbe999392009-09-15 16:23:51 +00005485/// \brief Produces a formatted string that describes the binding of
5486/// template parameters to template arguments.
5487std::string
5488Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5489 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005490 // FIXME: For variadic templates, we'll need to get the structured list.
5491 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5492 Args.flat_size());
5493}
5494
5495std::string
5496Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5497 const TemplateArgument *Args,
5498 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005499 std::string Result;
5500
Douglas Gregore62e6a02009-11-11 19:13:48 +00005501 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005502 return Result;
5503
5504 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005505 if (I >= NumArgs)
5506 break;
5507
Douglas Gregorbe999392009-09-15 16:23:51 +00005508 if (I == 0)
5509 Result += "[with ";
5510 else
5511 Result += ", ";
5512
5513 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5514 Result += Id->getName();
5515 } else {
5516 Result += '$';
5517 Result += llvm::utostr(I);
5518 }
5519
5520 Result += " = ";
5521
5522 switch (Args[I].getKind()) {
5523 case TemplateArgument::Null:
5524 Result += "<no value>";
5525 break;
5526
5527 case TemplateArgument::Type: {
5528 std::string TypeStr;
5529 Args[I].getAsType().getAsStringInternal(TypeStr,
5530 Context.PrintingPolicy);
5531 Result += TypeStr;
5532 break;
5533 }
5534
5535 case TemplateArgument::Declaration: {
5536 bool Unnamed = true;
5537 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5538 if (ND->getDeclName()) {
5539 Unnamed = false;
5540 Result += ND->getNameAsString();
5541 }
5542 }
5543
5544 if (Unnamed) {
5545 Result += "<anonymous>";
5546 }
5547 break;
5548 }
5549
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005550 case TemplateArgument::Template: {
5551 std::string Str;
5552 llvm::raw_string_ostream OS(Str);
5553 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5554 Result += OS.str();
5555 break;
5556 }
5557
Douglas Gregorbe999392009-09-15 16:23:51 +00005558 case TemplateArgument::Integral: {
5559 Result += Args[I].getAsIntegral()->toString(10);
5560 break;
5561 }
5562
5563 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005564 // FIXME: This is non-optimal, since we're regurgitating the
5565 // expression we were given.
5566 std::string Str;
5567 {
5568 llvm::raw_string_ostream OS(Str);
5569 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5570 Context.PrintingPolicy);
5571 }
5572 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005573 break;
5574 }
5575
5576 case TemplateArgument::Pack:
5577 // FIXME: Format template argument packs
5578 Result += "<template argument pack>";
5579 break;
5580 }
5581 }
5582
5583 Result += ']';
5584 return Result;
5585}