blob: 9816e76530bc208169453d904a26364afa7b80f5 [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.
213 if (LookupCtx && RequireCompleteDeclContext(SS))
214 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();
253 if (CorrectTypo(Found, S, &SS, LookupCtx)) {
254 FilterAcceptableTemplateNames(Context, Found);
255 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
256 if (LookupCtx)
257 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
258 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000259 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000260 Found.getLookupName().getAsString());
261 else
262 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
263 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000264 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000265 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000266 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
267 Diag(Template->getLocation(), diag::note_previous_decl)
268 << Template->getDeclName();
Douglas Gregorff18cc12009-12-31 08:11:17 +0000269 } else
270 Found.clear();
271 } else {
272 Found.clear();
273 }
274 }
275
John McCalle66edc12009-11-24 19:00:30 +0000276 FilterAcceptableTemplateNames(Context, Found);
277 if (Found.empty())
278 return;
279
280 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
281 // C++ [basic.lookup.classref]p1:
282 // [...] If the lookup in the class of the object expression finds a
283 // template, the name is also looked up in the context of the entire
284 // postfix-expression and [...]
285 //
286 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
287 LookupOrdinaryName);
288 LookupName(FoundOuter, S);
289 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000290
John McCalle66edc12009-11-24 19:00:30 +0000291 if (FoundOuter.empty()) {
292 // - if the name is not found, the name found in the class of the
293 // object expression is used, otherwise
294 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
295 // - if the name is found in the context of the entire
296 // postfix-expression and does not name a class template, the name
297 // found in the class of the object expression is used, otherwise
298 } else {
299 // - if the name found is a class template, it must refer to the same
300 // entity as the one found in the class of the object expression,
301 // otherwise the program is ill-formed.
302 if (!Found.isSingleResult() ||
303 Found.getFoundDecl()->getCanonicalDecl()
304 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
305 Diag(Found.getNameLoc(),
306 diag::err_nested_name_member_ref_lookup_ambiguous)
307 << Found.getLookupName();
308 Diag(Found.getRepresentativeDecl()->getLocation(),
309 diag::note_ambig_member_ref_object_type)
310 << ObjectType;
311 Diag(FoundOuter.getFoundDecl()->getLocation(),
312 diag::note_ambig_member_ref_scope);
313
314 // Recover by taking the template that we found in the object
315 // expression's type.
316 }
317 }
318 }
319}
320
John McCallcd4b4772009-12-02 03:53:29 +0000321/// ActOnDependentIdExpression - Handle a dependent id-expression that
322/// was just parsed. This is only possible with an explicit scope
323/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000324Sema::OwningExprResult
325Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
326 DeclarationName Name,
327 SourceLocation NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000328 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000329 const TemplateArgumentListInfo *TemplateArgs) {
330 NestedNameSpecifier *Qualifier
331 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
332
John McCallcd4b4772009-12-02 03:53:29 +0000333 if (!isAddressOfOperand &&
334 isa<CXXMethodDecl>(CurContext) &&
335 cast<CXXMethodDecl>(CurContext)->isInstance()) {
336 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
337
John McCalle66edc12009-11-24 19:00:30 +0000338 // Since the 'this' expression is synthesized, we don't need to
339 // perform the double-lookup check.
340 NamedDecl *FirstQualifierInScope = 0;
341
John McCall2d74de92009-12-01 22:10:20 +0000342 return Owned(CXXDependentScopeMemberExpr::Create(Context,
343 /*This*/ 0, ThisType,
344 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000345 /*Op*/ SourceLocation(),
346 Qualifier, SS.getRange(),
347 FirstQualifierInScope,
348 Name, NameLoc,
349 TemplateArgs));
350 }
351
352 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
353}
354
355Sema::OwningExprResult
356Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
357 DeclarationName Name,
358 SourceLocation NameLoc,
359 const TemplateArgumentListInfo *TemplateArgs) {
360 return Owned(DependentScopeDeclRefExpr::Create(Context,
361 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
362 SS.getRange(),
363 Name, NameLoc,
364 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000365}
366
Douglas Gregor5101c242008-12-05 18:15:24 +0000367/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
368/// that the template parameter 'PrevDecl' is being shadowed by a new
369/// declaration at location Loc. Returns true to indicate that this is
370/// an error, and false otherwise.
371bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000372 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000373
374 // Microsoft Visual C++ permits template parameters to be shadowed.
375 if (getLangOptions().Microsoft)
376 return false;
377
378 // C++ [temp.local]p4:
379 // A template-parameter shall not be redeclared within its
380 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000381 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000382 << cast<NamedDecl>(PrevDecl)->getDeclName();
383 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
384 return true;
385}
386
Douglas Gregor463421d2009-03-03 04:44:36 +0000387/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000388/// the parameter D to reference the templated declaration and return a pointer
389/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000390TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000391 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000392 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000393 return Temp;
394 }
395 return 0;
396}
397
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000398static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
399 const ParsedTemplateArgument &Arg) {
400
401 switch (Arg.getKind()) {
402 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000403 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000404 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
405 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000406 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000407 return TemplateArgumentLoc(TemplateArgument(T), DI);
408 }
409
410 case ParsedTemplateArgument::NonType: {
411 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
412 return TemplateArgumentLoc(TemplateArgument(E), E);
413 }
414
415 case ParsedTemplateArgument::Template: {
416 TemplateName Template
417 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
418 return TemplateArgumentLoc(TemplateArgument(Template),
419 Arg.getScopeSpec().getRange(),
420 Arg.getLocation());
421 }
422 }
423
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000424 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000425 return TemplateArgumentLoc();
426}
427
428/// \brief Translates template arguments as provided by the parser
429/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000430void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
431 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000432 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000433 TemplateArgs.addArgument(translateTemplateArgument(*this,
434 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000435}
436
Douglas Gregor5101c242008-12-05 18:15:24 +0000437/// ActOnTypeParameter - Called when a C++ template type parameter
438/// (e.g., "typename T") has been parsed. Typename specifies whether
439/// the keyword "typename" was used to declare the type parameter
440/// (otherwise, "class" was used), and KeyLoc is the location of the
441/// "class" or "typename" keyword. ParamName is the name of the
442/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000443/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000444/// If the type parameter has a default argument, it will be added
445/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000446Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000447 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000448 SourceLocation KeyLoc,
449 IdentifierInfo *ParamName,
450 SourceLocation ParamNameLoc,
451 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000452 assert(S->isTemplateParamScope() &&
453 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000454 bool Invalid = false;
455
456 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000457 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000458 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000459 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000460 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000461 }
462
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000463 SourceLocation Loc = ParamNameLoc;
464 if (!ParamName)
465 Loc = KeyLoc;
466
Douglas Gregor5101c242008-12-05 18:15:24 +0000467 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000468 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
469 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000470 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000471 if (Invalid)
472 Param->setInvalidDecl();
473
474 if (ParamName) {
475 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000476 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000477 IdResolver.AddDecl(Param);
478 }
479
Chris Lattner83f095c2009-03-28 19:18:32 +0000480 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000481}
482
Douglas Gregordba32632009-02-10 19:49:53 +0000483/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000484/// Default) to the given template type parameter (TypeParam).
485void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000486 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000487 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000488 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000489 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000490 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000491
John McCallbcd03502009-12-07 02:54:59 +0000492 TypeSourceInfo *DefaultTInfo;
493 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall0ad16662009-10-29 08:12:44 +0000494
John McCallbcd03502009-12-07 02:54:59 +0000495 assert(DefaultTInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000496
Anders Carlssond3824352009-06-12 22:30:13 +0000497 // C++0x [temp.param]p9:
498 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000499 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000500 if (Parm->isParameterPack()) {
501 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000502 return;
503 }
Mike Stump11289f42009-09-09 15:08:12 +0000504
Douglas Gregordba32632009-02-10 19:49:53 +0000505 // C++ [temp.param]p14:
506 // A template-parameter shall not be used in its own default argument.
507 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000508
Douglas Gregordba32632009-02-10 19:49:53 +0000509 // Check the template argument itself.
John McCallbcd03502009-12-07 02:54:59 +0000510 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000511 Parm->setInvalidDecl();
512 return;
513 }
514
John McCallbcd03502009-12-07 02:54:59 +0000515 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000516}
517
Douglas Gregor463421d2009-03-03 04:44:36 +0000518/// \brief Check that the type of a non-type template parameter is
519/// well-formed.
520///
521/// \returns the (possibly-promoted) parameter type if valid;
522/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000523QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000524Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
525 // C++ [temp.param]p4:
526 //
527 // A non-type template-parameter shall have one of the following
528 // (optionally cv-qualified) types:
529 //
530 // -- integral or enumeration type,
531 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000532 // -- pointer to object or pointer to function,
533 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000534 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
535 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000536 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000537 T->isReferenceType() ||
538 // -- pointer to member.
539 T->isMemberPointerType() ||
540 // If T is a dependent type, we can't do the check now, so we
541 // assume that it is well-formed.
542 T->isDependentType())
543 return T;
544 // C++ [temp.param]p8:
545 //
546 // A non-type template-parameter of type "array of T" or
547 // "function returning T" is adjusted to be of type "pointer to
548 // T" or "pointer to function returning T", respectively.
549 else if (T->isArrayType())
550 // FIXME: Keep the type prior to promotion?
551 return Context.getArrayDecayedType(T);
552 else if (T->isFunctionType())
553 // FIXME: Keep the type prior to promotion?
554 return Context.getPointerType(T);
555
556 Diag(Loc, diag::err_template_nontype_parm_bad_type)
557 << T;
558
559 return QualType();
560}
561
Douglas Gregor5101c242008-12-05 18:15:24 +0000562/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
563/// template parameter (e.g., "int Size" in "template<int Size>
564/// class Array") has been parsed. S is the current scope and D is
565/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000566Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000567 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000568 unsigned Position) {
John McCallbcd03502009-12-07 02:54:59 +0000569 TypeSourceInfo *TInfo = 0;
570 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000571
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000572 assert(S->isTemplateParamScope() &&
573 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000574 bool Invalid = false;
575
576 IdentifierInfo *ParamName = D.getIdentifier();
577 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000578 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000579 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000580 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000581 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000582 }
583
Douglas Gregor463421d2009-03-03 04:44:36 +0000584 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000585 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000586 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000587 Invalid = true;
588 }
Douglas Gregor81338792009-02-10 17:43:50 +0000589
Douglas Gregor5101c242008-12-05 18:15:24 +0000590 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000591 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
592 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000593 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000594 if (Invalid)
595 Param->setInvalidDecl();
596
597 if (D.getIdentifier()) {
598 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000599 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000600 IdResolver.AddDecl(Param);
601 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000602 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000603}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000604
Douglas Gregordba32632009-02-10 19:49:53 +0000605/// \brief Adds a default argument to the given non-type template
606/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000607void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000608 SourceLocation EqualLoc,
609 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000610 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000611 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000612 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000613
Douglas Gregordba32632009-02-10 19:49:53 +0000614 // C++ [temp.param]p14:
615 // A template-parameter shall not be used in its own default argument.
616 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000617
Douglas Gregordba32632009-02-10 19:49:53 +0000618 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000619 TemplateArgument Converted;
620 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
621 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000622 TemplateParm->setInvalidDecl();
623 return;
624 }
625
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000626 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000627}
628
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000629
630/// ActOnTemplateTemplateParameter - Called when a C++ template template
631/// parameter (e.g. T in template <template <typename> class T> class array)
632/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000633Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
634 SourceLocation TmpLoc,
635 TemplateParamsTy *Params,
636 IdentifierInfo *Name,
637 SourceLocation NameLoc,
638 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000639 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000640 assert(S->isTemplateParamScope() &&
641 "Template template parameter not in template parameter scope!");
642
643 // Construct the parameter object.
644 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000645 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
646 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000647 (TemplateParameterList*)Params);
648
649 // Make sure the parameter is valid.
650 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
651 // do anything yet. However, if the template parameter list or (eventual)
652 // default value is ever invalidated, that will propagate here.
653 bool Invalid = false;
654 if (Invalid) {
655 Param->setInvalidDecl();
656 }
657
658 // If the tt-param has a name, then link the identifier into the scope
659 // and lookup mechanisms.
660 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000661 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000662 IdResolver.AddDecl(Param);
663 }
664
Chris Lattner83f095c2009-03-28 19:18:32 +0000665 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000666}
667
Douglas Gregordba32632009-02-10 19:49:53 +0000668/// \brief Adds a default argument to the given template template
669/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000670void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000671 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000672 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000673 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000674 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000675
Douglas Gregordba32632009-02-10 19:49:53 +0000676 // C++ [temp.param]p14:
677 // A template-parameter shall not be used in its own default argument.
678 // FIXME: Implement this check! Needs a recursive walk over the types.
679
Douglas Gregore62e6a02009-11-11 19:13:48 +0000680 // Check only that we have a template template argument. We don't want to
681 // try to check well-formedness now, because our template template parameter
682 // might have dependent types in its template parameters, which we wouldn't
683 // be able to match now.
684 //
685 // If none of the template template parameter's template arguments mention
686 // other template parameters, we could actually perform more checking here.
687 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000688 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000689 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
690 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
691 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000692 return;
693 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000694
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000695 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000696}
697
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000698/// ActOnTemplateParameterList - Builds a TemplateParameterList that
699/// contains the template parameters in Params/NumParams.
700Sema::TemplateParamsTy *
701Sema::ActOnTemplateParameterList(unsigned Depth,
702 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000703 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000704 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000705 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000706 SourceLocation RAngleLoc) {
707 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000708 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000709
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000710 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000711 (NamedDecl**)Params, NumParams,
712 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000713}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000714
John McCall3e11ebe2010-03-15 10:12:16 +0000715static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
716 if (SS.isSet())
717 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
718 SS.getRange());
719}
720
Douglas Gregorc08f4892009-03-25 00:13:59 +0000721Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000722Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000723 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000724 IdentifierInfo *Name, SourceLocation NameLoc,
725 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000726 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000727 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000728 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000729 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000730 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000731 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000732
733 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000734 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000735 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000736
John McCall27b5c252009-09-14 21:59:20 +0000737 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
738 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000739
740 // There is no such thing as an unnamed class template.
741 if (!Name) {
742 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000743 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000744 }
745
746 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000747 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000748 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000749 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000750 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000751 if (RequireCompleteDeclContext(SS))
752 return true;
753
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000754 SemanticContext = computeDeclContext(SS, true);
755 if (!SemanticContext) {
756 // FIXME: Produce a reasonable diagnostic here
757 return true;
758 }
Mike Stump11289f42009-09-09 15:08:12 +0000759
John McCall27b18f82009-11-17 02:14:36 +0000760 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000761 } else {
762 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000763 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000764 }
Mike Stump11289f42009-09-09 15:08:12 +0000765
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000766 if (Previous.isAmbiguous())
767 return true;
768
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000769 NamedDecl *PrevDecl = 0;
770 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000771 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000772
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000773 // If there is a previous declaration with the same name, check
774 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000775 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000776 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000777
778 // We may have found the injected-class-name of a class template,
779 // class template partial specialization, or class template specialization.
780 // In these cases, grab the template that is being defined or specialized.
781 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
782 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
783 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
784 PrevClassTemplate
785 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
786 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
787 PrevClassTemplate
788 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
789 ->getSpecializedTemplate();
790 }
791 }
792
John McCalld43784f2009-12-18 11:25:59 +0000793 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000794 // C++ [namespace.memdef]p3:
795 // [...] When looking for a prior declaration of a class or a function
796 // declared as a friend, and when the name of the friend class or
797 // function is neither a qualified name nor a template-id, scopes outside
798 // the innermost enclosing namespace scope are not considered.
799 DeclContext *OutermostContext = CurContext;
800 while (!OutermostContext->isFileContext())
801 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000802
803 if (PrevDecl &&
804 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
805 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
John McCall90d3bb92009-12-17 23:21:11 +0000806 SemanticContext = PrevDecl->getDeclContext();
807 } else {
808 // Declarations in outer scopes don't matter. However, the outermost
809 // context we computed is the semantic context for our new
810 // declaration.
811 PrevDecl = PrevClassTemplate = 0;
812 SemanticContext = OutermostContext;
813 }
814
815 if (CurContext->isDependentContext()) {
816 // If this is a dependent context, we don't want to link the friend
817 // class template to the template in scope, because that would perform
818 // checking of the template parameter lists that can't be performed
819 // until the outer context is instantiated.
820 PrevDecl = PrevClassTemplate = 0;
821 }
822 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
823 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000824
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000825 if (PrevClassTemplate) {
826 // Ensure that the template parameter lists are compatible.
827 if (!TemplateParameterListsAreEqual(TemplateParams,
828 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000829 /*Complain=*/true,
830 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000831 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000832
833 // C++ [temp.class]p4:
834 // In a redeclaration, partial specialization, explicit
835 // specialization or explicit instantiation of a class template,
836 // the class-key shall agree in kind with the original class
837 // template declaration (7.1.5.3).
838 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000839 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000840 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000841 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000842 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000843 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000844 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000845 }
846
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000847 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000848 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000849 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000850 Diag(NameLoc, diag::err_redefinition) << Name;
851 Diag(Def->getLocation(), diag::note_previous_definition);
852 // FIXME: Would it make sense to try to "forget" the previous
853 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000854 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000855 }
856 }
857 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
858 // Maybe we will complain about the shadowed template parameter.
859 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
860 // Just pretend that we didn't see the previous declaration.
861 PrevDecl = 0;
862 } else if (PrevDecl) {
863 // C++ [temp]p5:
864 // A class template shall not have the same name as any other
865 // template, class, function, object, enumeration, enumerator,
866 // namespace, or type in the same scope (3.3), except as specified
867 // in (14.5.4).
868 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
869 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000870 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000871 }
872
Douglas Gregordba32632009-02-10 19:49:53 +0000873 // Check the template parameter list of this declaration, possibly
874 // merging in the template parameter list from the previous class
875 // template declaration.
876 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000877 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
878 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000879 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000880
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000881 if (SS.isSet()) {
882 // If the name of the template was qualified, we must be defining the
883 // template out-of-line.
884 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
885 !(TUK == TUK_Friend && CurContext->isDependentContext()))
886 Diag(NameLoc, diag::err_member_def_does_not_match)
887 << Name << SemanticContext << SS.getRange();
888 }
889
Mike Stump11289f42009-09-09 15:08:12 +0000890 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000891 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000892 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000893 PrevClassTemplate->getTemplatedDecl() : 0,
894 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000895 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000896
897 ClassTemplateDecl *NewTemplate
898 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
899 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000900 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000901 NewClass->setDescribedClassTemplate(NewTemplate);
902
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000903 // Build the type for the class template declaration now.
John McCalle78aac42010-03-10 03:28:59 +0000904 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
905 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000906 assert(T->isDependentType() && "Class template type is not dependent?");
907 (void)T;
908
Douglas Gregorcf915552009-10-13 16:30:37 +0000909 // If we are providing an explicit specialization of a member that is a
910 // class template, make a note of that.
911 if (PrevClassTemplate &&
912 PrevClassTemplate->getInstantiatedFromMemberTemplate())
913 PrevClassTemplate->setMemberSpecialization();
914
Anders Carlsson137108d2009-03-26 01:24:28 +0000915 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000916 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000917 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000918
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000919 // Set the lexical context of these templates
920 NewClass->setLexicalDeclContext(CurContext);
921 NewTemplate->setLexicalDeclContext(CurContext);
922
John McCall9bb74a52009-07-31 02:45:11 +0000923 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000924 NewClass->startDefinition();
925
926 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000927 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000928
John McCall27b5c252009-09-14 21:59:20 +0000929 if (TUK != TUK_Friend)
930 PushOnScopeChains(NewTemplate, S);
931 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000932 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000933 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000934 NewClass->setAccess(PrevClassTemplate->getAccess());
935 }
John McCall27b5c252009-09-14 21:59:20 +0000936
Douglas Gregor3dad8422009-09-26 06:47:28 +0000937 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
938 PrevClassTemplate != NULL);
939
John McCall27b5c252009-09-14 21:59:20 +0000940 // Friend templates are visible in fairly strange ways.
941 if (!CurContext->isDependentContext()) {
942 DeclContext *DC = SemanticContext->getLookupContext();
943 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
944 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
945 PushOnScopeChains(NewTemplate, EnclosingScope,
946 /* AddToContext = */ false);
947 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000948
949 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
950 NewClass->getLocation(),
951 NewTemplate,
952 /*FIXME:*/NewClass->getLocation());
953 Friend->setAccess(AS_public);
954 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000955 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000956
Douglas Gregordba32632009-02-10 19:49:53 +0000957 if (Invalid) {
958 NewTemplate->setInvalidDecl();
959 NewClass->setInvalidDecl();
960 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000961 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000962}
963
Douglas Gregored5731f2009-11-25 17:50:39 +0000964/// \brief Diagnose the presence of a default template argument on a
965/// template parameter, which is ill-formed in certain contexts.
966///
967/// \returns true if the default template argument should be dropped.
968static bool DiagnoseDefaultTemplateArgument(Sema &S,
969 Sema::TemplateParamListContext TPC,
970 SourceLocation ParamLoc,
971 SourceRange DefArgRange) {
972 switch (TPC) {
973 case Sema::TPC_ClassTemplate:
974 return false;
975
976 case Sema::TPC_FunctionTemplate:
977 // C++ [temp.param]p9:
978 // A default template-argument shall not be specified in a
979 // function template declaration or a function template
980 // definition [...]
981 // (This sentence is not in C++0x, per DR226).
982 if (!S.getLangOptions().CPlusPlus0x)
983 S.Diag(ParamLoc,
984 diag::err_template_parameter_default_in_function_template)
985 << DefArgRange;
986 return false;
987
988 case Sema::TPC_ClassTemplateMember:
989 // C++0x [temp.param]p9:
990 // A default template-argument shall not be specified in the
991 // template-parameter-lists of the definition of a member of a
992 // class template that appears outside of the member's class.
993 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
994 << DefArgRange;
995 return true;
996
997 case Sema::TPC_FriendFunctionTemplate:
998 // C++ [temp.param]p9:
999 // A default template-argument shall not be specified in a
1000 // friend template declaration.
1001 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1002 << DefArgRange;
1003 return true;
1004
1005 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1006 // for friend function templates if there is only a single
1007 // declaration (and it is a definition). Strange!
1008 }
1009
1010 return false;
1011}
1012
Douglas Gregordba32632009-02-10 19:49:53 +00001013/// \brief Checks the validity of a template parameter list, possibly
1014/// considering the template parameter list from a previous
1015/// declaration.
1016///
1017/// If an "old" template parameter list is provided, it must be
1018/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1019/// template parameter list.
1020///
1021/// \param NewParams Template parameter list for a new template
1022/// declaration. This template parameter list will be updated with any
1023/// default arguments that are carried through from the previous
1024/// template parameter list.
1025///
1026/// \param OldParams If provided, template parameter list from a
1027/// previous declaration of the same template. Default template
1028/// arguments will be merged from the old template parameter list to
1029/// the new template parameter list.
1030///
Douglas Gregored5731f2009-11-25 17:50:39 +00001031/// \param TPC Describes the context in which we are checking the given
1032/// template parameter list.
1033///
Douglas Gregordba32632009-02-10 19:49:53 +00001034/// \returns true if an error occurred, false otherwise.
1035bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001036 TemplateParameterList *OldParams,
1037 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001038 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001039
Douglas Gregordba32632009-02-10 19:49:53 +00001040 // C++ [temp.param]p10:
1041 // The set of default template-arguments available for use with a
1042 // template declaration or definition is obtained by merging the
1043 // default arguments from the definition (if in scope) and all
1044 // declarations in scope in the same way default function
1045 // arguments are (8.3.6).
1046 bool SawDefaultArgument = false;
1047 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001048
Anders Carlsson327865d2009-06-12 23:20:15 +00001049 bool SawParameterPack = false;
1050 SourceLocation ParameterPackLoc;
1051
Mike Stumpc89c8e32009-02-11 23:03:27 +00001052 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001053 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001054 if (OldParams)
1055 OldParam = OldParams->begin();
1056
1057 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1058 NewParamEnd = NewParams->end();
1059 NewParam != NewParamEnd; ++NewParam) {
1060 // Variables used to diagnose redundant default arguments
1061 bool RedundantDefaultArg = false;
1062 SourceLocation OldDefaultLoc;
1063 SourceLocation NewDefaultLoc;
1064
1065 // Variables used to diagnose missing default arguments
1066 bool MissingDefaultArg = false;
1067
Anders Carlsson327865d2009-06-12 23:20:15 +00001068 // C++0x [temp.param]p11:
1069 // If a template parameter of a class template is a template parameter pack,
1070 // it must be the last template parameter.
1071 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001072 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001073 diag::err_template_param_pack_must_be_last_template_parameter);
1074 Invalid = true;
1075 }
1076
Douglas Gregordba32632009-02-10 19:49:53 +00001077 if (TemplateTypeParmDecl *NewTypeParm
1078 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001079 // Check the presence of a default argument here.
1080 if (NewTypeParm->hasDefaultArgument() &&
1081 DiagnoseDefaultTemplateArgument(*this, TPC,
1082 NewTypeParm->getLocation(),
1083 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1084 .getFullSourceRange()))
1085 NewTypeParm->removeDefaultArgument();
1086
1087 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001088 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001089 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001090
Anders Carlsson327865d2009-06-12 23:20:15 +00001091 if (NewTypeParm->isParameterPack()) {
1092 assert(!NewTypeParm->hasDefaultArgument() &&
1093 "Parameter packs can't have a default argument!");
1094 SawParameterPack = true;
1095 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001096 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001097 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001098 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1099 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1100 SawDefaultArgument = true;
1101 RedundantDefaultArg = true;
1102 PreviousDefaultArgLoc = NewDefaultLoc;
1103 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1104 // Merge the default argument from the old declaration to the
1105 // new declaration.
1106 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001107 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001108 true);
1109 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1110 } else if (NewTypeParm->hasDefaultArgument()) {
1111 SawDefaultArgument = true;
1112 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1113 } else if (SawDefaultArgument)
1114 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001115 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001116 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001117 // Check the presence of a default argument here.
1118 if (NewNonTypeParm->hasDefaultArgument() &&
1119 DiagnoseDefaultTemplateArgument(*this, TPC,
1120 NewNonTypeParm->getLocation(),
1121 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1122 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1123 NewNonTypeParm->setDefaultArgument(0);
1124 }
1125
Mike Stump12b8ce12009-08-04 21:02:39 +00001126 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001127 NonTypeTemplateParmDecl *OldNonTypeParm
1128 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001129 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001130 NewNonTypeParm->hasDefaultArgument()) {
1131 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1132 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1133 SawDefaultArgument = true;
1134 RedundantDefaultArg = true;
1135 PreviousDefaultArgLoc = NewDefaultLoc;
1136 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1137 // Merge the default argument from the old declaration to the
1138 // new declaration.
1139 SawDefaultArgument = true;
1140 // FIXME: We need to create a new kind of "default argument"
1141 // expression that points to a previous template template
1142 // parameter.
1143 NewNonTypeParm->setDefaultArgument(
1144 OldNonTypeParm->getDefaultArgument());
1145 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1146 } else if (NewNonTypeParm->hasDefaultArgument()) {
1147 SawDefaultArgument = true;
1148 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1149 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001150 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001151 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001152 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001153 TemplateTemplateParmDecl *NewTemplateParm
1154 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001155 if (NewTemplateParm->hasDefaultArgument() &&
1156 DiagnoseDefaultTemplateArgument(*this, TPC,
1157 NewTemplateParm->getLocation(),
1158 NewTemplateParm->getDefaultArgument().getSourceRange()))
1159 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1160
1161 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001162 TemplateTemplateParmDecl *OldTemplateParm
1163 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001164 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001165 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001166 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1167 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001168 SawDefaultArgument = true;
1169 RedundantDefaultArg = true;
1170 PreviousDefaultArgLoc = NewDefaultLoc;
1171 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1172 // Merge the default argument from the old declaration to the
1173 // new declaration.
1174 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001175 // FIXME: We need to create a new kind of "default argument" expression
1176 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001177 NewTemplateParm->setDefaultArgument(
1178 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001179 PreviousDefaultArgLoc
1180 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001181 } else if (NewTemplateParm->hasDefaultArgument()) {
1182 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001183 PreviousDefaultArgLoc
1184 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001185 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001186 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001187 }
1188
1189 if (RedundantDefaultArg) {
1190 // C++ [temp.param]p12:
1191 // A template-parameter shall not be given default arguments
1192 // by two different declarations in the same scope.
1193 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1194 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1195 Invalid = true;
1196 } else if (MissingDefaultArg) {
1197 // C++ [temp.param]p11:
1198 // If a template-parameter has a default template-argument,
1199 // all subsequent template-parameters shall have a default
1200 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001201 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001202 diag::err_template_param_default_arg_missing);
1203 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1204 Invalid = true;
1205 }
1206
1207 // If we have an old template parameter list that we're merging
1208 // in, move on to the next parameter.
1209 if (OldParams)
1210 ++OldParam;
1211 }
1212
1213 return Invalid;
1214}
Douglas Gregord32e0282009-02-09 23:23:08 +00001215
Mike Stump11289f42009-09-09 15:08:12 +00001216/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001217/// specifier, returning the template parameter list that applies to the
1218/// name.
1219///
1220/// \param DeclStartLoc the start of the declaration that has a scope
1221/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001222///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001223/// \param SS the scope specifier that will be matched to the given template
1224/// parameter lists. This scope specifier precedes a qualified name that is
1225/// being declared.
1226///
1227/// \param ParamLists the template parameter lists, from the outermost to the
1228/// innermost template parameter lists.
1229///
1230/// \param NumParamLists the number of template parameter lists in ParamLists.
1231///
John McCalle820e5e2010-04-13 20:37:33 +00001232/// \param IsFriend Whether to apply the slightly different rules for
1233/// matching template parameters to scope specifiers in friend
1234/// declarations.
1235///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001236/// \param IsExplicitSpecialization will be set true if the entity being
1237/// declared is an explicit specialization, false otherwise.
1238///
Mike Stump11289f42009-09-09 15:08:12 +00001239/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001240/// name that is preceded by the scope specifier @p SS. This template
1241/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001242/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001243/// template specialization), or may be NULL (if we were's declaring isn't
1244/// itself a template).
1245TemplateParameterList *
1246Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1247 const CXXScopeSpec &SS,
1248 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001249 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001250 bool IsFriend,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001251 bool &IsExplicitSpecialization) {
1252 IsExplicitSpecialization = false;
1253
Douglas Gregord8d297c2009-07-21 23:53:31 +00001254 // Find the template-ids that occur within the nested-name-specifier. These
1255 // template-ids will match up with the template parameter lists.
1256 llvm::SmallVector<const TemplateSpecializationType *, 4>
1257 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001258 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1259 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001260 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1261 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001262 const Type *T = NNS->getAsType();
1263 if (!T) break;
1264
1265 // C++0x [temp.expl.spec]p17:
1266 // A member or a member template may be nested within many
1267 // enclosing class templates. In an explicit specialization for
1268 // such a member, the member declaration shall be preceded by a
1269 // template<> for each enclosing class template that is
1270 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001271 //
1272 // Following the existing practice of GNU and EDG, we allow a typedef of a
1273 // template specialization type.
1274 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1275 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001276
Mike Stump11289f42009-09-09 15:08:12 +00001277 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001278 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001279 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1280 if (!Template)
1281 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001282
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001283 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001284 ClassTemplateSpecializationDecl *SpecDecl
1285 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1286 // If the nested name specifier refers to an explicit specialization,
1287 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001288 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1289 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001290 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001291 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001292 }
Mike Stump11289f42009-09-09 15:08:12 +00001293
Douglas Gregord8d297c2009-07-21 23:53:31 +00001294 TemplateIdsInSpecifier.push_back(SpecType);
1295 }
1296 }
Mike Stump11289f42009-09-09 15:08:12 +00001297
Douglas Gregord8d297c2009-07-21 23:53:31 +00001298 // Reverse the list of template-ids in the scope specifier, so that we can
1299 // more easily match up the template-ids and the template parameter lists.
1300 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001301
Douglas Gregord8d297c2009-07-21 23:53:31 +00001302 SourceLocation FirstTemplateLoc = DeclStartLoc;
1303 if (NumParamLists)
1304 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001305
Douglas Gregord8d297c2009-07-21 23:53:31 +00001306 // Match the template-ids found in the specifier to the template parameter
1307 // lists.
1308 unsigned Idx = 0;
1309 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1310 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001311 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1312 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001313 if (Idx >= NumParamLists) {
1314 // We have a template-id without a corresponding template parameter
1315 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001316
1317 // ...which is fine if this is a friend declaration.
1318 if (IsFriend) {
1319 IsExplicitSpecialization = true;
1320 break;
1321 }
1322
Douglas Gregord8d297c2009-07-21 23:53:31 +00001323 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001324 // FIXME: the location information here isn't great.
1325 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001326 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001327 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001328 << SS.getRange();
1329 } else {
1330 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1331 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001332 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001333 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001334 }
1335 return 0;
1336 }
Mike Stump11289f42009-09-09 15:08:12 +00001337
Douglas Gregord8d297c2009-07-21 23:53:31 +00001338 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001339 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001340 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001341 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1342
Mike Stump11289f42009-09-09 15:08:12 +00001343 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001344 = dyn_cast<ClassTemplateDecl>(Template)) {
1345 TemplateParameterList *ExpectedTemplateParams = 0;
1346 // Is this template-id naming the primary template?
1347 if (Context.hasSameType(TemplateId,
John McCalle78aac42010-03-10 03:28:59 +00001348 ClassTemplate->getInjectedClassNameSpecialization(Context)))
Douglas Gregor15301382009-07-30 17:40:51 +00001349 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1350 // ... or a partial specialization?
1351 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1352 = ClassTemplate->findPartialSpecialization(TemplateId))
1353 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1354
1355 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001356 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001357 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001358 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001359 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001360
1361 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001362 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001363 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001364 diag::err_template_param_list_matches_nontemplate)
1365 << TemplateId
1366 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001367 else
1368 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001369 }
Mike Stump11289f42009-09-09 15:08:12 +00001370
Douglas Gregord8d297c2009-07-21 23:53:31 +00001371 // If there were at least as many template-ids as there were template
1372 // parameter lists, then there are no template parameter lists remaining for
1373 // the declaration itself.
1374 if (Idx >= NumParamLists)
1375 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001376
Douglas Gregord8d297c2009-07-21 23:53:31 +00001377 // If there were too many template parameter lists, complain about that now.
1378 if (Idx != NumParamLists - 1) {
1379 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001380 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001381 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001382 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1383 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001384 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1385 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001386
1387 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1388 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1389 diag::note_explicit_template_spec_does_not_need_header)
1390 << ExplicitSpecializationsInSpecifier.back();
1391 ExplicitSpecializationsInSpecifier.pop_back();
1392 }
1393
Douglas Gregord8d297c2009-07-21 23:53:31 +00001394 ++Idx;
1395 }
1396 }
Mike Stump11289f42009-09-09 15:08:12 +00001397
Douglas Gregord8d297c2009-07-21 23:53:31 +00001398 // Return the last template parameter list, which corresponds to the
1399 // entity being declared.
1400 return ParamLists[NumParamLists - 1];
1401}
1402
Douglas Gregordc572a32009-03-30 22:58:21 +00001403QualType Sema::CheckTemplateIdType(TemplateName Name,
1404 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001405 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001406 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001407 if (!Template) {
1408 // The template name does not resolve to a template, so we just
1409 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001410 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001411 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001412
Douglas Gregorc40290e2009-03-09 23:48:35 +00001413 // Check that the template argument list is well-formed for this
1414 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001415 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001416 TemplateArgs.size());
1417 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001418 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001419 return QualType();
1420
Mike Stump11289f42009-09-09 15:08:12 +00001421 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001422 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001423 "Converted template argument list is too short!");
1424
1425 QualType CanonType;
1426
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001427 if (Name.isDependent() ||
1428 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001429 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001430 // This class template specialization is a dependent
1431 // type. Therefore, its canonical type is another class template
1432 // specialization type that contains all of the converted
1433 // arguments in canonical form. This ensures that, e.g., A<T> and
1434 // A<T, T> have identical types when A is declared as:
1435 //
1436 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001437 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001438 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001439 Converted.getFlatArguments(),
1440 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001441
Douglas Gregora8e02e72009-07-28 23:00:59 +00001442 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001443 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001444 // In the future, we need to teach getTemplateSpecializationType to only
1445 // build the canonical type and return that to us.
1446 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001447 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001448 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001449 // Find the class template specialization declaration that
1450 // corresponds to these arguments.
1451 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001452 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001453 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001454 Converted.flatSize(),
1455 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001456 void *InsertPos = 0;
1457 ClassTemplateSpecializationDecl *Decl
1458 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1459 if (!Decl) {
1460 // This is the first time we have referenced this class template
1461 // specialization. Create the canonical declaration and add it to
1462 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001463 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001464 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001465 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001466 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001467 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001468 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1469 Decl->setLexicalDeclContext(CurContext);
1470 }
1471
1472 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001473 assert(isa<RecordType>(CanonType) &&
1474 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001475 }
Mike Stump11289f42009-09-09 15:08:12 +00001476
Douglas Gregorc40290e2009-03-09 23:48:35 +00001477 // Build the fully-sugared type for this class template
1478 // specialization, which refers back to the class template
1479 // specialization we created or found.
John McCall6b51f282009-11-23 01:53:49 +00001480 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001481}
1482
Douglas Gregor67a65642009-02-17 23:15:12 +00001483Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001484Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001485 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001486 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001487 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001488 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001489
Douglas Gregorc40290e2009-03-09 23:48:35 +00001490 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001491 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001492 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001493
John McCall6b51f282009-11-23 01:53:49 +00001494 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001495 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001496
1497 if (Result.isNull())
1498 return true;
1499
John McCallbcd03502009-12-07 02:54:59 +00001500 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001501 TemplateSpecializationTypeLoc TL
1502 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1503 TL.setTemplateNameLoc(TemplateLoc);
1504 TL.setLAngleLoc(LAngleLoc);
1505 TL.setRAngleLoc(RAngleLoc);
1506 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1507 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1508
1509 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001510}
John McCall06f6fe8d2009-09-04 01:14:41 +00001511
John McCalld8fe9af2009-09-08 17:47:29 +00001512Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1513 TagUseKind TUK,
1514 DeclSpec::TST TagSpec,
1515 SourceLocation TagLoc) {
1516 if (TypeResult.isInvalid())
1517 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001518
John McCall0ad16662009-10-29 08:12:44 +00001519 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001520 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001521 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001522
John McCalld8fe9af2009-09-08 17:47:29 +00001523 // Verify the tag specifier.
1524 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001525
John McCalld8fe9af2009-09-08 17:47:29 +00001526 if (const RecordType *RT = Type->getAs<RecordType>()) {
1527 RecordDecl *D = RT->getDecl();
1528
1529 IdentifierInfo *Id = D->getIdentifier();
1530 assert(Id && "templated class must have an identifier");
1531
1532 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1533 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001534 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001535 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001536 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001537 }
1538 }
1539
John McCalld8fe9af2009-09-08 17:47:29 +00001540 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1541
1542 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001543}
1544
John McCalle66edc12009-11-24 19:00:30 +00001545Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1546 LookupResult &R,
1547 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001548 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001549 // FIXME: Can we do any checking at this point? I guess we could check the
1550 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001551 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001552 // though.
John McCalle66edc12009-11-24 19:00:30 +00001553
1554 // These should be filtered out by our callers.
1555 assert(!R.empty() && "empty lookup results when building templateid");
1556 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1557
1558 NestedNameSpecifier *Qualifier = 0;
1559 SourceRange QualifierRange;
1560 if (SS.isSet()) {
1561 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1562 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001563 }
John McCall58cc69d2010-01-27 01:50:18 +00001564
1565 // We don't want lookup warnings at this point.
1566 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001567
John McCalle66edc12009-11-24 19:00:30 +00001568 bool Dependent
1569 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1570 &TemplateArgs);
1571 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001572 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001573 Qualifier, QualifierRange,
1574 R.getLookupName(), R.getNameLoc(),
1575 RequiresADL, TemplateArgs);
John McCall58cc69d2010-01-27 01:50:18 +00001576 ULE->addDecls(R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001577
1578 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001579}
1580
John McCalle66edc12009-11-24 19:00:30 +00001581// We actually only call this from template instantiation.
1582Sema::OwningExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001583Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001584 DeclarationName Name,
1585 SourceLocation NameLoc,
1586 const TemplateArgumentListInfo &TemplateArgs) {
1587 DeclContext *DC;
1588 if (!(DC = computeDeclContext(SS, false)) ||
1589 DC->isDependentContext() ||
1590 RequireCompleteDeclContext(SS))
1591 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001592
John McCalle66edc12009-11-24 19:00:30 +00001593 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1594 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00001595
John McCalle66edc12009-11-24 19:00:30 +00001596 if (R.isAmbiguous())
1597 return ExprError();
1598
1599 if (R.empty()) {
1600 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1601 << Name << SS.getRange();
1602 return ExprError();
1603 }
1604
1605 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1606 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1607 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1608 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1609 return ExprError();
1610 }
1611
1612 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001613}
1614
Douglas Gregorb67535d2009-03-31 00:43:58 +00001615/// \brief Form a dependent template name.
1616///
1617/// This action forms a dependent template name given the template
1618/// name and its (presumably dependent) scope specifier. For
1619/// example, given "MetaFun::template apply", the scope specifier \p
1620/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1621/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001622Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001623Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001624 CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001625 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001626 TypeTy *ObjectType,
1627 bool EnteringContext) {
Douglas Gregor9abe2372010-01-19 16:01:07 +00001628 DeclContext *LookupCtx = 0;
1629 if (SS.isSet())
1630 LookupCtx = computeDeclContext(SS, EnteringContext);
1631 if (!LookupCtx && ObjectType)
1632 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1633 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001634 // C++0x [temp.names]p5:
1635 // If a name prefixed by the keyword template is not the name of
1636 // a template, the program is ill-formed. [Note: the keyword
1637 // template may not be applied to non-template members of class
1638 // templates. -end note ] [ Note: as is the case with the
1639 // typename prefix, the template prefix is allowed in cases
1640 // where it is not strictly necessary; i.e., when the
1641 // nested-name-specifier or the expression on the left of the ->
1642 // or . is not dependent on a template-parameter, or the use
1643 // does not appear in the scope of a template. -end note]
1644 //
1645 // Note: C++03 was more strict here, because it banned the use of
1646 // the "template" keyword prior to a template-name that was not a
1647 // dependent name. C++ DR468 relaxed this requirement (the
1648 // "template" keyword is now permitted). We follow the C++0x
1649 // rules, even in C++03 mode, retroactively applying the DR.
1650 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001651 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001652 EnteringContext, Template);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001653 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1654 isa<CXXRecordDecl>(LookupCtx) &&
1655 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00001656 // This is a dependent template.
1657 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001658 Diag(Name.getSourceRange().getBegin(),
1659 diag::err_template_kw_refers_to_non_template)
1660 << GetNameFromUnqualifiedId(Name)
1661 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001662 return TemplateTy();
Douglas Gregord2e6a452010-01-14 17:47:39 +00001663 } else {
1664 // We found something; return it.
1665 return Template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001666 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001667 }
1668
Mike Stump11289f42009-09-09 15:08:12 +00001669 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001670 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001671
1672 switch (Name.getKind()) {
1673 case UnqualifiedId::IK_Identifier:
1674 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1675 Name.Identifier));
1676
Douglas Gregor71395fa2009-11-04 00:56:37 +00001677 case UnqualifiedId::IK_OperatorFunctionId:
1678 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1679 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001680
1681 case UnqualifiedId::IK_LiteralOperatorId:
1682 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1683
Douglas Gregor3cf81312009-11-03 23:16:33 +00001684 default:
1685 break;
1686 }
1687
1688 Diag(Name.getSourceRange().getBegin(),
1689 diag::err_template_kw_refers_to_non_template)
1690 << GetNameFromUnqualifiedId(Name)
1691 << Name.getSourceRange();
1692 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001693}
1694
Mike Stump11289f42009-09-09 15:08:12 +00001695bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001696 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001697 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001698 const TemplateArgument &Arg = AL.getArgument();
1699
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001700 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001701 switch(Arg.getKind()) {
1702 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001703 // C++ [temp.arg.type]p1:
1704 // A template-argument for a template-parameter which is a
1705 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001706 break;
1707 case TemplateArgument::Template: {
1708 // We have a template type parameter but the template argument
1709 // is a template without any arguments.
1710 SourceRange SR = AL.getSourceRange();
1711 TemplateName Name = Arg.getAsTemplate();
1712 Diag(SR.getBegin(), diag::err_template_missing_args)
1713 << Name << SR;
1714 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1715 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001716
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001717 return true;
1718 }
1719 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001720 // We have a template type parameter but the template argument
1721 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001722 SourceRange SR = AL.getSourceRange();
1723 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001724 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001725
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001726 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001727 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001728 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001729
John McCallbcd03502009-12-07 02:54:59 +00001730 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001731 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001732
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001733 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001734 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001735 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001736 return false;
1737}
1738
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001739/// \brief Substitute template arguments into the default template argument for
1740/// the given template type parameter.
1741///
1742/// \param SemaRef the semantic analysis object for which we are performing
1743/// the substitution.
1744///
1745/// \param Template the template that we are synthesizing template arguments
1746/// for.
1747///
1748/// \param TemplateLoc the location of the template name that started the
1749/// template-id we are checking.
1750///
1751/// \param RAngleLoc the location of the right angle bracket ('>') that
1752/// terminates the template-id.
1753///
1754/// \param Param the template template parameter whose default we are
1755/// substituting into.
1756///
1757/// \param Converted the list of template arguments provided for template
1758/// parameters that precede \p Param in the template parameter list.
1759///
1760/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001761static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001762SubstDefaultTemplateArgument(Sema &SemaRef,
1763 TemplateDecl *Template,
1764 SourceLocation TemplateLoc,
1765 SourceLocation RAngleLoc,
1766 TemplateTypeParmDecl *Param,
1767 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001768 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001769
1770 // If the argument type is dependent, instantiate it now based
1771 // on the previously-computed template arguments.
1772 if (ArgType->getType()->isDependentType()) {
1773 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1774 /*TakeArgs=*/false);
1775
1776 MultiLevelTemplateArgumentList AllTemplateArgs
1777 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1778
1779 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1780 Template, Converted.getFlatArguments(),
1781 Converted.flatSize(),
1782 SourceRange(TemplateLoc, RAngleLoc));
1783
1784 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1785 Param->getDefaultArgumentLoc(),
1786 Param->getDeclName());
1787 }
1788
1789 return ArgType;
1790}
1791
1792/// \brief Substitute template arguments into the default template argument for
1793/// the given non-type template parameter.
1794///
1795/// \param SemaRef the semantic analysis object for which we are performing
1796/// the substitution.
1797///
1798/// \param Template the template that we are synthesizing template arguments
1799/// for.
1800///
1801/// \param TemplateLoc the location of the template name that started the
1802/// template-id we are checking.
1803///
1804/// \param RAngleLoc the location of the right angle bracket ('>') that
1805/// terminates the template-id.
1806///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001807/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001808/// substituting into.
1809///
1810/// \param Converted the list of template arguments provided for template
1811/// parameters that precede \p Param in the template parameter list.
1812///
1813/// \returns the substituted template argument, or NULL if an error occurred.
1814static Sema::OwningExprResult
1815SubstDefaultTemplateArgument(Sema &SemaRef,
1816 TemplateDecl *Template,
1817 SourceLocation TemplateLoc,
1818 SourceLocation RAngleLoc,
1819 NonTypeTemplateParmDecl *Param,
1820 TemplateArgumentListBuilder &Converted) {
1821 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1822 /*TakeArgs=*/false);
1823
1824 MultiLevelTemplateArgumentList AllTemplateArgs
1825 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1826
1827 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1828 Template, Converted.getFlatArguments(),
1829 Converted.flatSize(),
1830 SourceRange(TemplateLoc, RAngleLoc));
1831
1832 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1833}
1834
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001835/// \brief Substitute template arguments into the default template argument for
1836/// the given template template parameter.
1837///
1838/// \param SemaRef the semantic analysis object for which we are performing
1839/// the substitution.
1840///
1841/// \param Template the template that we are synthesizing template arguments
1842/// for.
1843///
1844/// \param TemplateLoc the location of the template name that started the
1845/// template-id we are checking.
1846///
1847/// \param RAngleLoc the location of the right angle bracket ('>') that
1848/// terminates the template-id.
1849///
1850/// \param Param the template template parameter whose default we are
1851/// substituting into.
1852///
1853/// \param Converted the list of template arguments provided for template
1854/// parameters that precede \p Param in the template parameter list.
1855///
1856/// \returns the substituted template argument, or NULL if an error occurred.
1857static TemplateName
1858SubstDefaultTemplateArgument(Sema &SemaRef,
1859 TemplateDecl *Template,
1860 SourceLocation TemplateLoc,
1861 SourceLocation RAngleLoc,
1862 TemplateTemplateParmDecl *Param,
1863 TemplateArgumentListBuilder &Converted) {
1864 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1865 /*TakeArgs=*/false);
1866
1867 MultiLevelTemplateArgumentList AllTemplateArgs
1868 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1869
1870 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1871 Template, Converted.getFlatArguments(),
1872 Converted.flatSize(),
1873 SourceRange(TemplateLoc, RAngleLoc));
1874
1875 return SemaRef.SubstTemplateName(
1876 Param->getDefaultArgument().getArgument().getAsTemplate(),
1877 Param->getDefaultArgument().getTemplateNameLoc(),
1878 AllTemplateArgs);
1879}
1880
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001881/// \brief If the given template parameter has a default template
1882/// argument, substitute into that default template argument and
1883/// return the corresponding template argument.
1884TemplateArgumentLoc
1885Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1886 SourceLocation TemplateLoc,
1887 SourceLocation RAngleLoc,
1888 Decl *Param,
1889 TemplateArgumentListBuilder &Converted) {
1890 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1891 if (!TypeParm->hasDefaultArgument())
1892 return TemplateArgumentLoc();
1893
John McCallbcd03502009-12-07 02:54:59 +00001894 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001895 TemplateLoc,
1896 RAngleLoc,
1897 TypeParm,
1898 Converted);
1899 if (DI)
1900 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1901
1902 return TemplateArgumentLoc();
1903 }
1904
1905 if (NonTypeTemplateParmDecl *NonTypeParm
1906 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1907 if (!NonTypeParm->hasDefaultArgument())
1908 return TemplateArgumentLoc();
1909
1910 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1911 TemplateLoc,
1912 RAngleLoc,
1913 NonTypeParm,
1914 Converted);
1915 if (Arg.isInvalid())
1916 return TemplateArgumentLoc();
1917
1918 Expr *ArgE = Arg.takeAs<Expr>();
1919 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1920 }
1921
1922 TemplateTemplateParmDecl *TempTempParm
1923 = cast<TemplateTemplateParmDecl>(Param);
1924 if (!TempTempParm->hasDefaultArgument())
1925 return TemplateArgumentLoc();
1926
1927 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1928 TemplateLoc,
1929 RAngleLoc,
1930 TempTempParm,
1931 Converted);
1932 if (TName.isNull())
1933 return TemplateArgumentLoc();
1934
1935 return TemplateArgumentLoc(TemplateArgument(TName),
1936 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1937 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1938}
1939
Douglas Gregorda0fb532009-11-11 19:31:23 +00001940/// \brief Check that the given template argument corresponds to the given
1941/// template parameter.
1942bool Sema::CheckTemplateArgument(NamedDecl *Param,
1943 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001944 TemplateDecl *Template,
1945 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001946 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001947 TemplateArgumentListBuilder &Converted,
1948 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001949 // Check template type parameters.
1950 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001951 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001952
Douglas Gregoreebed722009-11-11 19:41:09 +00001953 // Check non-type template parameters.
1954 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001955 // Do substitution on the type of the non-type template parameter
1956 // with the template arguments we've seen thus far.
1957 QualType NTTPType = NTTP->getType();
1958 if (NTTPType->isDependentType()) {
1959 // Do substitution on the type of the non-type template parameter.
1960 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1961 NTTP, Converted.getFlatArguments(),
1962 Converted.flatSize(),
1963 SourceRange(TemplateLoc, RAngleLoc));
1964
1965 TemplateArgumentList TemplateArgs(Context, Converted,
1966 /*TakeArgs=*/false);
1967 NTTPType = SubstType(NTTPType,
1968 MultiLevelTemplateArgumentList(TemplateArgs),
1969 NTTP->getLocation(),
1970 NTTP->getDeclName());
1971 // If that worked, check the non-type template parameter type
1972 // for validity.
1973 if (!NTTPType.isNull())
1974 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1975 NTTP->getLocation());
1976 if (NTTPType.isNull())
1977 return true;
1978 }
1979
1980 switch (Arg.getArgument().getKind()) {
1981 case TemplateArgument::Null:
1982 assert(false && "Should never see a NULL template argument here");
1983 return true;
1984
1985 case TemplateArgument::Expression: {
1986 Expr *E = Arg.getArgument().getAsExpr();
1987 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001988 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001989 return true;
1990
1991 Converted.Append(Result);
1992 break;
1993 }
1994
1995 case TemplateArgument::Declaration:
1996 case TemplateArgument::Integral:
1997 // We've already checked this template argument, so just copy
1998 // it to the list of converted arguments.
1999 Converted.Append(Arg.getArgument());
2000 break;
2001
2002 case TemplateArgument::Template:
2003 // We were given a template template argument. It may not be ill-formed;
2004 // see below.
2005 if (DependentTemplateName *DTN
2006 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2007 // We have a template argument such as \c T::template X, which we
2008 // parsed as a template template argument. However, since we now
2009 // know that we need a non-type template argument, convert this
2010 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00002011 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2012 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002013 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00002014 DTN->getIdentifier(),
2015 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002016
2017 TemplateArgument Result;
2018 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2019 return true;
2020
2021 Converted.Append(Result);
2022 break;
2023 }
2024
2025 // We have a template argument that actually does refer to a class
2026 // template, template alias, or template template parameter, and
2027 // therefore cannot be a non-type template argument.
2028 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2029 << Arg.getSourceRange();
2030
2031 Diag(Param->getLocation(), diag::note_template_param_here);
2032 return true;
2033
2034 case TemplateArgument::Type: {
2035 // We have a non-type template parameter but the template
2036 // argument is a type.
2037
2038 // C++ [temp.arg]p2:
2039 // In a template-argument, an ambiguity between a type-id and
2040 // an expression is resolved to a type-id, regardless of the
2041 // form of the corresponding template-parameter.
2042 //
2043 // We warn specifically about this case, since it can be rather
2044 // confusing for users.
2045 QualType T = Arg.getArgument().getAsType();
2046 SourceRange SR = Arg.getSourceRange();
2047 if (T->isFunctionType())
2048 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2049 else
2050 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2051 Diag(Param->getLocation(), diag::note_template_param_here);
2052 return true;
2053 }
2054
2055 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002056 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002057 break;
2058 }
2059
2060 return false;
2061 }
2062
2063
2064 // Check template template parameters.
2065 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2066
2067 // Substitute into the template parameter list of the template
2068 // template parameter, since previously-supplied template arguments
2069 // may appear within the template template parameter.
2070 {
2071 // Set up a template instantiation context.
2072 LocalInstantiationScope Scope(*this);
2073 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2074 TempParm, Converted.getFlatArguments(),
2075 Converted.flatSize(),
2076 SourceRange(TemplateLoc, RAngleLoc));
2077
2078 TemplateArgumentList TemplateArgs(Context, Converted,
2079 /*TakeArgs=*/false);
2080 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2081 SubstDecl(TempParm, CurContext,
2082 MultiLevelTemplateArgumentList(TemplateArgs)));
2083 if (!TempParm)
2084 return true;
2085
2086 // FIXME: TempParam is leaked.
2087 }
2088
2089 switch (Arg.getArgument().getKind()) {
2090 case TemplateArgument::Null:
2091 assert(false && "Should never see a NULL template argument here");
2092 return true;
2093
2094 case TemplateArgument::Template:
2095 if (CheckTemplateArgument(TempParm, Arg))
2096 return true;
2097
2098 Converted.Append(Arg.getArgument());
2099 break;
2100
2101 case TemplateArgument::Expression:
2102 case TemplateArgument::Type:
2103 // We have a template template parameter but the template
2104 // argument does not refer to a template.
2105 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2106 return true;
2107
2108 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002109 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002110 "Declaration argument with template template parameter");
2111 break;
2112 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002113 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002114 "Integral argument with template template parameter");
2115 break;
2116
2117 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002118 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002119 break;
2120 }
2121
2122 return false;
2123}
2124
Douglas Gregord32e0282009-02-09 23:23:08 +00002125/// \brief Check that the given template argument list is well-formed
2126/// for specializing the given template.
2127bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2128 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002129 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002130 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002131 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002132 TemplateParameterList *Params = Template->getTemplateParameters();
2133 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002134 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002135 bool Invalid = false;
2136
John McCall6b51f282009-11-23 01:53:49 +00002137 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2138
Mike Stump11289f42009-09-09 15:08:12 +00002139 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002140 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002141
Anders Carlsson15201f12009-06-13 02:08:00 +00002142 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002143 (NumArgs < Params->getMinRequiredArguments() &&
2144 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002145 // FIXME: point at either the first arg beyond what we can handle,
2146 // or the '>', depending on whether we have too many or too few
2147 // arguments.
2148 SourceRange Range;
2149 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002150 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002151 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2152 << (NumArgs > NumParams)
2153 << (isa<ClassTemplateDecl>(Template)? 0 :
2154 isa<FunctionTemplateDecl>(Template)? 1 :
2155 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2156 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002157 Diag(Template->getLocation(), diag::note_template_decl_here)
2158 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002159 Invalid = true;
2160 }
Mike Stump11289f42009-09-09 15:08:12 +00002161
2162 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002163 // [...] The type and form of each template-argument specified in
2164 // a template-id shall match the type and form specified for the
2165 // corresponding parameter declared by the template in its
2166 // template-parameter-list.
2167 unsigned ArgIdx = 0;
2168 for (TemplateParameterList::iterator Param = Params->begin(),
2169 ParamEnd = Params->end();
2170 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002171 if (ArgIdx > NumArgs && PartialTemplateArgs)
2172 break;
Mike Stump11289f42009-09-09 15:08:12 +00002173
Douglas Gregoreebed722009-11-11 19:41:09 +00002174 // If we have a template parameter pack, check every remaining template
2175 // argument against that template parameter pack.
2176 if ((*Param)->isTemplateParameterPack()) {
2177 Converted.BeginPack();
2178 for (; ArgIdx < NumArgs; ++ArgIdx) {
2179 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2180 TemplateLoc, RAngleLoc, Converted)) {
2181 Invalid = true;
2182 break;
2183 }
2184 }
2185 Converted.EndPack();
2186 continue;
2187 }
2188
Douglas Gregor84d49a22009-11-11 21:54:23 +00002189 if (ArgIdx < NumArgs) {
2190 // Check the template argument we were given.
2191 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2192 TemplateLoc, RAngleLoc, Converted))
2193 return true;
2194
2195 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002196 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002197
Douglas Gregor84d49a22009-11-11 21:54:23 +00002198 // We have a default template argument that we will use.
2199 TemplateArgumentLoc Arg;
2200
2201 // Retrieve the default template argument from the template
2202 // parameter. For each kind of template parameter, we substitute the
2203 // template arguments provided thus far and any "outer" template arguments
2204 // (when the template parameter was part of a nested template) into
2205 // the default argument.
2206 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2207 if (!TTP->hasDefaultArgument()) {
2208 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2209 break;
2210 }
2211
John McCallbcd03502009-12-07 02:54:59 +00002212 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002213 Template,
2214 TemplateLoc,
2215 RAngleLoc,
2216 TTP,
2217 Converted);
2218 if (!ArgType)
2219 return true;
2220
2221 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2222 ArgType);
2223 } else if (NonTypeTemplateParmDecl *NTTP
2224 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2225 if (!NTTP->hasDefaultArgument()) {
2226 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2227 break;
2228 }
2229
2230 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2231 TemplateLoc,
2232 RAngleLoc,
2233 NTTP,
2234 Converted);
2235 if (E.isInvalid())
2236 return true;
2237
2238 Expr *Ex = E.takeAs<Expr>();
2239 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2240 } else {
2241 TemplateTemplateParmDecl *TempParm
2242 = cast<TemplateTemplateParmDecl>(*Param);
2243
2244 if (!TempParm->hasDefaultArgument()) {
2245 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2246 break;
2247 }
2248
2249 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2250 TemplateLoc,
2251 RAngleLoc,
2252 TempParm,
2253 Converted);
2254 if (Name.isNull())
2255 return true;
2256
2257 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2258 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2259 TempParm->getDefaultArgument().getTemplateNameLoc());
2260 }
2261
2262 // Introduce an instantiation record that describes where we are using
2263 // the default template argument.
2264 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2265 Converted.getFlatArguments(),
2266 Converted.flatSize(),
2267 SourceRange(TemplateLoc, RAngleLoc));
2268
2269 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002270 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002271 RAngleLoc, Converted))
2272 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002273 }
2274
2275 return Invalid;
2276}
2277
2278/// \brief Check a template argument against its corresponding
2279/// template type parameter.
2280///
2281/// This routine implements the semantics of C++ [temp.arg.type]. It
2282/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002283bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002284 TypeSourceInfo *ArgInfo) {
2285 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002286 QualType Arg = ArgInfo->getType();
2287
Douglas Gregord32e0282009-02-09 23:23:08 +00002288 // C++ [temp.arg.type]p2:
2289 // A local type, a type with no linkage, an unnamed type or a type
2290 // compounded from any of these types shall not be used as a
2291 // template-argument for a template type-parameter.
2292 //
2293 // FIXME: Perform the recursive and no-linkage type checks.
2294 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002295 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002296 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002297 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002298 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002299 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2300 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2301 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2302 << QualType(Tag, 0) << SR;
2303 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002304 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002305 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2306 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002307 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2308 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002309 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2310 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2311 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002312 }
2313
2314 return false;
2315}
2316
Douglas Gregorccb07762009-02-11 19:52:55 +00002317/// \brief Checks whether the given template argument is the address
2318/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002319static bool
2320CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2321 NonTypeTemplateParmDecl *Param,
2322 QualType ParamType,
2323 Expr *ArgIn,
2324 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002325 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002326 Expr *Arg = ArgIn;
2327 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002328
2329 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002330 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002331 Arg = Cast->getSubExpr();
2332
2333 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002334 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002335 // A template-argument for a non-type, non-template
2336 // template-parameter shall be one of: [...]
2337 //
2338 // -- the address of an object or function with external
2339 // linkage, including function templates and function
2340 // template-ids but excluding non-static class members,
2341 // expressed as & id-expression where the & is optional if
2342 // the name refers to a function or array, or if the
2343 // corresponding template-parameter is a reference; or
2344 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002345
Douglas Gregorccb07762009-02-11 19:52:55 +00002346 // Ignore (and complain about) any excess parentheses.
2347 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2348 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002349 S.Diag(Arg->getSourceRange().getBegin(),
2350 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002351 << Arg->getSourceRange();
2352 Invalid = true;
2353 }
2354
2355 Arg = Parens->getSubExpr();
2356 }
2357
Douglas Gregorb242683d2010-04-01 18:32:35 +00002358 bool AddressTaken = false;
2359 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002360 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002361 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002362 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002363 AddressTaken = true;
2364 AddrOpLoc = UnOp->getOperatorLoc();
2365 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002366 } else
2367 DRE = dyn_cast<DeclRefExpr>(Arg);
2368
Douglas Gregorb242683d2010-04-01 18:32:35 +00002369 if (!DRE) {
2370 if (S.Context.hasSameUnqualifiedType(ArgType, S.Context.OverloadTy)) {
2371 S.Diag(Arg->getLocStart(),
2372 diag::err_template_arg_unresolved_overloaded_function)
2373 << ParamType << Arg->getSourceRange();
2374 } else {
2375 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2376 << Arg->getSourceRange();
2377 }
2378 S.Diag(Param->getLocation(), diag::note_template_param_here);
2379 return true;
2380 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002381
2382 // Stop checking the precise nature of the argument if it is value dependent,
2383 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002384 if (Arg->isValueDependent()) {
2385 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002386 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002387 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002388
Douglas Gregorb242683d2010-04-01 18:32:35 +00002389 if (!isa<ValueDecl>(DRE->getDecl())) {
2390 S.Diag(Arg->getSourceRange().getBegin(),
2391 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002392 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002393 S.Diag(Param->getLocation(), diag::note_template_param_here);
2394 return true;
2395 }
2396
2397 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002398
2399 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002400 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2401 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002402 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002403 S.Diag(Param->getLocation(), diag::note_template_param_here);
2404 return true;
2405 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002406
2407 // Cannot refer to non-static member functions
2408 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002409 if (!Method->isStatic()) {
2410 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002411 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002412 S.Diag(Param->getLocation(), diag::note_template_param_here);
2413 return true;
2414 }
Mike Stump11289f42009-09-09 15:08:12 +00002415
Douglas Gregorccb07762009-02-11 19:52:55 +00002416 // Functions must have external linkage.
2417 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002418 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002419 S.Diag(Arg->getSourceRange().getBegin(),
2420 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002421 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002422 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002423 << true;
2424 return true;
2425 }
2426
2427 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002428 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002429
Douglas Gregorb242683d2010-04-01 18:32:35 +00002430 // If the template parameter has pointer type, the function decays.
2431 if (ParamType->isPointerType() && !AddressTaken)
2432 ArgType = S.Context.getPointerType(Func->getType());
2433 else if (AddressTaken && ParamType->isReferenceType()) {
2434 // If we originally had an address-of operator, but the
2435 // parameter has reference type, complain and (if things look
2436 // like they will work) drop the address-of operator.
2437 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2438 ParamType.getNonReferenceType())) {
2439 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2440 << ParamType;
2441 S.Diag(Param->getLocation(), diag::note_template_param_here);
2442 return true;
2443 }
2444
2445 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2446 << ParamType
2447 << FixItHint::CreateRemoval(AddrOpLoc);
2448 S.Diag(Param->getLocation(), diag::note_template_param_here);
2449
2450 ArgType = Func->getType();
2451 }
2452 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002453 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002454 S.Diag(Arg->getSourceRange().getBegin(),
2455 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002456 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002457 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002458 << true;
2459 return true;
2460 }
2461
Douglas Gregorb242683d2010-04-01 18:32:35 +00002462 // A value of reference type is not an object.
2463 if (Var->getType()->isReferenceType()) {
2464 S.Diag(Arg->getSourceRange().getBegin(),
2465 diag::err_template_arg_reference_var)
2466 << Var->getType() << Arg->getSourceRange();
2467 S.Diag(Param->getLocation(), diag::note_template_param_here);
2468 return true;
2469 }
2470
Douglas Gregorccb07762009-02-11 19:52:55 +00002471 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002472 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002473
2474 // If the template parameter has pointer type, we must have taken
2475 // the address of this object.
2476 if (ParamType->isReferenceType()) {
2477 if (AddressTaken) {
2478 // If we originally had an address-of operator, but the
2479 // parameter has reference type, complain and (if things look
2480 // like they will work) drop the address-of operator.
2481 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2482 ParamType.getNonReferenceType())) {
2483 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2484 << ParamType;
2485 S.Diag(Param->getLocation(), diag::note_template_param_here);
2486 return true;
2487 }
2488
2489 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2490 << ParamType
2491 << FixItHint::CreateRemoval(AddrOpLoc);
2492 S.Diag(Param->getLocation(), diag::note_template_param_here);
2493
2494 ArgType = Var->getType();
2495 }
2496 } else if (!AddressTaken && ParamType->isPointerType()) {
2497 if (Var->getType()->isArrayType()) {
2498 // Array-to-pointer decay.
2499 ArgType = S.Context.getArrayDecayedType(Var->getType());
2500 } else {
2501 // If the template parameter has pointer type but the address of
2502 // this object was not taken, complain and (possibly) recover by
2503 // taking the address of the entity.
2504 ArgType = S.Context.getPointerType(Var->getType());
2505 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2506 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2507 << ParamType;
2508 S.Diag(Param->getLocation(), diag::note_template_param_here);
2509 return true;
2510 }
2511
2512 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2513 << ParamType
2514 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2515
2516 S.Diag(Param->getLocation(), diag::note_template_param_here);
2517 }
2518 }
2519 } else {
2520 // We found something else, but we don't know specifically what it is.
2521 S.Diag(Arg->getSourceRange().getBegin(),
2522 diag::err_template_arg_not_object_or_func)
2523 << Arg->getSourceRange();
2524 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2525 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002526 }
Mike Stump11289f42009-09-09 15:08:12 +00002527
Douglas Gregorb242683d2010-04-01 18:32:35 +00002528 if (ParamType->isPointerType() &&
2529 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2530 S.IsQualificationConversion(ArgType, ParamType)) {
2531 // For pointer-to-object types, qualification conversions are
2532 // permitted.
2533 } else {
2534 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2535 if (!ParamRef->getPointeeType()->isFunctionType()) {
2536 // C++ [temp.arg.nontype]p5b3:
2537 // For a non-type template-parameter of type reference to
2538 // object, no conversions apply. The type referred to by the
2539 // reference may be more cv-qualified than the (otherwise
2540 // identical) type of the template- argument. The
2541 // template-parameter is bound directly to the
2542 // template-argument, which shall be an lvalue.
2543
2544 // FIXME: Other qualifiers?
2545 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2546 unsigned ArgQuals = ArgType.getCVRQualifiers();
2547
2548 if ((ParamQuals | ArgQuals) != ParamQuals) {
2549 S.Diag(Arg->getSourceRange().getBegin(),
2550 diag::err_template_arg_ref_bind_ignores_quals)
2551 << ParamType << Arg->getType()
2552 << Arg->getSourceRange();
2553 S.Diag(Param->getLocation(), diag::note_template_param_here);
2554 return true;
2555 }
2556 }
2557 }
2558
2559 // At this point, the template argument refers to an object or
2560 // function with external linkage. We now need to check whether the
2561 // argument and parameter types are compatible.
2562 if (!S.Context.hasSameUnqualifiedType(ArgType,
2563 ParamType.getNonReferenceType())) {
2564 // We can't perform this conversion or binding.
2565 if (ParamType->isReferenceType())
2566 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2567 << ParamType << Arg->getType() << Arg->getSourceRange();
2568 else
2569 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2570 << Arg->getType() << ParamType << Arg->getSourceRange();
2571 S.Diag(Param->getLocation(), diag::note_template_param_here);
2572 return true;
2573 }
2574 }
2575
2576 // Create the template argument.
2577 Converted = TemplateArgument(Entity->getCanonicalDecl());
2578 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002579}
2580
2581/// \brief Checks whether the given template argument is a pointer to
2582/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002583bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2584 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002585 bool Invalid = false;
2586
2587 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002588 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002589 Arg = Cast->getSubExpr();
2590
2591 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002592 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002593 // A template-argument for a non-type, non-template
2594 // template-parameter shall be one of: [...]
2595 //
2596 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002597 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002598
2599 // Ignore (and complain about) any excess parentheses.
2600 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2601 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002602 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002603 diag::err_template_arg_extra_parens)
2604 << Arg->getSourceRange();
2605 Invalid = true;
2606 }
2607
2608 Arg = Parens->getSubExpr();
2609 }
2610
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002611 // A pointer-to-member constant written &Class::member.
2612 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002613 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2614 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2615 if (DRE && !DRE->getQualifier())
2616 DRE = 0;
2617 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002618 }
2619 // A constant of pointer-to-member type.
2620 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2621 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2622 if (VD->getType()->isMemberPointerType()) {
2623 if (isa<NonTypeTemplateParmDecl>(VD) ||
2624 (isa<VarDecl>(VD) &&
2625 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2626 if (Arg->isTypeDependent() || Arg->isValueDependent())
2627 Converted = TemplateArgument(Arg->Retain());
2628 else
2629 Converted = TemplateArgument(VD->getCanonicalDecl());
2630 return Invalid;
2631 }
2632 }
2633 }
2634
2635 DRE = 0;
2636 }
2637
Douglas Gregorccb07762009-02-11 19:52:55 +00002638 if (!DRE)
2639 return Diag(Arg->getSourceRange().getBegin(),
2640 diag::err_template_arg_not_pointer_to_member_form)
2641 << Arg->getSourceRange();
2642
2643 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2644 assert((isa<FieldDecl>(DRE->getDecl()) ||
2645 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2646 "Only non-static member pointers can make it here");
2647
2648 // Okay: this is the address of a non-static member, and therefore
2649 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002650 if (Arg->isTypeDependent() || Arg->isValueDependent())
2651 Converted = TemplateArgument(Arg->Retain());
2652 else
2653 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002654 return Invalid;
2655 }
2656
2657 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002658 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002659 diag::err_template_arg_not_pointer_to_member_form)
2660 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002661 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002662 diag::note_template_arg_refers_here);
2663 return true;
2664}
2665
Douglas Gregord32e0282009-02-09 23:23:08 +00002666/// \brief Check a template argument against its corresponding
2667/// non-type template parameter.
2668///
Douglas Gregor463421d2009-03-03 04:44:36 +00002669/// This routine implements the semantics of C++ [temp.arg.nontype].
2670/// It returns true if an error occurred, and false otherwise. \p
2671/// InstantiatedParamType is the type of the non-type template
2672/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002673///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002674/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002675bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002676 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002677 TemplateArgument &Converted,
2678 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002679 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2680
Douglas Gregor86560402009-02-10 23:36:10 +00002681 // If either the parameter has a dependent type or the argument is
2682 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002683 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2684 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002685 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002686 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002687 }
Douglas Gregor86560402009-02-10 23:36:10 +00002688
2689 // C++ [temp.arg.nontype]p5:
2690 // The following conversions are performed on each expression used
2691 // as a non-type template-argument. If a non-type
2692 // template-argument cannot be converted to the type of the
2693 // corresponding template-parameter then the program is
2694 // ill-formed.
2695 //
2696 // -- for a non-type template-parameter of integral or
2697 // enumeration type, integral promotions (4.5) and integral
2698 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002699 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002700 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002701 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002702 // C++ [temp.arg.nontype]p1:
2703 // A template-argument for a non-type, non-template
2704 // template-parameter shall be one of:
2705 //
2706 // -- an integral constant-expression of integral or enumeration
2707 // type; or
2708 // -- the name of a non-type template-parameter; or
2709 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002710 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002711 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002712 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002713 diag::err_template_arg_not_integral_or_enumeral)
2714 << ArgType << Arg->getSourceRange();
2715 Diag(Param->getLocation(), diag::note_template_param_here);
2716 return true;
2717 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002718 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002719 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2720 << ArgType << Arg->getSourceRange();
2721 return true;
2722 }
2723
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002724 // From here on out, all we care about are the unqualified forms
2725 // of the parameter and argument types.
2726 ParamType = ParamType.getUnqualifiedType();
2727 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002728
2729 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002730 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002731 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002732 } else if (CTAK == CTAK_Deduced) {
2733 // C++ [temp.deduct.type]p17:
2734 // If, in the declaration of a function template with a non-type
2735 // template-parameter, the non-type template- parameter is used
2736 // in an expression in the function parameter-list and, if the
2737 // corresponding template-argument is deduced, the
2738 // template-argument type shall match the type of the
2739 // template-parameter exactly, except that a template-argument
2740 // deduced from an array bound may be of any integral type.
2741 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2742 << ArgType << ParamType;
2743 Diag(Param->getLocation(), diag::note_template_param_here);
2744 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002745 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2746 !ParamType->isEnumeralType()) {
2747 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002748 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002749 } else {
2750 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002751 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002752 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002753 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002754 Diag(Param->getLocation(), diag::note_template_param_here);
2755 return true;
2756 }
2757
Douglas Gregor52aba872009-03-14 00:20:21 +00002758 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002759 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002760 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002761
2762 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002763 llvm::APSInt OldValue = Value;
2764
2765 // Coerce the template argument's value to the value it will have
2766 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002767 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002768 if (Value.getBitWidth() != AllowedBits)
2769 Value.extOrTrunc(AllowedBits);
2770 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002771
2772 // Complain if an unsigned parameter received a negative value.
2773 if (IntegerType->isUnsignedIntegerType()
2774 && (OldValue.isSigned() && OldValue.isNegative())) {
2775 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2776 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2777 << Arg->getSourceRange();
2778 Diag(Param->getLocation(), diag::note_template_param_here);
2779 }
2780
2781 // Complain if we overflowed the template parameter's type.
2782 unsigned RequiredBits;
2783 if (IntegerType->isUnsignedIntegerType())
2784 RequiredBits = OldValue.getActiveBits();
2785 else if (OldValue.isUnsigned())
2786 RequiredBits = OldValue.getActiveBits() + 1;
2787 else
2788 RequiredBits = OldValue.getMinSignedBits();
2789 if (RequiredBits > AllowedBits) {
2790 Diag(Arg->getSourceRange().getBegin(),
2791 diag::warn_template_arg_too_large)
2792 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2793 << Arg->getSourceRange();
2794 Diag(Param->getLocation(), diag::note_template_param_here);
2795 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002796 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002797
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002798 // Add the value of this argument to the list of converted
2799 // arguments. We use the bitwidth and signedness of the template
2800 // parameter.
2801 if (Arg->isValueDependent()) {
2802 // The argument is value-dependent. Create a new
2803 // TemplateArgument with the converted expression.
2804 Converted = TemplateArgument(Arg);
2805 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002806 }
2807
John McCall0ad16662009-10-29 08:12:44 +00002808 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002809 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002810 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002811 return false;
2812 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002813
John McCall16df1e52010-03-30 21:47:33 +00002814 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2815
Douglas Gregorb242683d2010-04-01 18:32:35 +00002816 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2817 // from a template argument of type std::nullptr_t to a non-type
2818 // template parameter of type pointer to object, pointer to
2819 // function, or pointer-to-member, respectively.
2820 if (ArgType->isNullPtrType() &&
2821 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2822 Converted = TemplateArgument((NamedDecl *)0);
2823 return false;
2824 }
2825
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002826 // Handle pointer-to-function, reference-to-function, and
2827 // pointer-to-member-function all in (roughly) the same way.
2828 if (// -- For a non-type template-parameter of type pointer to
2829 // function, only the function-to-pointer conversion (4.3) is
2830 // applied. If the template-argument represents a set of
2831 // overloaded functions (or a pointer to such), the matching
2832 // function is selected from the set (13.4).
2833 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002834 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002835 // -- For a non-type template-parameter of type reference to
2836 // function, no conversions apply. If the template-argument
2837 // represents a set of overloaded functions, the matching
2838 // function is selected from the set (13.4).
2839 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002840 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002841 // -- For a non-type template-parameter of type pointer to
2842 // member function, no conversions apply. If the
2843 // template-argument represents a set of overloaded member
2844 // functions, the matching member function is selected from
2845 // the set (13.4).
2846 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002847 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002848 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002849
2850 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2851 true,
2852 FoundResult)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002853 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2854 return true;
2855
John McCall16df1e52010-03-30 21:47:33 +00002856 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002857 ArgType = Arg->getType();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002858 }
2859
Douglas Gregorb242683d2010-04-01 18:32:35 +00002860 if (!ParamType->isMemberPointerType())
2861 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2862 ParamType,
2863 Arg, Converted);
2864
2865 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2866 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2867 Arg->isLvalue(Context) == Expr::LV_Valid);
2868 } else if (!Context.hasSameUnqualifiedType(ArgType,
2869 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002870 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002871 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002872 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002873 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002874 Diag(Param->getLocation(), diag::note_template_param_here);
2875 return true;
2876 }
Mike Stump11289f42009-09-09 15:08:12 +00002877
Douglas Gregorb242683d2010-04-01 18:32:35 +00002878 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002879 }
2880
Chris Lattner696197c2009-02-20 21:37:53 +00002881 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002882 // -- for a non-type template-parameter of type pointer to
2883 // object, qualification conversions (4.4) and the
2884 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002885 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002886 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002887 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002888
Douglas Gregorb242683d2010-04-01 18:32:35 +00002889 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2890 ParamType,
2891 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002892 }
Mike Stump11289f42009-09-09 15:08:12 +00002893
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002894 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002895 // -- For a non-type template-parameter of type reference to
2896 // object, no conversions apply. The type referred to by the
2897 // reference may be more cv-qualified than the (otherwise
2898 // identical) type of the template-argument. The
2899 // template-parameter is bound directly to the
2900 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002901 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002902 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002903
Douglas Gregorb242683d2010-04-01 18:32:35 +00002904 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2905 ParamRefType->getPointeeType(),
2906 true,
2907 FoundResult)) {
2908 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2909 return true;
2910
2911 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2912 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002913 }
2914
Douglas Gregorb242683d2010-04-01 18:32:35 +00002915 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2916 ParamType,
2917 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002918 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002919
2920 // -- For a non-type template-parameter of type pointer to data
2921 // member, qualification conversions (4.4) are applied.
2922 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2923
Douglas Gregor1515f762009-02-11 18:22:40 +00002924 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002925 // Types match exactly: nothing more to do here.
2926 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002927 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2928 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor0e558532009-02-11 16:16:59 +00002929 } else {
2930 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002931 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002932 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002933 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002934 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002935 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002936 }
2937
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002938 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002939}
2940
2941/// \brief Check a template argument against its corresponding
2942/// template template parameter.
2943///
2944/// This routine implements the semantics of C++ [temp.arg.template].
2945/// It returns true if an error occurred, and false otherwise.
2946bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002947 const TemplateArgumentLoc &Arg) {
2948 TemplateName Name = Arg.getArgument().getAsTemplate();
2949 TemplateDecl *Template = Name.getAsTemplateDecl();
2950 if (!Template) {
2951 // Any dependent template name is fine.
2952 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2953 return false;
2954 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002955
2956 // C++ [temp.arg.template]p1:
2957 // A template-argument for a template template-parameter shall be
2958 // the name of a class template, expressed as id-expression. Only
2959 // primary class templates are considered when matching the
2960 // template template argument with the corresponding parameter;
2961 // partial specializations are not considered even if their
2962 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002963 //
2964 // Note that we also allow template template parameters here, which
2965 // will happen when we are dealing with, e.g., class template
2966 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002967 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002968 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002969 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002970 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002971 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002972 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002973 << Template;
2974 }
2975
2976 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2977 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002978 true,
2979 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002980 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002981}
2982
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002983/// \brief Given a non-type template argument that refers to a
2984/// declaration and the type of its corresponding non-type template
2985/// parameter, produce an expression that properly refers to that
2986/// declaration.
2987Sema::OwningExprResult
2988Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
2989 QualType ParamType,
2990 SourceLocation Loc) {
2991 assert(Arg.getKind() == TemplateArgument::Declaration &&
2992 "Only declaration template arguments permitted here");
2993 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
2994
2995 if (VD->getDeclContext()->isRecord() &&
2996 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
2997 // If the value is a class member, we might have a pointer-to-member.
2998 // Determine whether the non-type template template parameter is of
2999 // pointer-to-member type. If so, we need to build an appropriate
3000 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3001 // would refer to the member itself.
3002 if (ParamType->isMemberPointerType()) {
3003 QualType ClassType
3004 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3005 NestedNameSpecifier *Qualifier
3006 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3007 CXXScopeSpec SS;
3008 SS.setScopeRep(Qualifier);
3009 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3010 VD->getType().getNonReferenceType(),
3011 Loc,
3012 &SS);
3013 if (RefExpr.isInvalid())
3014 return ExprError();
3015
3016 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
3017 assert(!RefExpr.isInvalid() &&
3018 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
3019 ParamType));
3020 return move(RefExpr);
3021 }
3022 }
3023
3024 QualType T = VD->getType().getNonReferenceType();
3025 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003026 // When the non-type template parameter is a pointer, take the
3027 // address of the declaration.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003028 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3029 if (RefExpr.isInvalid())
3030 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003031
3032 if (T->isFunctionType() || T->isArrayType()) {
3033 // Decay functions and arrays.
3034 Expr *RefE = (Expr *)RefExpr.get();
3035 DefaultFunctionArrayConversion(RefE);
3036 if (RefE != RefExpr.get()) {
3037 RefExpr.release();
3038 RefExpr = Owned(RefE);
3039 }
3040
3041 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003042 }
3043
Douglas Gregorb242683d2010-04-01 18:32:35 +00003044 // Take the address of everything else
3045 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003046 }
3047
3048 // If the non-type template parameter has reference type, qualify the
3049 // resulting declaration reference with the extra qualifiers on the
3050 // type that the reference refers to.
3051 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3052 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3053
3054 return BuildDeclRefExpr(VD, T, Loc);
3055}
3056
3057/// \brief Construct a new expression that refers to the given
3058/// integral template argument with the given source-location
3059/// information.
3060///
3061/// This routine takes care of the mapping from an integral template
3062/// argument (which may have any integral type) to the appropriate
3063/// literal value.
3064Sema::OwningExprResult
3065Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3066 SourceLocation Loc) {
3067 assert(Arg.getKind() == TemplateArgument::Integral &&
3068 "Operation is only value for integral template arguments");
3069 QualType T = Arg.getIntegralType();
3070 if (T->isCharType() || T->isWideCharType())
3071 return Owned(new (Context) CharacterLiteral(
3072 Arg.getAsIntegral()->getZExtValue(),
3073 T->isWideCharType(),
3074 T,
3075 Loc));
3076 if (T->isBooleanType())
3077 return Owned(new (Context) CXXBoolLiteralExpr(
3078 Arg.getAsIntegral()->getBoolValue(),
3079 T,
3080 Loc));
3081
3082 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3083}
3084
3085
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003086/// \brief Determine whether the given template parameter lists are
3087/// equivalent.
3088///
Mike Stump11289f42009-09-09 15:08:12 +00003089/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003090/// source code as part of a new template declaration.
3091///
3092/// \param Old The old template parameter list, typically found via
3093/// name lookup of the template declared with this template parameter
3094/// list.
3095///
3096/// \param Complain If true, this routine will produce a diagnostic if
3097/// the template parameter lists are not equivalent.
3098///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003099/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003100///
3101/// \param TemplateArgLoc If this source location is valid, then we
3102/// are actually checking the template parameter list of a template
3103/// argument (New) against the template parameter list of its
3104/// corresponding template template parameter (Old). We produce
3105/// slightly different diagnostics in this scenario.
3106///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003107/// \returns True if the template parameter lists are equal, false
3108/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003109bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003110Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3111 TemplateParameterList *Old,
3112 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003113 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003114 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003115 if (Old->size() != New->size()) {
3116 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003117 unsigned NextDiag = diag::err_template_param_list_different_arity;
3118 if (TemplateArgLoc.isValid()) {
3119 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3120 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003121 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003122 Diag(New->getTemplateLoc(), NextDiag)
3123 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003124 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003125 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003126 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003127 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003128 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3129 }
3130
3131 return false;
3132 }
3133
3134 for (TemplateParameterList::iterator OldParm = Old->begin(),
3135 OldParmEnd = Old->end(), NewParm = New->begin();
3136 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3137 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003138 if (Complain) {
3139 unsigned NextDiag = diag::err_template_param_different_kind;
3140 if (TemplateArgLoc.isValid()) {
3141 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3142 NextDiag = diag::note_template_param_different_kind;
3143 }
3144 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003145 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003146 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003147 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003148 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003149 return false;
3150 }
3151
3152 if (isa<TemplateTypeParmDecl>(*OldParm)) {
3153 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00003154 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00003155 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003156 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3157 // The types of non-type template parameters must agree.
3158 NonTypeTemplateParmDecl *NewNTTP
3159 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003160
3161 // If we are matching a template template argument to a template
3162 // template parameter and one of the non-type template parameter types
3163 // is dependent, then we must wait until template instantiation time
3164 // to actually compare the arguments.
3165 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3166 (OldNTTP->getType()->isDependentType() ||
3167 NewNTTP->getType()->isDependentType()))
3168 continue;
3169
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003170 if (Context.getCanonicalType(OldNTTP->getType()) !=
3171 Context.getCanonicalType(NewNTTP->getType())) {
3172 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003173 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3174 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003175 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003176 diag::err_template_arg_template_params_mismatch);
3177 NextDiag = diag::note_template_nontype_parm_different_type;
3178 }
3179 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003180 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003181 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003182 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003183 diag::note_template_nontype_parm_prev_declaration)
3184 << OldNTTP->getType();
3185 }
3186 return false;
3187 }
3188 } else {
3189 // The template parameter lists of template template
3190 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003191 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003192 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003193 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003194 = cast<TemplateTemplateParmDecl>(*OldParm);
3195 TemplateTemplateParmDecl *NewTTP
3196 = cast<TemplateTemplateParmDecl>(*NewParm);
3197 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3198 OldTTP->getTemplateParameters(),
3199 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003200 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003201 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003202 return false;
3203 }
3204 }
3205
3206 return true;
3207}
3208
3209/// \brief Check whether a template can be declared within this scope.
3210///
3211/// If the template declaration is valid in this scope, returns
3212/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003213bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003214Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003215 // Find the nearest enclosing declaration scope.
3216 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3217 (S->getFlags() & Scope::TemplateParamScope) != 0)
3218 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003219
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003220 // C++ [temp]p2:
3221 // A template-declaration can appear only as a namespace scope or
3222 // class scope declaration.
3223 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003224 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3225 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003226 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003227 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003228
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003229 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003230 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003231
3232 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3233 return false;
3234
Mike Stump11289f42009-09-09 15:08:12 +00003235 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003236 diag::err_template_outside_namespace_or_class_scope)
3237 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003238}
Douglas Gregor67a65642009-02-17 23:15:12 +00003239
Douglas Gregor54888652009-10-07 00:13:32 +00003240/// \brief Determine what kind of template specialization the given declaration
3241/// is.
3242static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3243 if (!D)
3244 return TSK_Undeclared;
3245
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003246 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3247 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003248 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3249 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003250 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3251 return Var->getTemplateSpecializationKind();
3252
Douglas Gregor54888652009-10-07 00:13:32 +00003253 return TSK_Undeclared;
3254}
3255
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003256/// \brief Check whether a specialization is well-formed in the current
3257/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003258///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003259/// This routine determines whether a template specialization can be declared
3260/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003261///
3262/// \param S the semantic analysis object for which this check is being
3263/// performed.
3264///
3265/// \param Specialized the entity being specialized or instantiated, which
3266/// may be a kind of template (class template, function template, etc.) or
3267/// a member of a class template (member function, static data member,
3268/// member class).
3269///
3270/// \param PrevDecl the previous declaration of this entity, if any.
3271///
3272/// \param Loc the location of the explicit specialization or instantiation of
3273/// this entity.
3274///
3275/// \param IsPartialSpecialization whether this is a partial specialization of
3276/// a class template.
3277///
Douglas Gregor54888652009-10-07 00:13:32 +00003278/// \returns true if there was an error that we cannot recover from, false
3279/// otherwise.
3280static bool CheckTemplateSpecializationScope(Sema &S,
3281 NamedDecl *Specialized,
3282 NamedDecl *PrevDecl,
3283 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003284 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003285 // Keep these "kind" numbers in sync with the %select statements in the
3286 // various diagnostics emitted by this routine.
3287 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003288 bool isTemplateSpecialization = false;
3289 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003290 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003291 isTemplateSpecialization = true;
3292 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003293 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003294 isTemplateSpecialization = true;
3295 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003296 EntityKind = 3;
3297 else if (isa<VarDecl>(Specialized))
3298 EntityKind = 4;
3299 else if (isa<RecordDecl>(Specialized))
3300 EntityKind = 5;
3301 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003302 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3303 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003304 return true;
3305 }
3306
Douglas Gregorf47b9112009-02-25 22:02:03 +00003307 // C++ [temp.expl.spec]p2:
3308 // An explicit specialization shall be declared in the namespace
3309 // of which the template is a member, or, for member templates, in
3310 // the namespace of which the enclosing class or enclosing class
3311 // template is a member. An explicit specialization of a member
3312 // function, member class or static data member of a class
3313 // template shall be declared in the namespace of which the class
3314 // template is a member. Such a declaration may also be a
3315 // definition. If the declaration is not a definition, the
3316 // specialization may be defined later in the name- space in which
3317 // the explicit specialization was declared, or in a namespace
3318 // that encloses the one in which the explicit specialization was
3319 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003320 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3321 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003322 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003323 return true;
3324 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003325
Douglas Gregor40fb7442009-10-07 17:30:37 +00003326 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3327 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003328 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003329 return true;
3330 }
3331
Douglas Gregore4b05162009-10-07 17:21:34 +00003332 // C++ [temp.class.spec]p6:
3333 // A class template partial specialization may be declared or redeclared
3334 // in any namespace scope in which its definition may be defined (14.5.1
3335 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003336 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003337 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003338 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003339 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003340 if ((!PrevDecl ||
3341 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3342 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3343 // There is no prior declaration of this entity, so this
3344 // specialization must be in the same context as the template
3345 // itself.
3346 if (!DC->Equals(SpecializedContext)) {
3347 if (isa<TranslationUnitDecl>(SpecializedContext))
3348 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3349 << EntityKind << Specialized;
3350 else if (isa<NamespaceDecl>(SpecializedContext))
3351 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3352 << EntityKind << Specialized
3353 << cast<NamedDecl>(SpecializedContext);
3354
3355 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3356 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003357 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003358 }
Douglas Gregor54888652009-10-07 00:13:32 +00003359
3360 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003361 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003362 // Note that HandleDeclarator() performs this check for explicit
3363 // specializations of function templates, static data members, and member
3364 // functions, so we skip the check here for those kinds of entities.
3365 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003366 // Should we refactor that check, so that it occurs later?
3367 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003368 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3369 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003370 if (isa<TranslationUnitDecl>(SpecializedContext))
3371 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3372 << EntityKind << Specialized;
3373 else if (isa<NamespaceDecl>(SpecializedContext))
3374 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3375 << EntityKind << Specialized
3376 << cast<NamedDecl>(SpecializedContext);
3377
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003378 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003379 }
Douglas Gregor54888652009-10-07 00:13:32 +00003380
3381 // FIXME: check for specialization-after-instantiation errors and such.
3382
Douglas Gregorf47b9112009-02-25 22:02:03 +00003383 return false;
3384}
Douglas Gregor54888652009-10-07 00:13:32 +00003385
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003386/// \brief Check the non-type template arguments of a class template
3387/// partial specialization according to C++ [temp.class.spec]p9.
3388///
Douglas Gregor09a30232009-06-12 22:08:06 +00003389/// \param TemplateParams the template parameters of the primary class
3390/// template.
3391///
3392/// \param TemplateArg the template arguments of the class template
3393/// partial specialization.
3394///
3395/// \param MirrorsPrimaryTemplate will be set true if the class
3396/// template partial specialization arguments are identical to the
3397/// implicit template arguments of the primary template. This is not
3398/// necessarily an error (C++0x), and it is left to the caller to diagnose
3399/// this condition when it is an error.
3400///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003401/// \returns true if there was an error, false otherwise.
3402bool Sema::CheckClassTemplatePartialSpecializationArgs(
3403 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003404 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003405 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003406 // FIXME: the interface to this function will have to change to
3407 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003408 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003409
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003410 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003411
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003412 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003413 // Determine whether the template argument list of the partial
3414 // specialization is identical to the implicit argument list of
3415 // the primary template. The caller may need to diagnostic this as
3416 // an error per C++ [temp.class.spec]p9b3.
3417 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003418 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003419 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3420 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003421 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003422 MirrorsPrimaryTemplate = false;
3423 } else if (TemplateTemplateParmDecl *TTP
3424 = dyn_cast<TemplateTemplateParmDecl>(
3425 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003426 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003427 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003428 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003429 if (!ArgDecl ||
3430 ArgDecl->getIndex() != TTP->getIndex() ||
3431 ArgDecl->getDepth() != TTP->getDepth())
3432 MirrorsPrimaryTemplate = false;
3433 }
3434 }
3435
Mike Stump11289f42009-09-09 15:08:12 +00003436 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003437 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003438 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003439 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003440 }
3441
Anders Carlsson40c1d492009-06-13 18:20:51 +00003442 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003443 if (!ArgExpr) {
3444 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003445 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003446 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003447
3448 // C++ [temp.class.spec]p8:
3449 // A non-type argument is non-specialized if it is the name of a
3450 // non-type parameter. All other non-type arguments are
3451 // specialized.
3452 //
3453 // Below, we check the two conditions that only apply to
3454 // specialized non-type arguments, so skip any non-specialized
3455 // arguments.
3456 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003457 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003458 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003459 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003460 (Param->getIndex() != NTTP->getIndex() ||
3461 Param->getDepth() != NTTP->getDepth()))
3462 MirrorsPrimaryTemplate = false;
3463
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003464 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003465 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003466
3467 // C++ [temp.class.spec]p9:
3468 // Within the argument list of a class template partial
3469 // specialization, the following restrictions apply:
3470 // -- A partially specialized non-type argument expression
3471 // shall not involve a template parameter of the partial
3472 // specialization except when the argument expression is a
3473 // simple identifier.
3474 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003475 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003476 diag::err_dependent_non_type_arg_in_partial_spec)
3477 << ArgExpr->getSourceRange();
3478 return true;
3479 }
3480
3481 // -- The type of a template parameter corresponding to a
3482 // specialized non-type argument shall not be dependent on a
3483 // parameter of the specialization.
3484 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003485 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003486 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3487 << Param->getType()
3488 << ArgExpr->getSourceRange();
3489 Diag(Param->getLocation(), diag::note_template_param_here);
3490 return true;
3491 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003492
3493 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003494 }
3495
3496 return false;
3497}
3498
Douglas Gregorc854c662010-02-26 06:03:23 +00003499/// \brief Retrieve the previous declaration of the given declaration.
3500static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3501 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3502 return VD->getPreviousDeclaration();
3503 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3504 return FD->getPreviousDeclaration();
3505 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3506 return TD->getPreviousDeclaration();
3507 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3508 return TD->getPreviousDeclaration();
3509 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3510 return FTD->getPreviousDeclaration();
3511 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3512 return CTD->getPreviousDeclaration();
3513 return 0;
3514}
3515
Douglas Gregorc08f4892009-03-25 00:13:59 +00003516Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003517Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3518 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003519 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003520 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003521 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003522 SourceLocation TemplateNameLoc,
3523 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003524 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003525 SourceLocation RAngleLoc,
3526 AttributeList *Attr,
3527 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003528 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003529
Douglas Gregor67a65642009-02-17 23:15:12 +00003530 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003531 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003532 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003533 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3534
3535 if (!ClassTemplate) {
3536 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3537 << (Name.getAsTemplateDecl() &&
3538 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3539 return true;
3540 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003541
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003542 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003543 bool isPartialSpecialization = false;
3544
Douglas Gregorf47b9112009-02-25 22:02:03 +00003545 // Check the validity of the template headers that introduce this
3546 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003547 // FIXME: We probably shouldn't complain about these headers for
3548 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003549 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003550 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3551 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003552 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003553 TUK == TUK_Friend,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003554 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003555 if (TemplateParams && TemplateParams->size() > 0) {
3556 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003557
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003558 // C++ [temp.class.spec]p10:
3559 // The template parameter list of a specialization shall not
3560 // contain default template argument values.
3561 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3562 Decl *Param = TemplateParams->getParam(I);
3563 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3564 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003565 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003566 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003567 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003568 }
3569 } else if (NonTypeTemplateParmDecl *NTTP
3570 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3571 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003572 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003573 diag::err_default_arg_in_partial_spec)
3574 << DefArg->getSourceRange();
3575 NTTP->setDefaultArgument(0);
3576 DefArg->Destroy(Context);
3577 }
3578 } else {
3579 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003580 if (TTP->hasDefaultArgument()) {
3581 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003582 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003583 << TTP->getDefaultArgument().getSourceRange();
3584 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003585 }
3586 }
3587 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003588 } else if (TemplateParams) {
3589 if (TUK == TUK_Friend)
3590 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003591 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003592 SourceRange(TemplateParams->getTemplateLoc(),
3593 TemplateParams->getRAngleLoc()))
3594 << SourceRange(LAngleLoc, RAngleLoc);
3595 else
3596 isExplicitSpecialization = true;
3597 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003598 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003599 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003600 isExplicitSpecialization = true;
3601 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003602
Douglas Gregor67a65642009-02-17 23:15:12 +00003603 // Check that the specialization uses the same tag kind as the
3604 // original template.
3605 TagDecl::TagKind Kind;
3606 switch (TagSpec) {
3607 default: assert(0 && "Unknown tag type!");
3608 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3609 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3610 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3611 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003612 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003613 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003614 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003615 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003616 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003617 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003618 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003619 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003620 diag::note_previous_use);
3621 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3622 }
3623
Douglas Gregorc40290e2009-03-09 23:48:35 +00003624 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003625 TemplateArgumentListInfo TemplateArgs;
3626 TemplateArgs.setLAngleLoc(LAngleLoc);
3627 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003628 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003629
Douglas Gregor67a65642009-02-17 23:15:12 +00003630 // Check that the template argument list is well-formed for this
3631 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003632 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3633 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003634 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3635 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003636 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003637
Mike Stump11289f42009-09-09 15:08:12 +00003638 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003639 ClassTemplate->getTemplateParameters()->size()) &&
3640 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003641
Douglas Gregor2373c592009-05-31 09:31:02 +00003642 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003643 // corresponds to these arguments.
3644 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003645 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003646 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003647 if (CheckClassTemplatePartialSpecializationArgs(
3648 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003649 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003650 return true;
3651
Douglas Gregor09a30232009-06-12 22:08:06 +00003652 if (MirrorsPrimaryTemplate) {
3653 // C++ [temp.class.spec]p9b3:
3654 //
Mike Stump11289f42009-09-09 15:08:12 +00003655 // -- The argument list of the specialization shall not be identical
3656 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003657 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003658 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003659 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003660 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003661 ClassTemplate->getIdentifier(),
3662 TemplateNameLoc,
3663 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003664 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003665 AS_none);
3666 }
3667
Douglas Gregor2208a292009-09-26 20:57:03 +00003668 // FIXME: Diagnose friend partial specializations
3669
Douglas Gregor92354b62010-02-09 00:37:32 +00003670 if (!Name.isDependent() &&
3671 !TemplateSpecializationType::anyDependentTemplateArguments(
3672 TemplateArgs.getArgumentArray(),
3673 TemplateArgs.size())) {
3674 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3675 << ClassTemplate->getDeclName();
3676 isPartialSpecialization = false;
3677 } else {
3678 // FIXME: Template parameter list matters, too
3679 ClassTemplatePartialSpecializationDecl::Profile(ID,
3680 Converted.getFlatArguments(),
3681 Converted.flatSize(),
3682 Context);
3683 }
3684 }
3685
3686 if (!isPartialSpecialization)
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003687 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003688 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003689 Converted.flatSize(),
3690 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003691 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003692 ClassTemplateSpecializationDecl *PrevDecl = 0;
3693
3694 if (isPartialSpecialization)
3695 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003696 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003697 InsertPos);
3698 else
3699 PrevDecl
3700 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003701
3702 ClassTemplateSpecializationDecl *Specialization = 0;
3703
Douglas Gregorf47b9112009-02-25 22:02:03 +00003704 // Check whether we can declare a class template specialization in
3705 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003706 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003707 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003708 TemplateNameLoc,
3709 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003710 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003711
Douglas Gregor15301382009-07-30 17:40:51 +00003712 // The canonical type
3713 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003714 if (PrevDecl &&
3715 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003716 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003717 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003718 // arguments was referenced but not declared, or we're only
3719 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003720 // declaration node as our own, updating its source location to
3721 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003722 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003723 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003724 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003725 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003726 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003727 // Build the canonical type that describes the converted template
3728 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003729 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3730 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003731 Converted.getFlatArguments(),
3732 Converted.flatSize());
3733
Douglas Gregor2373c592009-05-31 09:31:02 +00003734 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003735 ClassTemplatePartialSpecializationDecl *PrevPartial
3736 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003737 ClassTemplatePartialSpecializationDecl *Partial
3738 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003739 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003740 TemplateNameLoc,
3741 TemplateParams,
3742 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003743 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003744 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003745 CanonType,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003746 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00003747 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor2373c592009-05-31 09:31:02 +00003748
3749 if (PrevPartial) {
3750 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3751 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3752 } else {
3753 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3754 }
3755 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003756
Douglas Gregor21610382009-10-29 00:04:11 +00003757 // If we are providing an explicit specialization of a member class
3758 // template specialization, make a note of that.
3759 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3760 PrevPartial->setMemberSpecialization();
3761
Douglas Gregor91772d12009-06-13 00:26:55 +00003762 // Check that all of the template parameters of the class template
3763 // partial specialization are deducible from the template
3764 // arguments. If not, this class template partial specialization
3765 // will never be used.
3766 llvm::SmallVector<bool, 8> DeducibleParams;
3767 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003768 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003769 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003770 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003771 unsigned NumNonDeducible = 0;
3772 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3773 if (!DeducibleParams[I])
3774 ++NumNonDeducible;
3775
3776 if (NumNonDeducible) {
3777 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3778 << (NumNonDeducible > 1)
3779 << SourceRange(TemplateNameLoc, RAngleLoc);
3780 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3781 if (!DeducibleParams[I]) {
3782 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3783 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003784 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003785 diag::note_partial_spec_unused_parameter)
3786 << Param->getDeclName();
3787 else
Mike Stump11289f42009-09-09 15:08:12 +00003788 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003789 diag::note_partial_spec_unused_parameter)
3790 << std::string("<anonymous>");
3791 }
3792 }
3793 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003794 } else {
3795 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003796 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003797 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003798 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003799 ClassTemplate->getDeclContext(),
3800 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003801 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003802 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003803 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003804 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor67a65642009-02-17 23:15:12 +00003805
3806 if (PrevDecl) {
3807 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3808 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3809 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003810 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003811 InsertPos);
3812 }
Douglas Gregor15301382009-07-30 17:40:51 +00003813
3814 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003815 }
3816
Douglas Gregor06db9f52009-10-12 20:18:28 +00003817 // C++ [temp.expl.spec]p6:
3818 // If a template, a member template or the member of a class template is
3819 // explicitly specialized then that specialization shall be declared
3820 // before the first use of that specialization that would cause an implicit
3821 // instantiation to take place, in every translation unit in which such a
3822 // use occurs; no diagnostic is required.
3823 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003824 bool Okay = false;
3825 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3826 // Is there any previous explicit specialization declaration?
3827 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3828 Okay = true;
3829 break;
3830 }
3831 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003832
Douglas Gregorc854c662010-02-26 06:03:23 +00003833 if (!Okay) {
3834 SourceRange Range(TemplateNameLoc, RAngleLoc);
3835 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3836 << Context.getTypeDeclType(Specialization) << Range;
3837
3838 Diag(PrevDecl->getPointOfInstantiation(),
3839 diag::note_instantiation_required_here)
3840 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003841 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003842 return true;
3843 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003844 }
3845
Douglas Gregor2208a292009-09-26 20:57:03 +00003846 // If this is not a friend, note that this is an explicit specialization.
3847 if (TUK != TUK_Friend)
3848 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003849
3850 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003851 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003852 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003853 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003854 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003855 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003856 Diag(Def->getLocation(), diag::note_previous_definition);
3857 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003858 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003859 }
3860 }
3861
Douglas Gregord56a91e2009-02-26 22:19:44 +00003862 // Build the fully-sugared type for this class template
3863 // specialization as the user wrote in the specialization
3864 // itself. This means that we'll pretty-print the type retrieved
3865 // from the specialization's declaration the way that the user
3866 // actually wrote the specialization, rather than formatting the
3867 // name based on the "canonical" representation used to store the
3868 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003869 TypeSourceInfo *WrittenTy
3870 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3871 TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003872 if (TUK != TUK_Friend)
3873 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003874 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003875
Douglas Gregor1e249f82009-02-25 22:18:32 +00003876 // C++ [temp.expl.spec]p9:
3877 // A template explicit specialization is in the scope of the
3878 // namespace in which the template was defined.
3879 //
3880 // We actually implement this paragraph where we set the semantic
3881 // context (in the creation of the ClassTemplateSpecializationDecl),
3882 // but we also maintain the lexical context where the actual
3883 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003884 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003885
Douglas Gregor67a65642009-02-17 23:15:12 +00003886 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003887 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003888 Specialization->startDefinition();
3889
Douglas Gregor2208a292009-09-26 20:57:03 +00003890 if (TUK == TUK_Friend) {
3891 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3892 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00003893 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00003894 /*FIXME:*/KWLoc);
3895 Friend->setAccess(AS_public);
3896 CurContext->addDecl(Friend);
3897 } else {
3898 // Add the specialization into its lexical context, so that it can
3899 // be seen when iterating through the list of declarations in that
3900 // context. However, specializations are not found by name lookup.
3901 CurContext->addDecl(Specialization);
3902 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003903 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003904}
Douglas Gregor333489b2009-03-27 23:10:48 +00003905
Mike Stump11289f42009-09-09 15:08:12 +00003906Sema::DeclPtrTy
3907Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003908 MultiTemplateParamsArg TemplateParameterLists,
3909 Declarator &D) {
3910 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3911}
3912
Mike Stump11289f42009-09-09 15:08:12 +00003913Sema::DeclPtrTy
3914Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003915 MultiTemplateParamsArg TemplateParameterLists,
3916 Declarator &D) {
3917 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3918 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3919 "Not a function declarator!");
3920 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003921
Douglas Gregor17a7c122009-06-24 00:54:41 +00003922 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003923 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003924 }
Mike Stump11289f42009-09-09 15:08:12 +00003925
Douglas Gregor17a7c122009-06-24 00:54:41 +00003926 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003927
3928 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003929 move(TemplateParameterLists),
3930 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003931 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003932 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003933 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003934 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003935 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3936 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003937 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003938}
3939
John McCall4f7ced62010-02-11 01:33:53 +00003940/// \brief Strips various properties off an implicit instantiation
3941/// that has just been explicitly specialized.
3942static void StripImplicitInstantiation(NamedDecl *D) {
3943 D->invalidateAttrs();
3944
3945 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3946 FD->setInlineSpecified(false);
3947 }
3948}
3949
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003950/// \brief Diagnose cases where we have an explicit template specialization
3951/// before/after an explicit template instantiation, producing diagnostics
3952/// for those cases where they are required and determining whether the
3953/// new specialization/instantiation will have any effect.
3954///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003955/// \param NewLoc the location of the new explicit specialization or
3956/// instantiation.
3957///
3958/// \param NewTSK the kind of the new explicit specialization or instantiation.
3959///
3960/// \param PrevDecl the previous declaration of the entity.
3961///
3962/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3963///
3964/// \param PrevPointOfInstantiation if valid, indicates where the previus
3965/// declaration was instantiated (either implicitly or explicitly).
3966///
3967/// \param SuppressNew will be set to true to indicate that the new
3968/// specialization or instantiation has no effect and should be ignored.
3969///
3970/// \returns true if there was an error that should prevent the introduction of
3971/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003972bool
3973Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3974 TemplateSpecializationKind NewTSK,
3975 NamedDecl *PrevDecl,
3976 TemplateSpecializationKind PrevTSK,
3977 SourceLocation PrevPointOfInstantiation,
3978 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003979 SuppressNew = false;
3980
3981 switch (NewTSK) {
3982 case TSK_Undeclared:
3983 case TSK_ImplicitInstantiation:
3984 assert(false && "Don't check implicit instantiations here");
3985 return false;
3986
3987 case TSK_ExplicitSpecialization:
3988 switch (PrevTSK) {
3989 case TSK_Undeclared:
3990 case TSK_ExplicitSpecialization:
3991 // Okay, we're just specializing something that is either already
3992 // explicitly specialized or has merely been mentioned without any
3993 // instantiation.
3994 return false;
3995
3996 case TSK_ImplicitInstantiation:
3997 if (PrevPointOfInstantiation.isInvalid()) {
3998 // The declaration itself has not actually been instantiated, so it is
3999 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004000 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004001 return false;
4002 }
4003 // Fall through
4004
4005 case TSK_ExplicitInstantiationDeclaration:
4006 case TSK_ExplicitInstantiationDefinition:
4007 assert((PrevTSK == TSK_ImplicitInstantiation ||
4008 PrevPointOfInstantiation.isValid()) &&
4009 "Explicit instantiation without point of instantiation?");
4010
4011 // C++ [temp.expl.spec]p6:
4012 // If a template, a member template or the member of a class template
4013 // is explicitly specialized then that specialization shall be declared
4014 // before the first use of that specialization that would cause an
4015 // implicit instantiation to take place, in every translation unit in
4016 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004017 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4018 // Is there any previous explicit specialization declaration?
4019 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4020 return false;
4021 }
4022
Douglas Gregor1d957a32009-10-27 18:42:08 +00004023 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004024 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004025 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004026 << (PrevTSK != TSK_ImplicitInstantiation);
4027
4028 return true;
4029 }
4030 break;
4031
4032 case TSK_ExplicitInstantiationDeclaration:
4033 switch (PrevTSK) {
4034 case TSK_ExplicitInstantiationDeclaration:
4035 // This explicit instantiation declaration is redundant (that's okay).
4036 SuppressNew = true;
4037 return false;
4038
4039 case TSK_Undeclared:
4040 case TSK_ImplicitInstantiation:
4041 // We're explicitly instantiating something that may have already been
4042 // implicitly instantiated; that's fine.
4043 return false;
4044
4045 case TSK_ExplicitSpecialization:
4046 // C++0x [temp.explicit]p4:
4047 // For a given set of template parameters, if an explicit instantiation
4048 // of a template appears after a declaration of an explicit
4049 // specialization for that template, the explicit instantiation has no
4050 // effect.
John McCall6b21eb52010-03-02 23:09:38 +00004051 SuppressNew = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004052 return false;
4053
4054 case TSK_ExplicitInstantiationDefinition:
4055 // C++0x [temp.explicit]p10:
4056 // If an entity is the subject of both an explicit instantiation
4057 // declaration and an explicit instantiation definition in the same
4058 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004059 Diag(NewLoc,
4060 diag::err_explicit_instantiation_declaration_after_definition);
4061 Diag(PrevPointOfInstantiation,
4062 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004063 assert(PrevPointOfInstantiation.isValid() &&
4064 "Explicit instantiation without point of instantiation?");
4065 SuppressNew = true;
4066 return false;
4067 }
4068 break;
4069
4070 case TSK_ExplicitInstantiationDefinition:
4071 switch (PrevTSK) {
4072 case TSK_Undeclared:
4073 case TSK_ImplicitInstantiation:
4074 // We're explicitly instantiating something that may have already been
4075 // implicitly instantiated; that's fine.
4076 return false;
4077
4078 case TSK_ExplicitSpecialization:
4079 // C++ DR 259, C++0x [temp.explicit]p4:
4080 // For a given set of template parameters, if an explicit
4081 // instantiation of a template appears after a declaration of
4082 // an explicit specialization for that template, the explicit
4083 // instantiation has no effect.
4084 //
4085 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004086 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004087 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004088 if (!getLangOptions().CPlusPlus0x) {
4089 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004090 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004091 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004092 diag::note_previous_template_specialization);
4093 }
4094 SuppressNew = true;
4095 return false;
4096
4097 case TSK_ExplicitInstantiationDeclaration:
4098 // We're explicity instantiating a definition for something for which we
4099 // were previously asked to suppress instantiations. That's fine.
4100 return false;
4101
4102 case TSK_ExplicitInstantiationDefinition:
4103 // C++0x [temp.spec]p5:
4104 // For a given template and a given set of template-arguments,
4105 // - an explicit instantiation definition shall appear at most once
4106 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004107 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004108 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004109 Diag(PrevPointOfInstantiation,
4110 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004111 SuppressNew = true;
4112 return false;
4113 }
4114 break;
4115 }
4116
4117 assert(false && "Missing specialization/instantiation case?");
4118
4119 return false;
4120}
4121
John McCallb9c78482010-04-08 09:05:18 +00004122/// \brief Perform semantic analysis for the given dependent function
4123/// template specialization. The only possible way to get a dependent
4124/// function template specialization is with a friend declaration,
4125/// like so:
4126///
4127/// template <class T> void foo(T);
4128/// template <class T> class A {
4129/// friend void foo<>(T);
4130/// };
4131///
4132/// There really isn't any useful analysis we can do here, so we
4133/// just store the information.
4134bool
4135Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4136 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4137 LookupResult &Previous) {
4138 // Remove anything from Previous that isn't a function template in
4139 // the correct context.
4140 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4141 LookupResult::Filter F = Previous.makeFilter();
4142 while (F.hasNext()) {
4143 NamedDecl *D = F.next()->getUnderlyingDecl();
4144 if (!isa<FunctionTemplateDecl>(D) ||
4145 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4146 F.erase();
4147 }
4148 F.done();
4149
4150 // Should this be diagnosed here?
4151 if (Previous.empty()) return true;
4152
4153 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4154 ExplicitTemplateArgs);
4155 return false;
4156}
4157
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004158/// \brief Perform semantic analysis for the given function template
4159/// specialization.
4160///
4161/// This routine performs all of the semantic analysis required for an
4162/// explicit function template specialization. On successful completion,
4163/// the function declaration \p FD will become a function template
4164/// specialization.
4165///
4166/// \param FD the function declaration, which will be updated to become a
4167/// function template specialization.
4168///
4169/// \param HasExplicitTemplateArgs whether any template arguments were
4170/// explicitly provided.
4171///
4172/// \param LAngleLoc the location of the left angle bracket ('<'), if
4173/// template arguments were explicitly provided.
4174///
4175/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4176/// if any.
4177///
4178/// \param NumExplicitTemplateArgs the number of explicitly-provided template
4179/// arguments. This number may be zero even when HasExplicitTemplateArgs is
4180/// true as in, e.g., \c void sort<>(char*, char*);
4181///
4182/// \param RAngleLoc the location of the right angle bracket ('>'), if
4183/// template arguments were explicitly provided.
4184///
4185/// \param PrevDecl the set of declarations that
4186bool
4187Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004188 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004189 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004190 // The set of function template specializations that could match this
4191 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004192 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004193
4194 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004195 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4196 I != E; ++I) {
4197 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4198 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004199 // Only consider templates found within the same semantic lookup scope as
4200 // FD.
4201 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4202 continue;
4203
4204 // C++ [temp.expl.spec]p11:
4205 // A trailing template-argument can be left unspecified in the
4206 // template-id naming an explicit function template specialization
4207 // provided it can be deduced from the function argument type.
4208 // Perform template argument deduction to determine whether we may be
4209 // specializing this template.
4210 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004211 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004212 FunctionDecl *Specialization = 0;
4213 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004214 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004215 FD->getType(),
4216 Specialization,
4217 Info)) {
4218 // FIXME: Template argument deduction failed; record why it failed, so
4219 // that we can provide nifty diagnostics.
4220 (void)TDK;
4221 continue;
4222 }
4223
4224 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004225 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004226 }
4227 }
4228
Douglas Gregor5de279c2009-09-26 03:41:46 +00004229 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004230 UnresolvedSetIterator Result
4231 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4232 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004233 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004234 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004235 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004236 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004237 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004238 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004239 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004240
4241 // Ignore access information; it doesn't figure into redeclaration checking.
4242 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004243 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004244
4245 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004246 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004247
4248 // If this is a friend declaration, then we're not really declaring
4249 // an explicit specialization.
4250 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004251
Douglas Gregor54888652009-10-07 00:13:32 +00004252 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004253 if (!isFriend &&
4254 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004255 Specialization->getPrimaryTemplate(),
4256 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004257 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004258 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004259
4260 // C++ [temp.expl.spec]p6:
4261 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004262 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004263 // before the first use of that specialization that would cause an implicit
4264 // instantiation to take place, in every translation unit in which such a
4265 // use occurs; no diagnostic is required.
4266 FunctionTemplateSpecializationInfo *SpecInfo
4267 = Specialization->getTemplateSpecializationInfo();
4268 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004269
4270 bool SuppressNew = false;
John McCall816d75b2010-03-24 07:46:06 +00004271 if (!isFriend &&
4272 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004273 TSK_ExplicitSpecialization,
4274 Specialization,
4275 SpecInfo->getTemplateSpecializationKind(),
4276 SpecInfo->getPointOfInstantiation(),
4277 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004278 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004279
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004280 // Mark the prior declaration as an explicit specialization, so that later
4281 // clients know that this is an explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004282 if (!isFriend)
4283 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004284
4285 // Turn the given function declaration into a function template
4286 // specialization, with the template arguments from the previous
4287 // specialization.
Douglas Gregord5058122010-02-11 01:19:42 +00004288 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004289 new (Context) TemplateArgumentList(
4290 *Specialization->getTemplateSpecializationArgs()),
4291 /*InsertPos=*/0,
John McCall816d75b2010-03-24 07:46:06 +00004292 SpecInfo->getTemplateSpecializationKind());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004293
4294 // The "previous declaration" for this function template specialization is
4295 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004296 Previous.clear();
4297 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004298 return false;
4299}
4300
Douglas Gregor86d142a2009-10-08 07:24:58 +00004301/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004302/// specialization.
4303///
4304/// This routine performs all of the semantic analysis required for an
4305/// explicit member function specialization. On successful completion,
4306/// the function declaration \p FD will become a member function
4307/// specialization.
4308///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004309/// \param Member the member declaration, which will be updated to become a
4310/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004311///
John McCall1f82f242009-11-18 22:49:29 +00004312/// \param Previous the set of declarations, one of which may be specialized
4313/// by this function specialization; the set will be modified to contain the
4314/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004315bool
John McCall1f82f242009-11-18 22:49:29 +00004316Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004317 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004318
Douglas Gregor86d142a2009-10-08 07:24:58 +00004319 // Try to find the member we are instantiating.
4320 NamedDecl *Instantiation = 0;
4321 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004322 MemberSpecializationInfo *MSInfo = 0;
4323
John McCall1f82f242009-11-18 22:49:29 +00004324 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004325 // Nowhere to look anyway.
4326 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004327 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4328 I != E; ++I) {
4329 NamedDecl *D = (*I)->getUnderlyingDecl();
4330 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004331 if (Context.hasSameType(Function->getType(), Method->getType())) {
4332 Instantiation = Method;
4333 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004334 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004335 break;
4336 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004337 }
4338 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004339 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004340 VarDecl *PrevVar;
4341 if (Previous.isSingleResult() &&
4342 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004343 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004344 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004345 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004346 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004347 }
4348 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004349 CXXRecordDecl *PrevRecord;
4350 if (Previous.isSingleResult() &&
4351 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4352 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004353 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004354 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004355 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004356 }
4357
4358 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004359 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004360 // specializations are always out-of-line, the caller will complain about
4361 // this mismatch later.
4362 return false;
4363 }
John McCalle820e5e2010-04-13 20:37:33 +00004364
4365 // If this is a friend, just bail out here before we start turning
4366 // things into explicit specializations.
4367 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4368 // Preserve instantiation information.
4369 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4370 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4371 cast<CXXMethodDecl>(InstantiatedFrom),
4372 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4373 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4374 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4375 cast<CXXRecordDecl>(InstantiatedFrom),
4376 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4377 }
4378
4379 Previous.clear();
4380 Previous.addDecl(Instantiation);
4381 return false;
4382 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004383
Douglas Gregor86d142a2009-10-08 07:24:58 +00004384 // Make sure that this is a specialization of a member.
4385 if (!InstantiatedFrom) {
4386 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4387 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004388 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4389 return true;
4390 }
4391
Douglas Gregor06db9f52009-10-12 20:18:28 +00004392 // C++ [temp.expl.spec]p6:
4393 // If a template, a member template or the member of a class template is
4394 // explicitly specialized then that spe- cialization shall be declared
4395 // before the first use of that specialization that would cause an implicit
4396 // instantiation to take place, in every translation unit in which such a
4397 // use occurs; no diagnostic is required.
4398 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004399
4400 bool SuppressNew = false;
4401 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4402 TSK_ExplicitSpecialization,
4403 Instantiation,
4404 MSInfo->getTemplateSpecializationKind(),
4405 MSInfo->getPointOfInstantiation(),
4406 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004407 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004408
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004409 // Check the scope of this explicit specialization.
4410 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004411 InstantiatedFrom,
4412 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004413 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004414 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004415
Douglas Gregor86d142a2009-10-08 07:24:58 +00004416 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004417 // the original declaration to note that it is an explicit specialization
4418 // (if it was previously an implicit instantiation). This latter step
4419 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004420 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004421 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4422 if (InstantiationFunction->getTemplateSpecializationKind() ==
4423 TSK_ImplicitInstantiation) {
4424 InstantiationFunction->setTemplateSpecializationKind(
4425 TSK_ExplicitSpecialization);
4426 InstantiationFunction->setLocation(Member->getLocation());
4427 }
4428
Douglas Gregor86d142a2009-10-08 07:24:58 +00004429 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4430 cast<CXXMethodDecl>(InstantiatedFrom),
4431 TSK_ExplicitSpecialization);
4432 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004433 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4434 if (InstantiationVar->getTemplateSpecializationKind() ==
4435 TSK_ImplicitInstantiation) {
4436 InstantiationVar->setTemplateSpecializationKind(
4437 TSK_ExplicitSpecialization);
4438 InstantiationVar->setLocation(Member->getLocation());
4439 }
4440
Douglas Gregor86d142a2009-10-08 07:24:58 +00004441 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4442 cast<VarDecl>(InstantiatedFrom),
4443 TSK_ExplicitSpecialization);
4444 } else {
4445 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004446 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4447 if (InstantiationClass->getTemplateSpecializationKind() ==
4448 TSK_ImplicitInstantiation) {
4449 InstantiationClass->setTemplateSpecializationKind(
4450 TSK_ExplicitSpecialization);
4451 InstantiationClass->setLocation(Member->getLocation());
4452 }
4453
Douglas Gregor86d142a2009-10-08 07:24:58 +00004454 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004455 cast<CXXRecordDecl>(InstantiatedFrom),
4456 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004457 }
4458
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004459 // Save the caller the trouble of having to figure out which declaration
4460 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004461 Previous.clear();
4462 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004463 return false;
4464}
4465
Douglas Gregore47f5a72009-10-14 23:41:34 +00004466/// \brief Check the scope of an explicit instantiation.
4467static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4468 SourceLocation InstLoc,
4469 bool WasQualifiedName) {
4470 DeclContext *ExpectedContext
4471 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4472 DeclContext *CurContext = S.CurContext->getLookupContext();
4473
4474 // C++0x [temp.explicit]p2:
4475 // An explicit instantiation shall appear in an enclosing namespace of its
4476 // template.
4477 //
4478 // This is DR275, which we do not retroactively apply to C++98/03.
4479 if (S.getLangOptions().CPlusPlus0x &&
4480 !CurContext->Encloses(ExpectedContext)) {
4481 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4482 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4483 << D << NS;
4484 else
4485 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4486 << D;
4487 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4488 return;
4489 }
4490
4491 // C++0x [temp.explicit]p2:
4492 // If the name declared in the explicit instantiation is an unqualified
4493 // name, the explicit instantiation shall appear in the namespace where
4494 // its template is declared or, if that namespace is inline (7.3.1), any
4495 // namespace from its enclosing namespace set.
4496 if (WasQualifiedName)
4497 return;
4498
4499 if (CurContext->Equals(ExpectedContext))
4500 return;
4501
4502 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4503 << D << ExpectedContext;
4504 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4505}
4506
4507/// \brief Determine whether the given scope specifier has a template-id in it.
4508static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4509 if (!SS.isSet())
4510 return false;
4511
4512 // C++0x [temp.explicit]p2:
4513 // If the explicit instantiation is for a member function, a member class
4514 // or a static data member of a class template specialization, the name of
4515 // the class template specialization in the qualified-id for the member
4516 // name shall be a simple-template-id.
4517 //
4518 // C++98 has the same restriction, just worded differently.
4519 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4520 NNS; NNS = NNS->getPrefix())
4521 if (Type *T = NNS->getAsType())
4522 if (isa<TemplateSpecializationType>(T))
4523 return true;
4524
4525 return false;
4526}
4527
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004528// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004529// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004530Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004531Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004532 SourceLocation ExternLoc,
4533 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004534 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004535 SourceLocation KWLoc,
4536 const CXXScopeSpec &SS,
4537 TemplateTy TemplateD,
4538 SourceLocation TemplateNameLoc,
4539 SourceLocation LAngleLoc,
4540 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004541 SourceLocation RAngleLoc,
4542 AttributeList *Attr) {
4543 // Find the class template we're specializing
4544 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004545 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004546 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4547
4548 // Check that the specialization uses the same tag kind as the
4549 // original template.
4550 TagDecl::TagKind Kind;
4551 switch (TagSpec) {
4552 default: assert(0 && "Unknown tag type!");
4553 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4554 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4555 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4556 }
Douglas Gregord9034f02009-05-14 16:41:31 +00004557 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004558 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004559 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004560 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004561 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004562 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004563 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004564 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004565 diag::note_previous_use);
4566 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4567 }
4568
Douglas Gregore47f5a72009-10-14 23:41:34 +00004569 // C++0x [temp.explicit]p2:
4570 // There are two forms of explicit instantiation: an explicit instantiation
4571 // definition and an explicit instantiation declaration. An explicit
4572 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004573 TemplateSpecializationKind TSK
4574 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4575 : TSK_ExplicitInstantiationDeclaration;
4576
Douglas Gregora1f49972009-05-13 00:25:59 +00004577 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004578 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004579 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004580
4581 // Check that the template argument list is well-formed for this
4582 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004583 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4584 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004585 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4586 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004587 return true;
4588
Mike Stump11289f42009-09-09 15:08:12 +00004589 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004590 ClassTemplate->getTemplateParameters()->size()) &&
4591 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004592
Douglas Gregora1f49972009-05-13 00:25:59 +00004593 // Find the class template specialization declaration that
4594 // corresponds to these arguments.
4595 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004596 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004597 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004598 Converted.flatSize(),
4599 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004600 void *InsertPos = 0;
4601 ClassTemplateSpecializationDecl *PrevDecl
4602 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4603
Douglas Gregor54888652009-10-07 00:13:32 +00004604 // C++0x [temp.explicit]p2:
4605 // [...] An explicit instantiation shall appear in an enclosing
4606 // namespace of its template. [...]
4607 //
4608 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004609 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4610 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004611
Douglas Gregora1f49972009-05-13 00:25:59 +00004612 ClassTemplateSpecializationDecl *Specialization = 0;
4613
Douglas Gregor0681a352009-11-25 06:01:46 +00004614 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004615 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004616 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004617 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004618 PrevDecl,
4619 PrevDecl->getSpecializationKind(),
4620 PrevDecl->getPointOfInstantiation(),
4621 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004622 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004623
Douglas Gregor12e49d32009-10-15 22:53:21 +00004624 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004625 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004626
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004627 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4628 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4629 // Since the only prior class template specialization with these
4630 // arguments was referenced but not declared, reuse that
4631 // declaration node as our own, updating its source location to
4632 // reflect our new declaration.
4633 Specialization = PrevDecl;
4634 Specialization->setLocation(TemplateNameLoc);
4635 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004636 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004637 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004638 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004639
4640 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004641 // Create a new class template specialization declaration node for
4642 // this explicit specialization.
4643 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00004644 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00004645 ClassTemplate->getDeclContext(),
4646 TemplateNameLoc,
4647 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004648 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004649 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004650
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004651 if (PrevDecl) {
4652 // Remove the previous declaration from the folding set, since we want
4653 // to introduce a new declaration.
4654 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4655 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4656 }
4657
4658 // Insert the new specialization.
4659 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004660 }
4661
4662 // Build the fully-sugared type for this explicit instantiation as
4663 // the user wrote in the explicit instantiation itself. This means
4664 // that we'll pretty-print the type retrieved from the
4665 // specialization's declaration the way that the user actually wrote
4666 // the explicit instantiation, rather than formatting the name based
4667 // on the "canonical" representation used to store the template
4668 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004669 TypeSourceInfo *WrittenTy
4670 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4671 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004672 Context.getTypeDeclType(Specialization));
4673 Specialization->setTypeAsWritten(WrittenTy);
4674 TemplateArgsIn.release();
4675
Douglas Gregor0681a352009-11-25 06:01:46 +00004676 if (!ReusedDecl) {
4677 // Add the explicit instantiation into its lexical context. However,
4678 // since explicit instantiations are never found by name lookup, we
4679 // just put it into the declaration context directly.
4680 Specialization->setLexicalDeclContext(CurContext);
4681 CurContext->addDecl(Specialization);
4682 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004683
4684 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004685 // A definition of a class template or class member template
4686 // shall be in scope at the point of the explicit instantiation of
4687 // the class template or class member template.
4688 //
4689 // This check comes when we actually try to perform the
4690 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004691 ClassTemplateSpecializationDecl *Def
4692 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004693 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004694 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004695 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004696
4697 // Instantiate the members of this class template specialization.
4698 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004699 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004700 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004701 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4702
4703 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4704 // TSK_ExplicitInstantiationDefinition
4705 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4706 TSK == TSK_ExplicitInstantiationDefinition)
4707 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004708
Douglas Gregor12e49d32009-10-15 22:53:21 +00004709 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004710 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004711
4712 return DeclPtrTy::make(Specialization);
4713}
4714
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004715// Explicit instantiation of a member class of a class template.
4716Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004717Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004718 SourceLocation ExternLoc,
4719 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004720 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004721 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004722 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004723 IdentifierInfo *Name,
4724 SourceLocation NameLoc,
4725 AttributeList *Attr) {
4726
Douglas Gregord6ab8742009-05-28 23:31:59 +00004727 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004728 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004729 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004730 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004731 MultiTemplateParamsArg(*this, 0, 0),
4732 Owned, IsDependent);
4733 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4734
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004735 if (!TagD)
4736 return true;
4737
4738 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4739 if (Tag->isEnum()) {
4740 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4741 << Context.getTypeDeclType(Tag);
4742 return true;
4743 }
4744
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004745 if (Tag->isInvalidDecl())
4746 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004747
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004748 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4749 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4750 if (!Pattern) {
4751 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4752 << Context.getTypeDeclType(Record);
4753 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4754 return true;
4755 }
4756
Douglas Gregore47f5a72009-10-14 23:41:34 +00004757 // C++0x [temp.explicit]p2:
4758 // If the explicit instantiation is for a class or member class, the
4759 // elaborated-type-specifier in the declaration shall include a
4760 // simple-template-id.
4761 //
4762 // C++98 has the same restriction, just worded differently.
4763 if (!ScopeSpecifierHasTemplateId(SS))
4764 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4765 << Record << SS.getRange();
4766
4767 // C++0x [temp.explicit]p2:
4768 // There are two forms of explicit instantiation: an explicit instantiation
4769 // definition and an explicit instantiation declaration. An explicit
4770 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004771 TemplateSpecializationKind TSK
4772 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4773 : TSK_ExplicitInstantiationDeclaration;
4774
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004775 // C++0x [temp.explicit]p2:
4776 // [...] An explicit instantiation shall appear in an enclosing
4777 // namespace of its template. [...]
4778 //
4779 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004780 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004781
4782 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004783 CXXRecordDecl *PrevDecl
4784 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004785 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004786 PrevDecl = Record;
4787 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004788 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4789 bool SuppressNew = false;
4790 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004791 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004792 PrevDecl,
4793 MSInfo->getTemplateSpecializationKind(),
4794 MSInfo->getPointOfInstantiation(),
4795 SuppressNew))
4796 return true;
4797 if (SuppressNew)
4798 return TagD;
4799 }
4800
Douglas Gregor12e49d32009-10-15 22:53:21 +00004801 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004802 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004803 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004804 // C++ [temp.explicit]p3:
4805 // A definition of a member class of a class template shall be in scope
4806 // at the point of an explicit instantiation of the member class.
4807 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004808 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004809 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004810 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4811 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004812 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4813 << Pattern;
4814 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004815 } else {
4816 if (InstantiateClass(NameLoc, Record, Def,
4817 getTemplateInstantiationArgs(Record),
4818 TSK))
4819 return true;
4820
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004821 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004822 if (!RecordDef)
4823 return true;
4824 }
4825 }
4826
4827 // Instantiate all of the members of the class.
4828 InstantiateClassMembers(NameLoc, RecordDef,
4829 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004830
Mike Stump87c57ac2009-05-16 07:39:55 +00004831 // FIXME: We don't have any representation for explicit instantiations of
4832 // member classes. Such a representation is not needed for compilation, but it
4833 // should be available for clients that want to see all of the declarations in
4834 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004835 return TagD;
4836}
4837
Douglas Gregor450f00842009-09-25 18:43:00 +00004838Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4839 SourceLocation ExternLoc,
4840 SourceLocation TemplateLoc,
4841 Declarator &D) {
4842 // Explicit instantiations always require a name.
4843 DeclarationName Name = GetNameForDeclarator(D);
4844 if (!Name) {
4845 if (!D.isInvalidType())
4846 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4847 diag::err_explicit_instantiation_requires_name)
4848 << D.getDeclSpec().getSourceRange()
4849 << D.getSourceRange();
4850
4851 return true;
4852 }
4853
4854 // The scope passed in may not be a decl scope. Zip up the scope tree until
4855 // we find one that is.
4856 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4857 (S->getFlags() & Scope::TemplateParamScope) != 0)
4858 S = S->getParent();
4859
4860 // Determine the type of the declaration.
4861 QualType R = GetTypeForDeclarator(D, S, 0);
4862 if (R.isNull())
4863 return true;
4864
4865 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4866 // Cannot explicitly instantiate a typedef.
4867 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4868 << Name;
4869 return true;
4870 }
4871
Douglas Gregor3c74d412009-10-14 20:14:33 +00004872 // C++0x [temp.explicit]p1:
4873 // [...] An explicit instantiation of a function template shall not use the
4874 // inline or constexpr specifiers.
4875 // Presumably, this also applies to member functions of class templates as
4876 // well.
4877 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4878 Diag(D.getDeclSpec().getInlineSpecLoc(),
4879 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00004880 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004881
4882 // FIXME: check for constexpr specifier.
4883
Douglas Gregore47f5a72009-10-14 23:41:34 +00004884 // C++0x [temp.explicit]p2:
4885 // There are two forms of explicit instantiation: an explicit instantiation
4886 // definition and an explicit instantiation declaration. An explicit
4887 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004888 TemplateSpecializationKind TSK
4889 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4890 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004891
John McCall27b18f82009-11-17 02:14:36 +00004892 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4893 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004894
4895 if (!R->isFunctionType()) {
4896 // C++ [temp.explicit]p1:
4897 // A [...] static data member of a class template can be explicitly
4898 // instantiated from the member definition associated with its class
4899 // template.
John McCall27b18f82009-11-17 02:14:36 +00004900 if (Previous.isAmbiguous())
4901 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004902
John McCall67c00872009-12-02 08:25:40 +00004903 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00004904 if (!Prev || !Prev->isStaticDataMember()) {
4905 // We expect to see a data data member here.
4906 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4907 << Name;
4908 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4909 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004910 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004911 return true;
4912 }
4913
4914 if (!Prev->getInstantiatedFromStaticDataMember()) {
4915 // FIXME: Check for explicit specialization?
4916 Diag(D.getIdentifierLoc(),
4917 diag::err_explicit_instantiation_data_member_not_instantiated)
4918 << Prev;
4919 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4920 // FIXME: Can we provide a note showing where this was declared?
4921 return true;
4922 }
4923
Douglas Gregore47f5a72009-10-14 23:41:34 +00004924 // C++0x [temp.explicit]p2:
4925 // If the explicit instantiation is for a member function, a member class
4926 // or a static data member of a class template specialization, the name of
4927 // the class template specialization in the qualified-id for the member
4928 // name shall be a simple-template-id.
4929 //
4930 // C++98 has the same restriction, just worded differently.
4931 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4932 Diag(D.getIdentifierLoc(),
4933 diag::err_explicit_instantiation_without_qualified_id)
4934 << Prev << D.getCXXScopeSpec().getRange();
4935
4936 // Check the scope of this explicit instantiation.
4937 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4938
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004939 // Verify that it is okay to explicitly instantiate here.
4940 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4941 assert(MSInfo && "Missing static data member specialization info?");
4942 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004943 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004944 MSInfo->getTemplateSpecializationKind(),
4945 MSInfo->getPointOfInstantiation(),
4946 SuppressNew))
4947 return true;
4948 if (SuppressNew)
4949 return DeclPtrTy();
4950
Douglas Gregor450f00842009-09-25 18:43:00 +00004951 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004952 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004953 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004954 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4955 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004956
4957 // FIXME: Create an ExplicitInstantiation node?
4958 return DeclPtrTy();
4959 }
4960
Douglas Gregor0e876e02009-09-25 23:53:26 +00004961 // If the declarator is a template-id, translate the parser's template
4962 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004963 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004964 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004965 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4966 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004967 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4968 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004969 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4970 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004971 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004972 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004973 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004974 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004975 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004976
Douglas Gregor450f00842009-09-25 18:43:00 +00004977 // C++ [temp.explicit]p1:
4978 // A [...] function [...] can be explicitly instantiated from its template.
4979 // A member function [...] of a class template can be explicitly
4980 // instantiated from the member definition associated with its class
4981 // template.
John McCall58cc69d2010-01-27 01:50:18 +00004982 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00004983 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4984 P != PEnd; ++P) {
4985 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004986 if (!HasExplicitTemplateArgs) {
4987 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4988 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4989 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004990
John McCall58cc69d2010-01-27 01:50:18 +00004991 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004992 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
4993 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00004994 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004995 }
4996 }
4997
4998 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4999 if (!FunTmpl)
5000 continue;
5001
John McCallbc077cf2010-02-08 23:07:23 +00005002 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005003 FunctionDecl *Specialization = 0;
5004 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005005 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005006 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005007 R, Specialization, Info)) {
5008 // FIXME: Keep track of almost-matches?
5009 (void)TDK;
5010 continue;
5011 }
5012
John McCall58cc69d2010-01-27 01:50:18 +00005013 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005014 }
5015
5016 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005017 UnresolvedSetIterator Result
5018 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005019 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005020 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5021 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5022 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005023
John McCall58cc69d2010-01-27 01:50:18 +00005024 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005025 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005026
5027 // Ignore access control bits, we don't need them for redeclaration checking.
5028 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005029
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005030 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005031 Diag(D.getIdentifierLoc(),
5032 diag::err_explicit_instantiation_member_function_not_instantiated)
5033 << Specialization
5034 << (Specialization->getTemplateSpecializationKind() ==
5035 TSK_ExplicitSpecialization);
5036 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5037 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005038 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005039
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005040 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005041 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5042 PrevDecl = Specialization;
5043
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005044 if (PrevDecl) {
5045 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005046 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005047 PrevDecl,
5048 PrevDecl->getTemplateSpecializationKind(),
5049 PrevDecl->getPointOfInstantiation(),
5050 SuppressNew))
5051 return true;
5052
5053 // FIXME: We may still want to build some representation of this
5054 // explicit specialization.
5055 if (SuppressNew)
5056 return DeclPtrTy();
5057 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005058
5059 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005060
5061 if (TSK == TSK_ExplicitInstantiationDefinition)
5062 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5063 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005064
Douglas Gregore47f5a72009-10-14 23:41:34 +00005065 // C++0x [temp.explicit]p2:
5066 // If the explicit instantiation is for a member function, a member class
5067 // or a static data member of a class template specialization, the name of
5068 // the class template specialization in the qualified-id for the member
5069 // name shall be a simple-template-id.
5070 //
5071 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005072 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005073 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005074 D.getCXXScopeSpec().isSet() &&
5075 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5076 Diag(D.getIdentifierLoc(),
5077 diag::err_explicit_instantiation_without_qualified_id)
5078 << Specialization << D.getCXXScopeSpec().getRange();
5079
5080 CheckExplicitInstantiationScope(*this,
5081 FunTmpl? (NamedDecl *)FunTmpl
5082 : Specialization->getInstantiatedFromMemberFunction(),
5083 D.getIdentifierLoc(),
5084 D.getCXXScopeSpec().isSet());
5085
Douglas Gregor450f00842009-09-25 18:43:00 +00005086 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5087 return DeclPtrTy();
5088}
5089
Douglas Gregor333489b2009-03-27 23:10:48 +00005090Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005091Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5092 const CXXScopeSpec &SS, IdentifierInfo *Name,
5093 SourceLocation TagLoc, SourceLocation NameLoc) {
5094 // This has to hold, because SS is expected to be defined.
5095 assert(Name && "Expected a name in a dependent tag");
5096
5097 NestedNameSpecifier *NNS
5098 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5099 if (!NNS)
5100 return true;
5101
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005102 ElaboratedTypeKeyword Keyword = ETK_None;
Douglas Gregore677daf2010-03-31 22:19:08 +00005103 switch (TagDecl::getTagKindForTypeSpec(TagSpec)) {
5104 case TagDecl::TK_struct: Keyword = ETK_Struct; break;
5105 case TagDecl::TK_class: Keyword = ETK_Class; break;
5106 case TagDecl::TK_union: Keyword = ETK_Union; break;
5107 case TagDecl::TK_enum: Keyword = ETK_Enum; break;
5108 }
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005109 assert(Keyword != ETK_None && "Invalid tag kind!");
5110
Douglas Gregore677daf2010-03-31 22:19:08 +00005111 return Context.getDependentNameType(Keyword, NNS, Name).getAsOpaquePtr();
John McCall7f41d982009-09-11 04:59:25 +00005112}
5113
5114Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00005115Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5116 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005117 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005118 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5119 if (!NNS)
5120 return true;
5121
5122 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005123 if (T.isNull())
5124 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00005125 return T.getAsOpaquePtr();
5126}
5127
Douglas Gregordce2b622009-04-01 00:28:59 +00005128Sema::TypeResult
5129Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5130 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005131 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005132 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00005133 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00005134 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00005135 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00005136 assert(TemplateId && "Expected a template specialization type");
5137
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005138 if (computeDeclContext(SS, false)) {
5139 // If we can compute a declaration context, then the "typename"
5140 // keyword was superfluous. Just build a QualifiedNameType to keep
5141 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00005142
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005143 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
5144 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
5145 }
Mike Stump11289f42009-09-09 15:08:12 +00005146
Douglas Gregor02085352010-03-31 20:19:30 +00005147 return Context.getDependentNameType(ETK_Typename, NNS, TemplateId)
5148 .getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00005149}
5150
Douglas Gregor333489b2009-03-27 23:10:48 +00005151/// \brief Build the type that describes a C++ typename specifier,
5152/// e.g., "typename T::type".
5153QualType
5154Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
5155 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005156 CXXRecordDecl *CurrentInstantiation = 0;
5157 if (NNS->isDependent()) {
5158 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00005159
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005160 // If the nested-name-specifier does not refer to the current
5161 // instantiation, then build a typename type.
5162 if (!CurrentInstantiation)
Douglas Gregor02085352010-03-31 20:19:30 +00005163 return Context.getDependentNameType(ETK_Typename, NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00005164
Douglas Gregorc707da62009-09-02 13:12:51 +00005165 // The nested-name-specifier refers to the current instantiation, so the
5166 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00005167 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00005168 // extraneous "typename" keywords, and we retroactively apply this DR to
5169 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005170 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005171
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005172 DeclContext *Ctx = 0;
5173
5174 if (CurrentInstantiation)
5175 Ctx = CurrentInstantiation;
5176 else {
5177 CXXScopeSpec SS;
5178 SS.setScopeRep(NNS);
5179 SS.setRange(Range);
5180 if (RequireCompleteDeclContext(SS))
5181 return QualType();
5182
5183 Ctx = computeDeclContext(SS);
5184 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005185 assert(Ctx && "No declaration context?");
5186
5187 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00005188 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
5189 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005190 unsigned DiagID = 0;
5191 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005192 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005193 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005194 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005195 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005196
5197 case LookupResult::NotFoundInCurrentInstantiation:
5198 // Okay, it's a member of an unknown instantiation.
Douglas Gregor02085352010-03-31 20:19:30 +00005199 return Context.getDependentNameType(ETK_Typename, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005200
5201 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00005202 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005203 // We found a type. Build a QualifiedNameType, since the
5204 // typename-specifier was just sugar. FIXME: Tell
5205 // QualifiedNameType that it has a "typename" prefix.
5206 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
5207 }
5208
5209 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005210 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005211 break;
5212
John McCalle61f2ba2009-11-18 02:36:19 +00005213 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005214 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005215 return QualType();
5216
Douglas Gregor333489b2009-03-27 23:10:48 +00005217 case LookupResult::FoundOverloaded:
5218 DiagID = diag::err_typename_nested_not_type;
5219 Referenced = *Result.begin();
5220 break;
5221
John McCall6538c932009-10-10 05:48:19 +00005222 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005223 return QualType();
5224 }
5225
5226 // If we get here, it's because name lookup did not find a
5227 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00005228 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005229 if (Referenced)
5230 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5231 << Name;
5232 return QualType();
5233}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005234
5235namespace {
5236 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005237 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005238 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005239 SourceLocation Loc;
5240 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005241
Douglas Gregor15acfb92009-08-06 16:20:37 +00005242 public:
Mike Stump11289f42009-09-09 15:08:12 +00005243 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005244 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005245 DeclarationName Entity)
5246 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005247 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005248
5249 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005250 /// transformed.
5251 ///
5252 /// For the purposes of type reconstruction, a type has already been
5253 /// transformed if it is NULL or if it is not dependent.
5254 bool AlreadyTransformed(QualType T) {
5255 return T.isNull() || !T->isDependentType();
5256 }
Mike Stump11289f42009-09-09 15:08:12 +00005257
5258 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005259 /// rebuilt.
5260 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005261
Douglas Gregor15acfb92009-08-06 16:20:37 +00005262 /// \brief Returns the name of the entity whose type is being rebuilt.
5263 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005264
Douglas Gregoref6ab412009-10-27 06:26:26 +00005265 /// \brief Sets the "base" location and entity when that
5266 /// information is known based on another transformation.
5267 void setBase(SourceLocation Loc, DeclarationName Entity) {
5268 this->Loc = Loc;
5269 this->Entity = Entity;
5270 }
5271
Douglas Gregor15acfb92009-08-06 16:20:37 +00005272 /// \brief Transforms an expression by returning the expression itself
5273 /// (an identity function).
5274 ///
5275 /// FIXME: This is completely unsafe; we will need to actually clone the
5276 /// expressions.
5277 Sema::OwningExprResult TransformExpr(Expr *E) {
5278 return getSema().Owned(E);
5279 }
Mike Stump11289f42009-09-09 15:08:12 +00005280
Douglas Gregor15acfb92009-08-06 16:20:37 +00005281 /// \brief Transforms a typename type by determining whether the type now
5282 /// refers to a member of the current instantiation, and then
5283 /// type-checking and building a QualifiedNameType (when possible).
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005284 QualType TransformDependentNameType(TypeLocBuilder &TLB, DependentNameTypeLoc TL,
Douglas Gregorfe17d252010-02-16 19:09:40 +00005285 QualType ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00005286 };
5287}
5288
Mike Stump11289f42009-09-09 15:08:12 +00005289QualType
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005290CurrentInstantiationRebuilder::TransformDependentNameType(TypeLocBuilder &TLB,
5291 DependentNameTypeLoc TL,
Douglas Gregorfe17d252010-02-16 19:09:40 +00005292 QualType ObjectType) {
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005293 DependentNameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00005294
Douglas Gregor15acfb92009-08-06 16:20:37 +00005295 NestedNameSpecifier *NNS
5296 = TransformNestedNameSpecifier(T->getQualifier(),
Douglas Gregorfe17d252010-02-16 19:09:40 +00005297 /*FIXME:*/SourceRange(getBaseLocation()),
5298 ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00005299 if (!NNS)
5300 return QualType();
5301
5302 // If the nested-name-specifier did not change, and we cannot compute the
5303 // context corresponding to the nested-name-specifier, then this
5304 // typename type will not change; exit early.
5305 CXXScopeSpec SS;
5306 SS.setRange(SourceRange(getBaseLocation()));
5307 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00005308
5309 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005310 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00005311 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00005312
5313 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00005314 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00005315 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00005316 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00005317 = TransformType(QualType(TemplateId, 0));
5318 if (NewTemplateId.isNull())
5319 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005320
Douglas Gregor15acfb92009-08-06 16:20:37 +00005321 if (NNS == T->getQualifier() &&
5322 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00005323 Result = QualType(T, 0);
5324 else
Douglas Gregor02085352010-03-31 20:19:30 +00005325 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
5326 NNS, NewTemplateId);
John McCall0ad16662009-10-29 08:12:44 +00005327 } else
Douglas Gregor02085352010-03-31 20:19:30 +00005328 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
5329 NNS, T->getIdentifier(),
5330 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00005331
Douglas Gregor281c4862010-03-07 23:26:22 +00005332 if (Result.isNull())
5333 return QualType();
5334
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005335 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
John McCall0ad16662009-10-29 08:12:44 +00005336 NewTL.setNameLoc(TL.getNameLoc());
5337 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005338}
5339
5340/// \brief Rebuilds a type within the context of the current instantiation.
5341///
Mike Stump11289f42009-09-09 15:08:12 +00005342/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005343/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005344/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005345/// partial specialization thereof). This routine will rebuild that type now
5346/// that we have entered the declarator's scope, which may produce different
5347/// canonical types, e.g.,
5348///
5349/// \code
5350/// template<typename T>
5351/// struct X {
5352/// typedef T* pointer;
5353/// pointer data();
5354/// };
5355///
5356/// template<typename T>
5357/// typename X<T>::pointer X<T>::data() { ... }
5358/// \endcode
5359///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005360/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005361/// since we do not know that we can look into X<T> when we parsed the type.
5362/// This function will rebuild the type, performing the lookup of "pointer"
5363/// in X<T> and returning a QualifiedNameType whose canonical type is the same
5364/// as the canonical type of T*, allowing the return types of the out-of-line
5365/// definition and the declaration to match.
5366QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
5367 DeclarationName Name) {
5368 if (T.isNull() || !T->isDependentType())
5369 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005370
Douglas Gregor15acfb92009-08-06 16:20:37 +00005371 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5372 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005373}
Douglas Gregorbe999392009-09-15 16:23:51 +00005374
5375/// \brief Produces a formatted string that describes the binding of
5376/// template parameters to template arguments.
5377std::string
5378Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5379 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005380 // FIXME: For variadic templates, we'll need to get the structured list.
5381 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5382 Args.flat_size());
5383}
5384
5385std::string
5386Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5387 const TemplateArgument *Args,
5388 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005389 std::string Result;
5390
Douglas Gregore62e6a02009-11-11 19:13:48 +00005391 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005392 return Result;
5393
5394 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005395 if (I >= NumArgs)
5396 break;
5397
Douglas Gregorbe999392009-09-15 16:23:51 +00005398 if (I == 0)
5399 Result += "[with ";
5400 else
5401 Result += ", ";
5402
5403 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5404 Result += Id->getName();
5405 } else {
5406 Result += '$';
5407 Result += llvm::utostr(I);
5408 }
5409
5410 Result += " = ";
5411
5412 switch (Args[I].getKind()) {
5413 case TemplateArgument::Null:
5414 Result += "<no value>";
5415 break;
5416
5417 case TemplateArgument::Type: {
5418 std::string TypeStr;
5419 Args[I].getAsType().getAsStringInternal(TypeStr,
5420 Context.PrintingPolicy);
5421 Result += TypeStr;
5422 break;
5423 }
5424
5425 case TemplateArgument::Declaration: {
5426 bool Unnamed = true;
5427 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5428 if (ND->getDeclName()) {
5429 Unnamed = false;
5430 Result += ND->getNameAsString();
5431 }
5432 }
5433
5434 if (Unnamed) {
5435 Result += "<anonymous>";
5436 }
5437 break;
5438 }
5439
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005440 case TemplateArgument::Template: {
5441 std::string Str;
5442 llvm::raw_string_ostream OS(Str);
5443 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5444 Result += OS.str();
5445 break;
5446 }
5447
Douglas Gregorbe999392009-09-15 16:23:51 +00005448 case TemplateArgument::Integral: {
5449 Result += Args[I].getAsIntegral()->toString(10);
5450 break;
5451 }
5452
5453 case TemplateArgument::Expression: {
5454 assert(false && "No expressions in deduced template arguments!");
5455 Result += "<expression>";
5456 break;
5457 }
5458
5459 case TemplateArgument::Pack:
5460 // FIXME: Format template argument packs
5461 Result += "<template argument pack>";
5462 break;
5463 }
5464 }
5465
5466 Result += ']';
5467 return Result;
5468}