blob: f94f34626d5443d6b21b28b9e1b349a0eadc1276 [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
John McCall83024632010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCallcc14d1f2010-08-24 08:50:51 +000014#include "clang/Sema/Scope.h"
John McCallde6836a2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000017#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000019#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000020#include "clang/AST/ExprCXX.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000022#include "clang/AST/DeclTemplate.h"
John McCalla020a012010-10-20 05:44:58 +000023#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000024#include "clang/AST/TypeVisitor.h"
John McCall8b0666c2010-08-20 18:27:03 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000027#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000029#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000030using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000031using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000032
John McCall9b72f892010-11-10 02:40:36 +000033// Exported for use by Parser.
34SourceRange
35clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
36 unsigned N) {
37 if (!N) return SourceRange();
38 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
39}
40
Douglas Gregorb7bfe792009-09-02 22:59:36 +000041/// \brief Determine whether the declaration found is acceptable as the name
42/// of a template and, if so, return that template declaration. Otherwise,
43/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000044static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
45 NamedDecl *Orig) {
46 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000047
Douglas Gregorb7bfe792009-09-02 22:59:36 +000048 if (isa<TemplateDecl>(D))
John McCalle9cccd82010-06-16 08:42:20 +000049 return Orig;
Mike Stump11289f42009-09-09 15:08:12 +000050
Douglas Gregorb7bfe792009-09-02 22:59:36 +000051 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
52 // C++ [temp.local]p1:
53 // Like normal (non-template) classes, class templates have an
54 // injected-class-name (Clause 9). The injected-class-name
55 // can be used with or without a template-argument-list. When
56 // it is used without a template-argument-list, it is
57 // equivalent to the injected-class-name followed by the
58 // template-parameters of the class template enclosed in
59 // <>. When it is used with a template-argument-list, it
60 // refers to the specified class template specialization,
61 // which could be the current specialization or another
62 // specialization.
63 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000064 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000065 if (Record->getDescribedClassTemplate())
66 return Record->getDescribedClassTemplate();
67
68 if (ClassTemplateSpecializationDecl *Spec
69 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
70 return Spec->getSpecializedTemplate();
71 }
Mike Stump11289f42009-09-09 15:08:12 +000072
Douglas Gregorb7bfe792009-09-02 22:59:36 +000073 return 0;
74 }
Mike Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregorb7bfe792009-09-02 22:59:36 +000076 return 0;
77}
78
John McCalle66edc12009-11-24 19:00:30 +000079static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor41f90302010-04-12 20:54:26 +000080 // The set of class templates we've already seen.
81 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000082 LookupResult::Filter filter = R.makeFilter();
83 while (filter.hasNext()) {
84 NamedDecl *Orig = filter.next();
John McCalle9cccd82010-06-16 08:42:20 +000085 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCalle66edc12009-11-24 19:00:30 +000086 if (!Repl)
87 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000088 else if (Repl != Orig) {
89
90 // C++ [temp.local]p3:
91 // A lookup that finds an injected-class-name (10.2) can result in an
92 // ambiguity in certain cases (for example, if it is found in more than
93 // one base class). If all of the injected-class-names that are found
94 // refer to specializations of the same class template, and if the name
95 // is followed by a template-argument-list, the reference refers to the
96 // class template itself and not a specialization thereof, and is not
97 // ambiguous.
98 //
99 // FIXME: Will we eventually have to do the same for alias templates?
100 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
101 if (!ClassTemplates.insert(ClassTmpl)) {
102 filter.erase();
103 continue;
104 }
John McCallbd8062d2010-08-13 07:02:08 +0000105
106 // FIXME: we promote access to public here as a workaround to
107 // the fact that LookupResult doesn't let us remember that we
108 // found this template through a particular injected class name,
109 // which means we end up doing nasty things to the invariants.
110 // Pretending that access is public is *much* safer.
111 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000112 }
John McCalle66edc12009-11-24 19:00:30 +0000113 }
114 filter.done();
115}
116
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000117TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000118 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000119 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000120 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000121 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000122 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000123 TemplateTy &TemplateResult,
124 bool &MemberOfUnknownSpecialization) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000125 assert(getLangOptions().CPlusPlus && "No template names in C!");
126
Douglas Gregor3cf81312009-11-03 23:16:33 +0000127 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000128 MemberOfUnknownSpecialization = false;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000129
130 switch (Name.getKind()) {
131 case UnqualifiedId::IK_Identifier:
132 TName = DeclarationName(Name.Identifier);
133 break;
134
135 case UnqualifiedId::IK_OperatorFunctionId:
136 TName = Context.DeclarationNames.getCXXOperatorName(
137 Name.OperatorFunctionId.Operator);
138 break;
139
Alexis Hunted0530f2009-11-28 08:58:14 +0000140 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000141 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
142 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000143
Douglas Gregor3cf81312009-11-03 23:16:33 +0000144 default:
145 return TNK_Non_template;
146 }
Mike Stump11289f42009-09-09 15:08:12 +0000147
John McCallba7bf592010-08-24 05:47:05 +0000148 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000149
Douglas Gregorff18cc12009-12-31 08:11:17 +0000150 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
151 LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000152 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
153 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000154 if (R.empty()) return TNK_Non_template;
155 if (R.isAmbiguous()) {
156 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000157 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000158
159 // FIXME: we might have ambiguous templates, in which case we
160 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000161 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000162 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000163
John McCalld28ae272009-12-02 08:04:21 +0000164 TemplateName Template;
165 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000166
John McCalld28ae272009-12-02 08:04:21 +0000167 unsigned ResultCount = R.end() - R.begin();
168 if (ResultCount > 1) {
169 // We assume that we'll preserve the qualifier from a function
170 // template name in other ways.
171 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
172 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000173
174 // We'll do this lookup again later.
175 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000176 } else {
John McCalld28ae272009-12-02 08:04:21 +0000177 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
178
179 if (SS.isSet() && !SS.isInvalid()) {
180 NestedNameSpecifier *Qualifier
181 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000182 Template = Context.getQualifiedTemplateName(Qualifier,
183 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000184 } else {
185 Template = TemplateName(TD);
186 }
187
John McCalldcc71402010-08-13 02:23:42 +0000188 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000189 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000190
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
193 } else {
John McCalld28ae272009-12-02 08:04:21 +0000194 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
195 TemplateKind = TNK_Type_template;
196 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000197 }
Mike Stump11289f42009-09-09 15:08:12 +0000198
John McCalld28ae272009-12-02 08:04:21 +0000199 TemplateResult = TemplateTy::make(Template);
200 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000201}
202
Douglas Gregor18473f32010-01-12 21:28:44 +0000203bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
204 SourceLocation IILoc,
205 Scope *S,
206 const CXXScopeSpec *SS,
207 TemplateTy &SuggestedTemplate,
208 TemplateNameKind &SuggestedKind) {
209 // We can't recover unless there's a dependent scope specifier preceding the
210 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000211 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000212 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
213 computeDeclContext(*SS))
214 return false;
215
216 // The code is missing a 'template' keyword prior to the dependent template
217 // name.
218 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
219 Diag(IILoc, diag::err_template_kw_missing)
220 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000221 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000222 SuggestedTemplate
223 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
224 SuggestedKind = TNK_Dependent_template_name;
225 return true;
226}
227
John McCalle66edc12009-11-24 19:00:30 +0000228void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000229 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000230 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000231 bool EnteringContext,
232 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000233 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000234 MemberOfUnknownSpecialization = false;
John McCalle66edc12009-11-24 19:00:30 +0000235 DeclContext *LookupCtx = 0;
236 bool isDependent = false;
237 if (!ObjectType.isNull()) {
238 // This nested-name-specifier occurs in a member access expression, e.g.,
239 // x->B::f, and we are looking into the type of the object.
240 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
241 LookupCtx = computeDeclContext(ObjectType);
242 isDependent = ObjectType->isDependentType();
243 assert((isDependent || !ObjectType->isIncompleteType()) &&
244 "Caller should have completed object type");
245 } else if (SS.isSet()) {
246 // This nested-name-specifier occurs after another nested-name-specifier,
247 // so long into the context associated with the prior nested-name-specifier.
248 LookupCtx = computeDeclContext(SS, EnteringContext);
249 isDependent = isDependentScopeSpecifier(SS);
250
251 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000252 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000253 return;
254 }
255
256 bool ObjectTypeSearchedInScope = false;
257 if (LookupCtx) {
258 // Perform "qualified" name lookup into the declaration context we
259 // computed, which is either the type of the base of a member access
260 // expression or the declaration context associated with a prior
261 // nested-name-specifier.
262 LookupQualifiedName(Found, LookupCtx);
263
264 if (!ObjectType.isNull() && Found.empty()) {
265 // C++ [basic.lookup.classref]p1:
266 // In a class member access expression (5.2.5), if the . or -> token is
267 // immediately followed by an identifier followed by a <, the
268 // identifier must be looked up to determine whether the < is the
269 // beginning of a template argument list (14.2) or a less-than operator.
270 // The identifier is first looked up in the class of the object
271 // expression. If the identifier is not found, it is then looked up in
272 // the context of the entire postfix-expression and shall name a class
273 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000274 if (S) LookupName(Found, S);
275 ObjectTypeSearchedInScope = true;
276 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000277 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000278 // We cannot look into a dependent object type or nested nme
279 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000280 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000281 return;
282 } else {
283 // Perform unqualified name lookup in the current scope.
284 LookupName(Found, S);
285 }
286
Douglas Gregorc119dd52010-01-12 17:06:20 +0000287 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000288 // If we did not find any names, attempt to correct any typos.
289 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000290 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregorc048c522010-06-29 19:27:42 +0000291 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000292 FilterAcceptableTemplateNames(Context, Found);
John McCalle9cccd82010-06-16 08:42:20 +0000293 if (!Found.empty()) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000294 if (LookupCtx)
295 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
296 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000297 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000298 Found.getLookupName().getAsString());
299 else
300 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
301 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000302 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000303 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000304 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
305 Diag(Template->getLocation(), diag::note_previous_decl)
306 << Template->getDeclName();
John McCalle9cccd82010-06-16 08:42:20 +0000307 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000308 } else {
309 Found.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +0000310 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000311 }
312 }
313
John McCalle66edc12009-11-24 19:00:30 +0000314 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000315 if (Found.empty()) {
316 if (isDependent)
317 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000318 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000319 }
John McCalle66edc12009-11-24 19:00:30 +0000320
321 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
322 // C++ [basic.lookup.classref]p1:
323 // [...] If the lookup in the class of the object expression finds a
324 // template, the name is also looked up in the context of the entire
325 // postfix-expression and [...]
326 //
327 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
328 LookupOrdinaryName);
329 LookupName(FoundOuter, S);
330 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000331
John McCalle66edc12009-11-24 19:00:30 +0000332 if (FoundOuter.empty()) {
333 // - if the name is not found, the name found in the class of the
334 // object expression is used, otherwise
335 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
336 // - if the name is found in the context of the entire
337 // postfix-expression and does not name a class template, the name
338 // found in the class of the object expression is used, otherwise
John McCalle9cccd82010-06-16 08:42:20 +0000339 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000340 // - if the name found is a class template, it must refer to the same
341 // entity as the one found in the class of the object expression,
342 // otherwise the program is ill-formed.
343 if (!Found.isSingleResult() ||
344 Found.getFoundDecl()->getCanonicalDecl()
345 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
346 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000347 diag::ext_nested_name_member_ref_lookup_ambiguous)
348 << Found.getLookupName()
349 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000350 Diag(Found.getRepresentativeDecl()->getLocation(),
351 diag::note_ambig_member_ref_object_type)
352 << ObjectType;
353 Diag(FoundOuter.getFoundDecl()->getLocation(),
354 diag::note_ambig_member_ref_scope);
355
356 // Recover by taking the template that we found in the object
357 // expression's type.
358 }
359 }
360 }
361}
362
John McCallcd4b4772009-12-02 03:53:29 +0000363/// ActOnDependentIdExpression - Handle a dependent id-expression that
364/// was just parsed. This is only possible with an explicit scope
365/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000366ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000367Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000368 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000369 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000370 const TemplateArgumentListInfo *TemplateArgs) {
371 NestedNameSpecifier *Qualifier
372 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall87fe5d52010-05-20 01:18:31 +0000373
374 DeclContext *DC = getFunctionLevelDeclContext();
John McCalle66edc12009-11-24 19:00:30 +0000375
John McCallcd4b4772009-12-02 03:53:29 +0000376 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000377 isa<CXXMethodDecl>(DC) &&
378 cast<CXXMethodDecl>(DC)->isInstance()) {
379 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallcd4b4772009-12-02 03:53:29 +0000380
John McCalle66edc12009-11-24 19:00:30 +0000381 // Since the 'this' expression is synthesized, we don't need to
382 // perform the double-lookup check.
383 NamedDecl *FirstQualifierInScope = 0;
384
John McCall2d74de92009-12-01 22:10:20 +0000385 return Owned(CXXDependentScopeMemberExpr::Create(Context,
386 /*This*/ 0, ThisType,
387 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000388 /*Op*/ SourceLocation(),
389 Qualifier, SS.getRange(),
390 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000391 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000392 TemplateArgs));
393 }
394
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000395 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000396}
397
John McCalldadc5752010-08-24 06:29:42 +0000398ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000399Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000400 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000401 const TemplateArgumentListInfo *TemplateArgs) {
402 return Owned(DependentScopeDeclRefExpr::Create(Context,
403 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
404 SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000405 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000406 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000407}
408
Douglas Gregor5101c242008-12-05 18:15:24 +0000409/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
410/// that the template parameter 'PrevDecl' is being shadowed by a new
411/// declaration at location Loc. Returns true to indicate that this is
412/// an error, and false otherwise.
413bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000414 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000415
416 // Microsoft Visual C++ permits template parameters to be shadowed.
417 if (getLangOptions().Microsoft)
418 return false;
419
420 // C++ [temp.local]p4:
421 // A template-parameter shall not be redeclared within its
422 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000423 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000424 << cast<NamedDecl>(PrevDecl)->getDeclName();
425 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
426 return true;
427}
428
Douglas Gregor463421d2009-03-03 04:44:36 +0000429/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000430/// the parameter D to reference the templated declaration and return a pointer
431/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000432TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
433 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
434 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000435 return Temp;
436 }
437 return 0;
438}
439
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000440static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
441 const ParsedTemplateArgument &Arg) {
442
443 switch (Arg.getKind()) {
444 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000445 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000446 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
447 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000448 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000449 return TemplateArgumentLoc(TemplateArgument(T), DI);
450 }
451
452 case ParsedTemplateArgument::NonType: {
453 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
454 return TemplateArgumentLoc(TemplateArgument(E), E);
455 }
456
457 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000458 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000459 return TemplateArgumentLoc(TemplateArgument(Template),
460 Arg.getScopeSpec().getRange(),
461 Arg.getLocation());
462 }
463 }
464
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000465 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000466 return TemplateArgumentLoc();
467}
468
469/// \brief Translates template arguments as provided by the parser
470/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000471void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
472 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000473 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000474 TemplateArgs.addArgument(translateTemplateArgument(*this,
475 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000476}
477
Douglas Gregor5101c242008-12-05 18:15:24 +0000478/// ActOnTypeParameter - Called when a C++ template type parameter
479/// (e.g., "typename T") has been parsed. Typename specifies whether
480/// the keyword "typename" was used to declare the type parameter
481/// (otherwise, "class" was used), and KeyLoc is the location of the
482/// "class" or "typename" keyword. ParamName is the name of the
483/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregor2ebcae12010-06-16 15:23:05 +0000484/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000485/// If the type parameter has a default argument, it will be added
486/// later via ActOnTypeParameterDefault.
John McCall48871652010-08-21 09:40:31 +0000487Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
488 SourceLocation EllipsisLoc,
489 SourceLocation KeyLoc,
490 IdentifierInfo *ParamName,
491 SourceLocation ParamNameLoc,
492 unsigned Depth, unsigned Position,
493 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000494 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000495 assert(S->isTemplateParamScope() &&
496 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000497 bool Invalid = false;
498
499 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000500 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000501 LookupOrdinaryName,
502 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000503 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000504 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000505 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000506 }
507
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000508 SourceLocation Loc = ParamNameLoc;
509 if (!ParamName)
510 Loc = KeyLoc;
511
Douglas Gregor5101c242008-12-05 18:15:24 +0000512 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000513 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
514 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000515 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000516 if (Invalid)
517 Param->setInvalidDecl();
518
519 if (ParamName) {
520 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000521 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000522 IdResolver.AddDecl(Param);
523 }
524
Douglas Gregordc13ded2010-07-01 00:00:45 +0000525 // Handle the default argument, if provided.
526 if (DefaultArg) {
527 TypeSourceInfo *DefaultTInfo;
528 GetTypeFromParser(DefaultArg, &DefaultTInfo);
529
530 assert(DefaultTInfo && "expected source information for type");
531
532 // C++0x [temp.param]p9:
533 // A default template-argument may be specified for any kind of
534 // template-parameter that is not a template parameter pack.
535 if (Ellipsis) {
536 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
John McCall48871652010-08-21 09:40:31 +0000537 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000538 }
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000539
540 // Check for unexpanded parameter packs.
541 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
542 UPPC_DefaultArgument))
543 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000544
545 // Check the template argument itself.
546 if (CheckTemplateArgument(Param, DefaultTInfo)) {
547 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000548 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000549 }
550
551 Param->setDefaultArgument(DefaultTInfo, false);
552 }
553
John McCall48871652010-08-21 09:40:31 +0000554 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000555}
556
Douglas Gregor463421d2009-03-03 04:44:36 +0000557/// \brief Check that the type of a non-type template parameter is
558/// well-formed.
559///
560/// \returns the (possibly-promoted) parameter type if valid;
561/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000562QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000563Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000564 // We don't allow variably-modified types as the type of non-type template
565 // parameters.
566 if (T->isVariablyModifiedType()) {
567 Diag(Loc, diag::err_variably_modified_nontype_template_param)
568 << T;
569 return QualType();
570 }
571
Douglas Gregor463421d2009-03-03 04:44:36 +0000572 // C++ [temp.param]p4:
573 //
574 // A non-type template-parameter shall have one of the following
575 // (optionally cv-qualified) types:
576 //
577 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000578 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000579 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000580 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000581 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000582 T->isReferenceType() ||
583 // -- pointer to member.
584 T->isMemberPointerType() ||
585 // If T is a dependent type, we can't do the check now, so we
586 // assume that it is well-formed.
587 T->isDependentType())
588 return T;
589 // C++ [temp.param]p8:
590 //
591 // A non-type template-parameter of type "array of T" or
592 // "function returning T" is adjusted to be of type "pointer to
593 // T" or "pointer to function returning T", respectively.
594 else if (T->isArrayType())
595 // FIXME: Keep the type prior to promotion?
596 return Context.getArrayDecayedType(T);
597 else if (T->isFunctionType())
598 // FIXME: Keep the type prior to promotion?
599 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000600
Douglas Gregor463421d2009-03-03 04:44:36 +0000601 Diag(Loc, diag::err_template_nontype_parm_bad_type)
602 << T;
603
604 return QualType();
605}
606
John McCall48871652010-08-21 09:40:31 +0000607Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
608 unsigned Depth,
609 unsigned Position,
610 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000611 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000612 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
613 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000614
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000615 assert(S->isTemplateParamScope() &&
616 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000617 bool Invalid = false;
618
619 IdentifierInfo *ParamName = D.getIdentifier();
620 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000621 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000622 LookupOrdinaryName,
623 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000624 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000625 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000626 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000627 }
628
Douglas Gregore1520d62010-12-16 08:56:23 +0000629 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
630 UPPC_NonTypeTemplateParameterType)) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000631 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000632 Invalid = true;
Douglas Gregore1520d62010-12-16 08:56:23 +0000633 } else {
634 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
635 if (T.isNull()) {
636 T = Context.IntTy; // Recover with an 'int' type.
637 Invalid = true;
638 }
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000639 }
Douglas Gregore1520d62010-12-16 08:56:23 +0000640
Douglas Gregor5101c242008-12-05 18:15:24 +0000641 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000642 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
643 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000644 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000645 if (Invalid)
646 Param->setInvalidDecl();
647
648 if (D.getIdentifier()) {
649 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000650 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000651 IdResolver.AddDecl(Param);
652 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000653
654 // Check the well-formedness of the default template argument, if provided.
John McCallb268a282010-08-23 23:25:46 +0000655 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000656 // Check for unexpanded parameter packs.
657 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
658 return Param;
659
Douglas Gregordc13ded2010-07-01 00:00:45 +0000660 TemplateArgument Converted;
661 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
662 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000663 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000664 }
665
John McCallb268a282010-08-23 23:25:46 +0000666 Param->setDefaultArgument(Default, false);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000667 }
668
John McCall48871652010-08-21 09:40:31 +0000669 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000670}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000671
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000672/// ActOnTemplateTemplateParameter - Called when a C++ template template
673/// parameter (e.g. T in template <template <typename> class T> class array)
674/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000675Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
676 SourceLocation TmpLoc,
677 TemplateParamsTy *Params,
678 IdentifierInfo *Name,
679 SourceLocation NameLoc,
680 unsigned Depth,
681 unsigned Position,
682 SourceLocation EqualLoc,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000683 const ParsedTemplateArgument &Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000684 assert(S->isTemplateParamScope() &&
685 "Template template parameter not in template parameter scope!");
686
687 // Construct the parameter object.
688 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000689 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Douglas Gregor713602b2010-08-31 17:01:39 +0000690 NameLoc.isInvalid()? TmpLoc : NameLoc,
691 Depth, Position, Name,
Douglas Gregora02bb372010-10-21 17:26:49 +0000692 Params);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000693
Douglas Gregordc13ded2010-07-01 00:00:45 +0000694 // If the template template parameter has a name, then link the identifier
695 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000696 if (Name) {
John McCall48871652010-08-21 09:40:31 +0000697 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000698 IdResolver.AddDecl(Param);
699 }
700
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000701 if (Params->size() == 0) {
702 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
703 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
704 Param->setInvalidDecl();
705 }
706
Douglas Gregordc13ded2010-07-01 00:00:45 +0000707 if (!Default.isInvalid()) {
708 // Check only that we have a template template argument. We don't want to
709 // try to check well-formedness now, because our template template parameter
710 // might have dependent types in its template parameters, which we wouldn't
711 // be able to match now.
712 //
713 // If none of the template template parameter's template arguments mention
714 // other template parameters, we could actually perform more checking here.
715 // However, it isn't worth doing.
716 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
717 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
718 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
719 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000720 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000721 }
722
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000723 // Check for unexpanded parameter packs.
724 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
725 DefaultArg.getArgument().getAsTemplate(),
726 UPPC_DefaultArgument))
727 return Param;
728
Douglas Gregordc13ded2010-07-01 00:00:45 +0000729 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000730 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000731
John McCall48871652010-08-21 09:40:31 +0000732 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000733}
734
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000735/// ActOnTemplateParameterList - Builds a TemplateParameterList that
736/// contains the template parameters in Params/NumParams.
737Sema::TemplateParamsTy *
738Sema::ActOnTemplateParameterList(unsigned Depth,
739 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000740 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000741 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000742 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000743 SourceLocation RAngleLoc) {
744 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000745 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000746
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000747 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000748 (NamedDecl**)Params, NumParams,
749 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000750}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000751
John McCall3e11ebe2010-03-15 10:12:16 +0000752static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
753 if (SS.isSet())
754 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
755 SS.getRange());
756}
757
John McCallfaf5fb42010-08-26 23:41:50 +0000758DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000759Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000760 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000761 IdentifierInfo *Name, SourceLocation NameLoc,
762 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000763 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000764 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000765 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000766 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000767 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000768 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000769
770 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000771 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000772 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000773
Abramo Bagnara6150c882010-05-11 21:36:43 +0000774 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
775 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000776
777 // There is no such thing as an unnamed class template.
778 if (!Name) {
779 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000780 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000781 }
782
783 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000784 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000785 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000786 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000787 if (SS.isNotEmpty() && !SS.isInvalid()) {
788 SemanticContext = computeDeclContext(SS, true);
789 if (!SemanticContext) {
790 // FIXME: Produce a reasonable diagnostic here
791 return true;
792 }
Mike Stump11289f42009-09-09 15:08:12 +0000793
John McCall0b66eb32010-05-01 00:40:08 +0000794 if (RequireCompleteDeclContext(SS, SemanticContext))
795 return true;
796
John McCall27b18f82009-11-17 02:14:36 +0000797 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000798 } else {
799 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000800 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000801 }
Mike Stump11289f42009-09-09 15:08:12 +0000802
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000803 if (Previous.isAmbiguous())
804 return true;
805
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000806 NamedDecl *PrevDecl = 0;
807 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000808 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000809
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000810 // If there is a previous declaration with the same name, check
811 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000812 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000813 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000814
815 // We may have found the injected-class-name of a class template,
816 // class template partial specialization, or class template specialization.
817 // In these cases, grab the template that is being defined or specialized.
818 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
819 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
820 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
821 PrevClassTemplate
822 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
823 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
824 PrevClassTemplate
825 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
826 ->getSpecializedTemplate();
827 }
828 }
829
John McCalld43784f2009-12-18 11:25:59 +0000830 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000831 // C++ [namespace.memdef]p3:
832 // [...] When looking for a prior declaration of a class or a function
833 // declared as a friend, and when the name of the friend class or
834 // function is neither a qualified name nor a template-id, scopes outside
835 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000836 if (!SS.isSet()) {
837 DeclContext *OutermostContext = CurContext;
838 while (!OutermostContext->isFileContext())
839 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000840
Douglas Gregorb74b1032010-04-18 17:37:40 +0000841 if (PrevDecl &&
842 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
843 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
844 SemanticContext = PrevDecl->getDeclContext();
845 } else {
846 // Declarations in outer scopes don't matter. However, the outermost
847 // context we computed is the semantic context for our new
848 // declaration.
849 PrevDecl = PrevClassTemplate = 0;
850 SemanticContext = OutermostContext;
851 }
John McCall90d3bb92009-12-17 23:21:11 +0000852 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000853
John McCall90d3bb92009-12-17 23:21:11 +0000854 if (CurContext->isDependentContext()) {
855 // If this is a dependent context, we don't want to link the friend
856 // class template to the template in scope, because that would perform
857 // checking of the template parameter lists that can't be performed
858 // until the outer context is instantiated.
859 PrevDecl = PrevClassTemplate = 0;
860 }
861 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
862 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000863
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000864 if (PrevClassTemplate) {
865 // Ensure that the template parameter lists are compatible.
866 if (!TemplateParameterListsAreEqual(TemplateParams,
867 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000868 /*Complain=*/true,
869 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000870 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000871
872 // C++ [temp.class]p4:
873 // In a redeclaration, partial specialization, explicit
874 // specialization or explicit instantiation of a class template,
875 // the class-key shall agree in kind with the original class
876 // template declaration (7.1.5.3).
877 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000878 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000879 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000880 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000881 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000882 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000883 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000884 }
885
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000886 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000887 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000888 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000889 Diag(NameLoc, diag::err_redefinition) << Name;
890 Diag(Def->getLocation(), diag::note_previous_definition);
891 // FIXME: Would it make sense to try to "forget" the previous
892 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000893 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000894 }
895 }
896 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
897 // Maybe we will complain about the shadowed template parameter.
898 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
899 // Just pretend that we didn't see the previous declaration.
900 PrevDecl = 0;
901 } else if (PrevDecl) {
902 // C++ [temp]p5:
903 // A class template shall not have the same name as any other
904 // template, class, function, object, enumeration, enumerator,
905 // namespace, or type in the same scope (3.3), except as specified
906 // in (14.5.4).
907 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
908 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000909 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000910 }
911
Douglas Gregordba32632009-02-10 19:49:53 +0000912 // Check the template parameter list of this declaration, possibly
913 // merging in the template parameter list from the previous class
914 // template declaration.
915 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000916 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
917 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000918 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000919
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000920 if (SS.isSet()) {
921 // If the name of the template was qualified, we must be defining the
922 // template out-of-line.
923 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
924 !(TUK == TUK_Friend && CurContext->isDependentContext()))
925 Diag(NameLoc, diag::err_member_def_does_not_match)
926 << Name << SemanticContext << SS.getRange();
927 }
928
Mike Stump11289f42009-09-09 15:08:12 +0000929 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000930 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000931 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000932 PrevClassTemplate->getTemplatedDecl() : 0,
933 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000934 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000935
936 ClassTemplateDecl *NewTemplate
937 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
938 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000939 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000940 NewClass->setDescribedClassTemplate(NewTemplate);
941
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000942 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000943 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +0000944 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000945 assert(T->isDependentType() && "Class template type is not dependent?");
946 (void)T;
947
Douglas Gregorcf915552009-10-13 16:30:37 +0000948 // If we are providing an explicit specialization of a member that is a
949 // class template, make a note of that.
950 if (PrevClassTemplate &&
951 PrevClassTemplate->getInstantiatedFromMemberTemplate())
952 PrevClassTemplate->setMemberSpecialization();
953
Anders Carlsson137108d2009-03-26 01:24:28 +0000954 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000955 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000956 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000957
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000958 // Set the lexical context of these templates
959 NewClass->setLexicalDeclContext(CurContext);
960 NewTemplate->setLexicalDeclContext(CurContext);
961
John McCall9bb74a52009-07-31 02:45:11 +0000962 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000963 NewClass->startDefinition();
964
965 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000966 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000967
John McCall27b5c252009-09-14 21:59:20 +0000968 if (TUK != TUK_Friend)
969 PushOnScopeChains(NewTemplate, S);
970 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000971 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000972 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000973 NewClass->setAccess(PrevClassTemplate->getAccess());
974 }
John McCall27b5c252009-09-14 21:59:20 +0000975
Douglas Gregor3dad8422009-09-26 06:47:28 +0000976 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
977 PrevClassTemplate != NULL);
978
John McCall27b5c252009-09-14 21:59:20 +0000979 // Friend templates are visible in fairly strange ways.
980 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000981 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall27b5c252009-09-14 21:59:20 +0000982 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
983 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
984 PushOnScopeChains(NewTemplate, EnclosingScope,
985 /* AddToContext = */ false);
986 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000987
988 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
989 NewClass->getLocation(),
990 NewTemplate,
991 /*FIXME:*/NewClass->getLocation());
992 Friend->setAccess(AS_public);
993 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000994 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000995
Douglas Gregordba32632009-02-10 19:49:53 +0000996 if (Invalid) {
997 NewTemplate->setInvalidDecl();
998 NewClass->setInvalidDecl();
999 }
John McCall48871652010-08-21 09:40:31 +00001000 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001001}
1002
Douglas Gregored5731f2009-11-25 17:50:39 +00001003/// \brief Diagnose the presence of a default template argument on a
1004/// template parameter, which is ill-formed in certain contexts.
1005///
1006/// \returns true if the default template argument should be dropped.
1007static bool DiagnoseDefaultTemplateArgument(Sema &S,
1008 Sema::TemplateParamListContext TPC,
1009 SourceLocation ParamLoc,
1010 SourceRange DefArgRange) {
1011 switch (TPC) {
1012 case Sema::TPC_ClassTemplate:
1013 return false;
1014
1015 case Sema::TPC_FunctionTemplate:
1016 // C++ [temp.param]p9:
1017 // A default template-argument shall not be specified in a
1018 // function template declaration or a function template
1019 // definition [...]
1020 // (This sentence is not in C++0x, per DR226).
1021 if (!S.getLangOptions().CPlusPlus0x)
1022 S.Diag(ParamLoc,
1023 diag::err_template_parameter_default_in_function_template)
1024 << DefArgRange;
1025 return false;
1026
1027 case Sema::TPC_ClassTemplateMember:
1028 // C++0x [temp.param]p9:
1029 // A default template-argument shall not be specified in the
1030 // template-parameter-lists of the definition of a member of a
1031 // class template that appears outside of the member's class.
1032 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1033 << DefArgRange;
1034 return true;
1035
1036 case Sema::TPC_FriendFunctionTemplate:
1037 // C++ [temp.param]p9:
1038 // A default template-argument shall not be specified in a
1039 // friend template declaration.
1040 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1041 << DefArgRange;
1042 return true;
1043
1044 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1045 // for friend function templates if there is only a single
1046 // declaration (and it is a definition). Strange!
1047 }
1048
1049 return false;
1050}
1051
Douglas Gregordba32632009-02-10 19:49:53 +00001052/// \brief Checks the validity of a template parameter list, possibly
1053/// considering the template parameter list from a previous
1054/// declaration.
1055///
1056/// If an "old" template parameter list is provided, it must be
1057/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1058/// template parameter list.
1059///
1060/// \param NewParams Template parameter list for a new template
1061/// declaration. This template parameter list will be updated with any
1062/// default arguments that are carried through from the previous
1063/// template parameter list.
1064///
1065/// \param OldParams If provided, template parameter list from a
1066/// previous declaration of the same template. Default template
1067/// arguments will be merged from the old template parameter list to
1068/// the new template parameter list.
1069///
Douglas Gregored5731f2009-11-25 17:50:39 +00001070/// \param TPC Describes the context in which we are checking the given
1071/// template parameter list.
1072///
Douglas Gregordba32632009-02-10 19:49:53 +00001073/// \returns true if an error occurred, false otherwise.
1074bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001075 TemplateParameterList *OldParams,
1076 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001077 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001078
Douglas Gregordba32632009-02-10 19:49:53 +00001079 // C++ [temp.param]p10:
1080 // The set of default template-arguments available for use with a
1081 // template declaration or definition is obtained by merging the
1082 // default arguments from the definition (if in scope) and all
1083 // declarations in scope in the same way default function
1084 // arguments are (8.3.6).
1085 bool SawDefaultArgument = false;
1086 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001087
Anders Carlsson327865d2009-06-12 23:20:15 +00001088 bool SawParameterPack = false;
1089 SourceLocation ParameterPackLoc;
1090
Mike Stumpc89c8e32009-02-11 23:03:27 +00001091 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001092 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001093 if (OldParams)
1094 OldParam = OldParams->begin();
1095
1096 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1097 NewParamEnd = NewParams->end();
1098 NewParam != NewParamEnd; ++NewParam) {
1099 // Variables used to diagnose redundant default arguments
1100 bool RedundantDefaultArg = false;
1101 SourceLocation OldDefaultLoc;
1102 SourceLocation NewDefaultLoc;
1103
1104 // Variables used to diagnose missing default arguments
1105 bool MissingDefaultArg = false;
1106
Anders Carlsson327865d2009-06-12 23:20:15 +00001107 // C++0x [temp.param]p11:
1108 // If a template parameter of a class template is a template parameter pack,
1109 // it must be the last template parameter.
1110 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001111 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001112 diag::err_template_param_pack_must_be_last_template_parameter);
1113 Invalid = true;
1114 }
1115
Douglas Gregordba32632009-02-10 19:49:53 +00001116 if (TemplateTypeParmDecl *NewTypeParm
1117 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001118 // Check the presence of a default argument here.
1119 if (NewTypeParm->hasDefaultArgument() &&
1120 DiagnoseDefaultTemplateArgument(*this, TPC,
1121 NewTypeParm->getLocation(),
1122 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001123 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001124 NewTypeParm->removeDefaultArgument();
1125
1126 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001127 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001128 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001129
Anders Carlsson327865d2009-06-12 23:20:15 +00001130 if (NewTypeParm->isParameterPack()) {
1131 assert(!NewTypeParm->hasDefaultArgument() &&
1132 "Parameter packs can't have a default argument!");
1133 SawParameterPack = true;
1134 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001135 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001136 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001137 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1138 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1139 SawDefaultArgument = true;
1140 RedundantDefaultArg = true;
1141 PreviousDefaultArgLoc = NewDefaultLoc;
1142 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1143 // Merge the default argument from the old declaration to the
1144 // new declaration.
1145 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001146 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001147 true);
1148 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1149 } else if (NewTypeParm->hasDefaultArgument()) {
1150 SawDefaultArgument = true;
1151 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1152 } else if (SawDefaultArgument)
1153 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001154 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001155 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001156 // Check the presence of a default argument here.
1157 if (NewNonTypeParm->hasDefaultArgument() &&
1158 DiagnoseDefaultTemplateArgument(*this, TPC,
1159 NewNonTypeParm->getLocation(),
1160 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001161 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001162 }
1163
Mike Stump12b8ce12009-08-04 21:02:39 +00001164 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001165 NonTypeTemplateParmDecl *OldNonTypeParm
1166 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001167 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001168 NewNonTypeParm->hasDefaultArgument()) {
1169 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1170 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1171 SawDefaultArgument = true;
1172 RedundantDefaultArg = true;
1173 PreviousDefaultArgLoc = NewDefaultLoc;
1174 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1175 // Merge the default argument from the old declaration to the
1176 // new declaration.
1177 SawDefaultArgument = true;
1178 // FIXME: We need to create a new kind of "default argument"
1179 // expression that points to a previous template template
1180 // parameter.
1181 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001182 OldNonTypeParm->getDefaultArgument(),
1183 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001184 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1185 } else if (NewNonTypeParm->hasDefaultArgument()) {
1186 SawDefaultArgument = true;
1187 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1188 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001189 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001190 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001191 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001192 TemplateTemplateParmDecl *NewTemplateParm
1193 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001194 if (NewTemplateParm->hasDefaultArgument() &&
1195 DiagnoseDefaultTemplateArgument(*this, TPC,
1196 NewTemplateParm->getLocation(),
1197 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001198 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001199
1200 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001201 TemplateTemplateParmDecl *OldTemplateParm
1202 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001203 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001204 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001205 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1206 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001207 SawDefaultArgument = true;
1208 RedundantDefaultArg = true;
1209 PreviousDefaultArgLoc = NewDefaultLoc;
1210 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1211 // Merge the default argument from the old declaration to the
1212 // new declaration.
1213 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001214 // FIXME: We need to create a new kind of "default argument" expression
1215 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001216 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001217 OldTemplateParm->getDefaultArgument(),
1218 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001219 PreviousDefaultArgLoc
1220 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001221 } else if (NewTemplateParm->hasDefaultArgument()) {
1222 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001223 PreviousDefaultArgLoc
1224 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001225 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001226 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001227 }
1228
1229 if (RedundantDefaultArg) {
1230 // C++ [temp.param]p12:
1231 // A template-parameter shall not be given default arguments
1232 // by two different declarations in the same scope.
1233 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1234 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1235 Invalid = true;
1236 } else if (MissingDefaultArg) {
1237 // C++ [temp.param]p11:
1238 // If a template-parameter has a default template-argument,
1239 // all subsequent template-parameters shall have a default
1240 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001241 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001242 diag::err_template_param_default_arg_missing);
1243 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1244 Invalid = true;
1245 }
1246
1247 // If we have an old template parameter list that we're merging
1248 // in, move on to the next parameter.
1249 if (OldParams)
1250 ++OldParam;
1251 }
1252
1253 return Invalid;
1254}
Douglas Gregord32e0282009-02-09 23:23:08 +00001255
John McCalla020a012010-10-20 05:44:58 +00001256namespace {
1257
1258/// A class which looks for a use of a certain level of template
1259/// parameter.
1260struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1261 typedef RecursiveASTVisitor<DependencyChecker> super;
1262
1263 unsigned Depth;
1264 bool Match;
1265
1266 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1267 NamedDecl *ND = Params->getParam(0);
1268 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1269 Depth = PD->getDepth();
1270 } else if (NonTypeTemplateParmDecl *PD =
1271 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1272 Depth = PD->getDepth();
1273 } else {
1274 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1275 }
1276 }
1277
1278 bool Matches(unsigned ParmDepth) {
1279 if (ParmDepth >= Depth) {
1280 Match = true;
1281 return true;
1282 }
1283 return false;
1284 }
1285
1286 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1287 return !Matches(T->getDepth());
1288 }
1289
1290 bool TraverseTemplateName(TemplateName N) {
1291 if (TemplateTemplateParmDecl *PD =
1292 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1293 if (Matches(PD->getDepth())) return false;
1294 return super::TraverseTemplateName(N);
1295 }
1296
1297 bool VisitDeclRefExpr(DeclRefExpr *E) {
1298 if (NonTypeTemplateParmDecl *PD =
1299 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1300 if (PD->getDepth() == Depth) {
1301 Match = true;
1302 return false;
1303 }
1304 }
1305 return super::VisitDeclRefExpr(E);
1306 }
1307};
1308}
1309
1310/// Determines whether a template-id depends on the given parameter
1311/// list.
1312static bool
1313DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId,
1314 TemplateParameterList *Params) {
1315 DependencyChecker Checker(Params);
1316 Checker.TraverseType(QualType(TemplateId, 0));
1317 return Checker.Match;
1318}
1319
Mike Stump11289f42009-09-09 15:08:12 +00001320/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001321/// specifier, returning the template parameter list that applies to the
1322/// name.
1323///
1324/// \param DeclStartLoc the start of the declaration that has a scope
1325/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001326///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001327/// \param SS the scope specifier that will be matched to the given template
1328/// parameter lists. This scope specifier precedes a qualified name that is
1329/// being declared.
1330///
1331/// \param ParamLists the template parameter lists, from the outermost to the
1332/// innermost template parameter lists.
1333///
1334/// \param NumParamLists the number of template parameter lists in ParamLists.
1335///
John McCalle820e5e2010-04-13 20:37:33 +00001336/// \param IsFriend Whether to apply the slightly different rules for
1337/// matching template parameters to scope specifiers in friend
1338/// declarations.
1339///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001340/// \param IsExplicitSpecialization will be set true if the entity being
1341/// declared is an explicit specialization, false otherwise.
1342///
Mike Stump11289f42009-09-09 15:08:12 +00001343/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001344/// name that is preceded by the scope specifier @p SS. This template
1345/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001346/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001347/// template specialization), or may be NULL (if we were's declaring isn't
1348/// itself a template).
1349TemplateParameterList *
1350Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1351 const CXXScopeSpec &SS,
1352 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001353 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001354 bool IsFriend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001355 bool &IsExplicitSpecialization,
1356 bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001357 IsExplicitSpecialization = false;
1358
Douglas Gregord8d297c2009-07-21 23:53:31 +00001359 // Find the template-ids that occur within the nested-name-specifier. These
1360 // template-ids will match up with the template parameter lists.
1361 llvm::SmallVector<const TemplateSpecializationType *, 4>
1362 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001363 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1364 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001365 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1366 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001367 const Type *T = NNS->getAsType();
1368 if (!T) break;
1369
1370 // C++0x [temp.expl.spec]p17:
1371 // A member or a member template may be nested within many
1372 // enclosing class templates. In an explicit specialization for
1373 // such a member, the member declaration shall be preceded by a
1374 // template<> for each enclosing class template that is
1375 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001376 //
1377 // Following the existing practice of GNU and EDG, we allow a typedef of a
1378 // template specialization type.
John McCall717d9b02010-12-10 11:01:00 +00001379 while (const TypedefType *TT = dyn_cast<TypedefType>(T))
1380 T = TT->getDecl()->getUnderlyingType().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001381
Mike Stump11289f42009-09-09 15:08:12 +00001382 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001383 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001384 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1385 if (!Template)
1386 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001387
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001388 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001389 ClassTemplateSpecializationDecl *SpecDecl
1390 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1391 // If the nested name specifier refers to an explicit specialization,
1392 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001393 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1394 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001395 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001396 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001397 }
Mike Stump11289f42009-09-09 15:08:12 +00001398
Douglas Gregord8d297c2009-07-21 23:53:31 +00001399 TemplateIdsInSpecifier.push_back(SpecType);
1400 }
1401 }
Mike Stump11289f42009-09-09 15:08:12 +00001402
Douglas Gregord8d297c2009-07-21 23:53:31 +00001403 // Reverse the list of template-ids in the scope specifier, so that we can
1404 // more easily match up the template-ids and the template parameter lists.
1405 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001406
Douglas Gregord8d297c2009-07-21 23:53:31 +00001407 SourceLocation FirstTemplateLoc = DeclStartLoc;
1408 if (NumParamLists)
1409 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001410
Douglas Gregord8d297c2009-07-21 23:53:31 +00001411 // Match the template-ids found in the specifier to the template parameter
1412 // lists.
John McCalla020a012010-10-20 05:44:58 +00001413 unsigned ParamIdx = 0, TemplateIdx = 0;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001414 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
John McCalla020a012010-10-20 05:44:58 +00001415 TemplateIdx != NumTemplateIds; ++TemplateIdx) {
1416 const TemplateSpecializationType *TemplateId
1417 = TemplateIdsInSpecifier[TemplateIdx];
Douglas Gregor15301382009-07-30 17:40:51 +00001418 bool DependentTemplateId = TemplateId->isDependentType();
John McCalla020a012010-10-20 05:44:58 +00001419
1420 // In friend declarations we can have template-ids which don't
1421 // depend on the corresponding template parameter lists. But
1422 // assume that empty parameter lists are supposed to match this
1423 // template-id.
1424 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) {
1425 if (!DependentTemplateId ||
1426 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx]))
1427 continue;
1428 }
1429
1430 if (ParamIdx >= NumParamLists) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001431 // We have a template-id without a corresponding template parameter
1432 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001433
1434 // ...which is fine if this is a friend declaration.
1435 if (IsFriend) {
1436 IsExplicitSpecialization = true;
1437 break;
1438 }
1439
Douglas Gregord8d297c2009-07-21 23:53:31 +00001440 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001441 // FIXME: the location information here isn't great.
1442 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001443 diag::err_template_spec_needs_template_parameters)
John McCalla020a012010-10-20 05:44:58 +00001444 << QualType(TemplateId, 0)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001445 << SS.getRange();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001446 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001447 } else {
1448 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1449 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001450 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001451 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001452 }
1453 return 0;
1454 }
Mike Stump11289f42009-09-09 15:08:12 +00001455
Douglas Gregord8d297c2009-07-21 23:53:31 +00001456 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001457 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001458 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001459
John McCall2408e322010-04-27 00:57:59 +00001460 // Are there cases in (e.g.) friends where this won't match?
1461 if (const InjectedClassNameType *Injected
1462 = TemplateId->getAs<InjectedClassNameType>()) {
1463 CXXRecordDecl *Record = Injected->getDecl();
1464 if (ClassTemplatePartialSpecializationDecl *Partial =
1465 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1466 ExpectedTemplateParams = Partial->getTemplateParameters();
1467 else
1468 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1469 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001470 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001471
John McCall2408e322010-04-27 00:57:59 +00001472 if (ExpectedTemplateParams)
John McCalla020a012010-10-20 05:44:58 +00001473 TemplateParameterListsAreEqual(ParamLists[ParamIdx],
John McCall2408e322010-04-27 00:57:59 +00001474 ExpectedTemplateParams,
1475 true, TPL_TemplateMatch);
1476
John McCalla020a012010-10-20 05:44:58 +00001477 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1478 TPC_ClassTemplateMember);
1479 } else if (ParamLists[ParamIdx]->size() > 0)
1480 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001481 diag::err_template_param_list_matches_nontemplate)
1482 << TemplateId
John McCalla020a012010-10-20 05:44:58 +00001483 << ParamLists[ParamIdx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001484 else
1485 IsExplicitSpecialization = true;
John McCalla020a012010-10-20 05:44:58 +00001486
1487 ++ParamIdx;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001488 }
Mike Stump11289f42009-09-09 15:08:12 +00001489
Douglas Gregord8d297c2009-07-21 23:53:31 +00001490 // If there were at least as many template-ids as there were template
1491 // parameter lists, then there are no template parameter lists remaining for
1492 // the declaration itself.
John McCalla020a012010-10-20 05:44:58 +00001493 if (ParamIdx >= NumParamLists)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001494 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001495
Douglas Gregord8d297c2009-07-21 23:53:31 +00001496 // If there were too many template parameter lists, complain about that now.
John McCalla020a012010-10-20 05:44:58 +00001497 if (ParamIdx != NumParamLists - 1) {
1498 while (ParamIdx < NumParamLists - 1) {
1499 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0;
1500 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001501 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1502 : diag::err_template_spec_extra_headers)
John McCalla020a012010-10-20 05:44:58 +00001503 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1504 ParamLists[ParamIdx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001505
1506 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1507 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1508 diag::note_explicit_template_spec_does_not_need_header)
1509 << ExplicitSpecializationsInSpecifier.back();
1510 ExplicitSpecializationsInSpecifier.pop_back();
1511 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001512
1513 // We have a template parameter list with no corresponding scope, which
1514 // means that the resulting template declaration can't be instantiated
1515 // properly (we'll end up with dependent nodes when we shouldn't).
1516 if (!isExplicitSpecHeader)
1517 Invalid = true;
1518
John McCalla020a012010-10-20 05:44:58 +00001519 ++ParamIdx;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001520 }
1521 }
Mike Stump11289f42009-09-09 15:08:12 +00001522
Douglas Gregord8d297c2009-07-21 23:53:31 +00001523 // Return the last template parameter list, which corresponds to the
1524 // entity being declared.
1525 return ParamLists[NumParamLists - 1];
1526}
1527
Douglas Gregordc572a32009-03-30 22:58:21 +00001528QualType Sema::CheckTemplateIdType(TemplateName Name,
1529 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001530 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001531 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001532 if (!Template) {
1533 // The template name does not resolve to a template, so we just
1534 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001535 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001536 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001537
Douglas Gregorc40290e2009-03-09 23:48:35 +00001538 // Check that the template argument list is well-formed for this
1539 // template.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001540 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00001541 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001542 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001543 return QualType();
1544
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001545 assert((Converted.size() == Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001546 "Converted template argument list is too short!");
1547
1548 QualType CanonType;
1549
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001550 if (Name.isDependent() ||
1551 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001552 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001553 // This class template specialization is a dependent
1554 // type. Therefore, its canonical type is another class template
1555 // specialization type that contains all of the converted
1556 // arguments in canonical form. This ensures that, e.g., A<T> and
1557 // A<T, T> have identical types when A is declared as:
1558 //
1559 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001560 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001561 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001562 Converted.data(),
1563 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00001564
Douglas Gregora8e02e72009-07-28 23:00:59 +00001565 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001566 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001567 // In the future, we need to teach getTemplateSpecializationType to only
1568 // build the canonical type and return that to us.
1569 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001570
1571 // This might work out to be a current instantiation, in which
1572 // case the canonical type needs to be the InjectedClassNameType.
1573 //
1574 // TODO: in theory this could be a simple hashtable lookup; most
1575 // changes to CurContext don't change the set of current
1576 // instantiations.
1577 if (isa<ClassTemplateDecl>(Template)) {
1578 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1579 // If we get out to a namespace, we're done.
1580 if (Ctx->isFileContext()) break;
1581
1582 // If this isn't a record, keep looking.
1583 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1584 if (!Record) continue;
1585
1586 // Look for one of the two cases with InjectedClassNameTypes
1587 // and check whether it's the same template.
1588 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1589 !Record->getDescribedClassTemplate())
1590 continue;
1591
1592 // Fetch the injected class name type and check whether its
1593 // injected type is equal to the type we just built.
1594 QualType ICNT = Context.getTypeDeclType(Record);
1595 QualType Injected = cast<InjectedClassNameType>(ICNT)
1596 ->getInjectedSpecializationType();
1597
1598 if (CanonType != Injected->getCanonicalTypeInternal())
1599 continue;
1600
1601 // If so, the canonical type of this TST is the injected
1602 // class name type of the record we just found.
1603 assert(ICNT.isCanonical());
1604 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001605 break;
1606 }
1607 }
Mike Stump11289f42009-09-09 15:08:12 +00001608 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001609 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001610 // Find the class template specialization declaration that
1611 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001612 void *InsertPos = 0;
1613 ClassTemplateSpecializationDecl *Decl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001614 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
1615 InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001616 if (!Decl) {
1617 // This is the first time we have referenced this class template
1618 // specialization. Create the canonical declaration and add it to
1619 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001620 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001621 ClassTemplate->getTemplatedDecl()->getTagKind(),
1622 ClassTemplate->getDeclContext(),
1623 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001624 ClassTemplate,
1625 Converted.data(),
1626 Converted.size(), 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001627 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001628 Decl->setLexicalDeclContext(CurContext);
1629 }
1630
1631 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001632 assert(isa<RecordType>(CanonType) &&
1633 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001634 }
Mike Stump11289f42009-09-09 15:08:12 +00001635
Douglas Gregorc40290e2009-03-09 23:48:35 +00001636 // Build the fully-sugared type for this class template
1637 // specialization, which refers back to the class template
1638 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001639 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001640}
1641
John McCallfaf5fb42010-08-26 23:41:50 +00001642TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001643Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001644 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001645 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001646 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001647 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001648
Douglas Gregorc40290e2009-03-09 23:48:35 +00001649 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001650 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001651 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001652
John McCall6b51f282009-11-23 01:53:49 +00001653 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001654 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001655
1656 if (Result.isNull())
1657 return true;
1658
John McCallbcd03502009-12-07 02:54:59 +00001659 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001660 TemplateSpecializationTypeLoc TL
1661 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1662 TL.setTemplateNameLoc(TemplateLoc);
1663 TL.setLAngleLoc(LAngleLoc);
1664 TL.setRAngleLoc(RAngleLoc);
1665 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1666 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1667
John McCallba7bf592010-08-24 05:47:05 +00001668 return CreateParsedType(Result, DI);
John McCalld8fe9af2009-09-08 17:47:29 +00001669}
John McCall06f6fe8d2009-09-04 01:14:41 +00001670
Craig Silverstein9bc166a2010-11-18 08:32:02 +00001671TypeResult Sema::ActOnTagTemplateIdType(CXXScopeSpec &SS,
1672 TypeResult TypeResult,
John McCallfaf5fb42010-08-26 23:41:50 +00001673 TagUseKind TUK,
1674 TypeSpecifierType TagSpec,
1675 SourceLocation TagLoc) {
John McCalld8fe9af2009-09-08 17:47:29 +00001676 if (TypeResult.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00001677 return ::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001678
John McCallbcd03502009-12-07 02:54:59 +00001679 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001680 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001681
John McCalld8fe9af2009-09-08 17:47:29 +00001682 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001683 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001684
John McCalld8fe9af2009-09-08 17:47:29 +00001685 if (const RecordType *RT = Type->getAs<RecordType>()) {
1686 RecordDecl *D = RT->getDecl();
1687
1688 IdentifierInfo *Id = D->getIdentifier();
1689 assert(Id && "templated class must have an identifier");
1690
1691 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1692 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001693 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001694 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001695 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001696 }
1697 }
1698
Abramo Bagnara6150c882010-05-11 21:36:43 +00001699 ElaboratedTypeKeyword Keyword
1700 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1701 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001702
Craig Silverstein9bc166a2010-11-18 08:32:02 +00001703 TypeSourceInfo *ElabDI = Context.CreateTypeSourceInfo(ElabType);
1704 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(ElabDI->getTypeLoc());
1705 TL.setKeywordLoc(TagLoc);
1706 TL.setQualifierRange(SS.getRange());
1707 TL.getNamedTypeLoc().initializeFullCopy(DI->getTypeLoc());
1708 return CreateParsedType(ElabType, ElabDI);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001709}
1710
John McCalldadc5752010-08-24 06:29:42 +00001711ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001712 LookupResult &R,
1713 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001714 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001715 // FIXME: Can we do any checking at this point? I guess we could check the
1716 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001717 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001718 // though.
John McCalle66edc12009-11-24 19:00:30 +00001719
1720 // These should be filtered out by our callers.
1721 assert(!R.empty() && "empty lookup results when building templateid");
1722 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1723
1724 NestedNameSpecifier *Qualifier = 0;
1725 SourceRange QualifierRange;
1726 if (SS.isSet()) {
1727 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1728 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001729 }
John McCall58cc69d2010-01-27 01:50:18 +00001730
1731 // We don't want lookup warnings at this point.
1732 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001733
John McCalle66edc12009-11-24 19:00:30 +00001734 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00001735 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001736 Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001737 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001738 RequiresADL, TemplateArgs,
1739 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001740
1741 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001742}
1743
John McCalle66edc12009-11-24 19:00:30 +00001744// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00001745ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001746Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001747 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +00001748 const TemplateArgumentListInfo &TemplateArgs) {
1749 DeclContext *DC;
1750 if (!(DC = computeDeclContext(SS, false)) ||
1751 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001752 RequireCompleteDeclContext(SS, DC))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001753 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001754
Douglas Gregor786123d2010-05-21 23:18:07 +00001755 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001756 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001757 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1758 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001759
John McCalle66edc12009-11-24 19:00:30 +00001760 if (R.isAmbiguous())
1761 return ExprError();
1762
1763 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001764 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1765 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001766 return ExprError();
1767 }
1768
1769 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001770 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1771 << (NestedNameSpecifier*) SS.getScopeRep()
1772 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001773 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1774 return ExprError();
1775 }
1776
1777 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001778}
1779
Douglas Gregorb67535d2009-03-31 00:43:58 +00001780/// \brief Form a dependent template name.
1781///
1782/// This action forms a dependent template name given the template
1783/// name and its (presumably dependent) scope specifier. For
1784/// example, given "MetaFun::template apply", the scope specifier \p
1785/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1786/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregorbb119652010-06-16 23:00:59 +00001787TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1788 SourceLocation TemplateKWLoc,
1789 CXXScopeSpec &SS,
1790 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00001791 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00001792 bool EnteringContext,
1793 TemplateTy &Result) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001794 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1795 !getLangOptions().CPlusPlus0x)
1796 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1797 << FixItHint::CreateRemoval(TemplateKWLoc);
1798
Douglas Gregor9abe2372010-01-19 16:01:07 +00001799 DeclContext *LookupCtx = 0;
1800 if (SS.isSet())
1801 LookupCtx = computeDeclContext(SS, EnteringContext);
1802 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00001803 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00001804 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001805 // C++0x [temp.names]p5:
1806 // If a name prefixed by the keyword template is not the name of
1807 // a template, the program is ill-formed. [Note: the keyword
1808 // template may not be applied to non-template members of class
1809 // templates. -end note ] [ Note: as is the case with the
1810 // typename prefix, the template prefix is allowed in cases
1811 // where it is not strictly necessary; i.e., when the
1812 // nested-name-specifier or the expression on the left of the ->
1813 // or . is not dependent on a template-parameter, or the use
1814 // does not appear in the scope of a template. -end note]
1815 //
1816 // Note: C++03 was more strict here, because it banned the use of
1817 // the "template" keyword prior to a template-name that was not a
1818 // dependent name. C++ DR468 relaxed this requirement (the
1819 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001820 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00001821 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001822 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1823 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00001824 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001825 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1826 isa<CXXRecordDecl>(LookupCtx) &&
1827 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregorbb119652010-06-16 23:00:59 +00001828 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00001829 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001830 Diag(Name.getSourceRange().getBegin(),
1831 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001832 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001833 << Name.getSourceRange()
1834 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001835 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00001836 } else {
1837 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00001838 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001839 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001840 }
1841
Mike Stump11289f42009-09-09 15:08:12 +00001842 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001843 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001844
1845 switch (Name.getKind()) {
1846 case UnqualifiedId::IK_Identifier:
Douglas Gregorbb119652010-06-16 23:00:59 +00001847 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1848 Name.Identifier));
1849 return TNK_Dependent_template_name;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001850
Douglas Gregor71395fa2009-11-04 00:56:37 +00001851 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00001852 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001853 Name.OperatorFunctionId.Operator));
Douglas Gregorbb119652010-06-16 23:00:59 +00001854 return TNK_Dependent_template_name;
Alexis Hunted0530f2009-11-28 08:58:14 +00001855
1856 case UnqualifiedId::IK_LiteralOperatorId:
1857 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1858
Douglas Gregor3cf81312009-11-03 23:16:33 +00001859 default:
1860 break;
1861 }
1862
1863 Diag(Name.getSourceRange().getBegin(),
1864 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001865 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001866 << Name.getSourceRange()
1867 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001868 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001869}
1870
Mike Stump11289f42009-09-09 15:08:12 +00001871bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001872 const TemplateArgumentLoc &AL,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001873 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001874 const TemplateArgument &Arg = AL.getArgument();
1875
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001876 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001877 switch(Arg.getKind()) {
1878 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001879 // C++ [temp.arg.type]p1:
1880 // A template-argument for a template-parameter which is a
1881 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001882 break;
1883 case TemplateArgument::Template: {
1884 // We have a template type parameter but the template argument
1885 // is a template without any arguments.
1886 SourceRange SR = AL.getSourceRange();
1887 TemplateName Name = Arg.getAsTemplate();
1888 Diag(SR.getBegin(), diag::err_template_missing_args)
1889 << Name << SR;
1890 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1891 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001892
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001893 return true;
1894 }
1895 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001896 // We have a template type parameter but the template argument
1897 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001898 SourceRange SR = AL.getSourceRange();
1899 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001900 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001901
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001902 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001903 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001904 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001905
John McCallbcd03502009-12-07 02:54:59 +00001906 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001907 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001908
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001909 // Add the converted template type argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001910 Converted.push_back(
John McCall0ad16662009-10-29 08:12:44 +00001911 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001912 return false;
1913}
1914
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001915/// \brief Substitute template arguments into the default template argument for
1916/// the given template type parameter.
1917///
1918/// \param SemaRef the semantic analysis object for which we are performing
1919/// the substitution.
1920///
1921/// \param Template the template that we are synthesizing template arguments
1922/// for.
1923///
1924/// \param TemplateLoc the location of the template name that started the
1925/// template-id we are checking.
1926///
1927/// \param RAngleLoc the location of the right angle bracket ('>') that
1928/// terminates the template-id.
1929///
1930/// \param Param the template template parameter whose default we are
1931/// substituting into.
1932///
1933/// \param Converted the list of template arguments provided for template
1934/// parameters that precede \p Param in the template parameter list.
1935///
1936/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001937static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001938SubstDefaultTemplateArgument(Sema &SemaRef,
1939 TemplateDecl *Template,
1940 SourceLocation TemplateLoc,
1941 SourceLocation RAngleLoc,
1942 TemplateTypeParmDecl *Param,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001943 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001944 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001945
1946 // If the argument type is dependent, instantiate it now based
1947 // on the previously-computed template arguments.
1948 if (ArgType->getType()->isDependentType()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001949 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1950 Converted.data(), Converted.size());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001951
1952 MultiLevelTemplateArgumentList AllTemplateArgs
1953 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1954
1955 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001956 Template, Converted.data(),
1957 Converted.size(),
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001958 SourceRange(TemplateLoc, RAngleLoc));
1959
1960 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1961 Param->getDefaultArgumentLoc(),
1962 Param->getDeclName());
1963 }
1964
1965 return ArgType;
1966}
1967
1968/// \brief Substitute template arguments into the default template argument for
1969/// the given non-type template parameter.
1970///
1971/// \param SemaRef the semantic analysis object for which we are performing
1972/// the substitution.
1973///
1974/// \param Template the template that we are synthesizing template arguments
1975/// for.
1976///
1977/// \param TemplateLoc the location of the template name that started the
1978/// template-id we are checking.
1979///
1980/// \param RAngleLoc the location of the right angle bracket ('>') that
1981/// terminates the template-id.
1982///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001983/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001984/// substituting into.
1985///
1986/// \param Converted the list of template arguments provided for template
1987/// parameters that precede \p Param in the template parameter list.
1988///
1989/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00001990static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001991SubstDefaultTemplateArgument(Sema &SemaRef,
1992 TemplateDecl *Template,
1993 SourceLocation TemplateLoc,
1994 SourceLocation RAngleLoc,
1995 NonTypeTemplateParmDecl *Param,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001996 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
1997 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1998 Converted.data(), Converted.size());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001999
2000 MultiLevelTemplateArgumentList AllTemplateArgs
2001 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2002
2003 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002004 Template, Converted.data(),
2005 Converted.size(),
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00002006 SourceRange(TemplateLoc, RAngleLoc));
2007
2008 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2009}
2010
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002011/// \brief Substitute template arguments into the default template argument for
2012/// the given template template parameter.
2013///
2014/// \param SemaRef the semantic analysis object for which we are performing
2015/// the substitution.
2016///
2017/// \param Template the template that we are synthesizing template arguments
2018/// for.
2019///
2020/// \param TemplateLoc the location of the template name that started the
2021/// template-id we are checking.
2022///
2023/// \param RAngleLoc the location of the right angle bracket ('>') that
2024/// terminates the template-id.
2025///
2026/// \param Param the template template parameter whose default we are
2027/// substituting into.
2028///
2029/// \param Converted the list of template arguments provided for template
2030/// parameters that precede \p Param in the template parameter list.
2031///
2032/// \returns the substituted template argument, or NULL if an error occurred.
2033static TemplateName
2034SubstDefaultTemplateArgument(Sema &SemaRef,
2035 TemplateDecl *Template,
2036 SourceLocation TemplateLoc,
2037 SourceLocation RAngleLoc,
2038 TemplateTemplateParmDecl *Param,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002039 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2040 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2041 Converted.data(), Converted.size());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002042
2043 MultiLevelTemplateArgumentList AllTemplateArgs
2044 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2045
2046 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002047 Template, Converted.data(),
2048 Converted.size(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002049 SourceRange(TemplateLoc, RAngleLoc));
2050
2051 return SemaRef.SubstTemplateName(
2052 Param->getDefaultArgument().getArgument().getAsTemplate(),
2053 Param->getDefaultArgument().getTemplateNameLoc(),
2054 AllTemplateArgs);
2055}
2056
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002057/// \brief If the given template parameter has a default template
2058/// argument, substitute into that default template argument and
2059/// return the corresponding template argument.
2060TemplateArgumentLoc
2061Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2062 SourceLocation TemplateLoc,
2063 SourceLocation RAngleLoc,
2064 Decl *Param,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002065 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2066 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002067 if (!TypeParm->hasDefaultArgument())
2068 return TemplateArgumentLoc();
2069
John McCallbcd03502009-12-07 02:54:59 +00002070 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002071 TemplateLoc,
2072 RAngleLoc,
2073 TypeParm,
2074 Converted);
2075 if (DI)
2076 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2077
2078 return TemplateArgumentLoc();
2079 }
2080
2081 if (NonTypeTemplateParmDecl *NonTypeParm
2082 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2083 if (!NonTypeParm->hasDefaultArgument())
2084 return TemplateArgumentLoc();
2085
John McCalldadc5752010-08-24 06:29:42 +00002086 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002087 TemplateLoc,
2088 RAngleLoc,
2089 NonTypeParm,
2090 Converted);
2091 if (Arg.isInvalid())
2092 return TemplateArgumentLoc();
2093
2094 Expr *ArgE = Arg.takeAs<Expr>();
2095 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2096 }
2097
2098 TemplateTemplateParmDecl *TempTempParm
2099 = cast<TemplateTemplateParmDecl>(Param);
2100 if (!TempTempParm->hasDefaultArgument())
2101 return TemplateArgumentLoc();
2102
2103 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2104 TemplateLoc,
2105 RAngleLoc,
2106 TempTempParm,
2107 Converted);
2108 if (TName.isNull())
2109 return TemplateArgumentLoc();
2110
2111 return TemplateArgumentLoc(TemplateArgument(TName),
2112 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2113 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2114}
2115
Douglas Gregorda0fb532009-11-11 19:31:23 +00002116/// \brief Check that the given template argument corresponds to the given
2117/// template parameter.
2118bool Sema::CheckTemplateArgument(NamedDecl *Param,
2119 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002120 TemplateDecl *Template,
2121 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002122 SourceLocation RAngleLoc,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002123 llvm::SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002124 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00002125 // Check template type parameters.
2126 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002127 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002128
Douglas Gregoreebed722009-11-11 19:41:09 +00002129 // Check non-type template parameters.
2130 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002131 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00002132 // with the template arguments we've seen thus far. But if the
2133 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00002134 QualType NTTPType = NTTP->getType();
Peter Collingbourne01687632010-12-10 17:08:53 +00002135 if (NTTPType->isDependentType() &&
2136 !isa<TemplateTemplateParmDecl>(Template) &&
2137 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002138 // Do substitution on the type of the non-type template parameter.
2139 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002140 NTTP, Converted.data(), Converted.size(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002141 SourceRange(TemplateLoc, RAngleLoc));
2142
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002143 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2144 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002145 NTTPType = SubstType(NTTPType,
2146 MultiLevelTemplateArgumentList(TemplateArgs),
2147 NTTP->getLocation(),
2148 NTTP->getDeclName());
2149 // If that worked, check the non-type template parameter type
2150 // for validity.
2151 if (!NTTPType.isNull())
2152 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2153 NTTP->getLocation());
2154 if (NTTPType.isNull())
2155 return true;
2156 }
2157
2158 switch (Arg.getArgument().getKind()) {
2159 case TemplateArgument::Null:
2160 assert(false && "Should never see a NULL template argument here");
2161 return true;
2162
2163 case TemplateArgument::Expression: {
2164 Expr *E = Arg.getArgument().getAsExpr();
2165 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002166 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002167 return true;
2168
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002169 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002170 break;
2171 }
2172
2173 case TemplateArgument::Declaration:
2174 case TemplateArgument::Integral:
2175 // We've already checked this template argument, so just copy
2176 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002177 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002178 break;
2179
2180 case TemplateArgument::Template:
2181 // We were given a template template argument. It may not be ill-formed;
2182 // see below.
2183 if (DependentTemplateName *DTN
2184 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2185 // We have a template argument such as \c T::template X, which we
2186 // parsed as a template template argument. However, since we now
2187 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002188 // template name into an expression.
2189
2190 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2191 Arg.getTemplateNameLoc());
2192
John McCalle66edc12009-11-24 19:00:30 +00002193 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2194 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002195 Arg.getTemplateQualifierRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002196 NameInfo);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002197
2198 TemplateArgument Result;
2199 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2200 return true;
2201
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002202 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002203 break;
2204 }
2205
2206 // We have a template argument that actually does refer to a class
2207 // template, template alias, or template template parameter, and
2208 // therefore cannot be a non-type template argument.
2209 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2210 << Arg.getSourceRange();
2211
2212 Diag(Param->getLocation(), diag::note_template_param_here);
2213 return true;
2214
2215 case TemplateArgument::Type: {
2216 // We have a non-type template parameter but the template
2217 // argument is a type.
2218
2219 // C++ [temp.arg]p2:
2220 // In a template-argument, an ambiguity between a type-id and
2221 // an expression is resolved to a type-id, regardless of the
2222 // form of the corresponding template-parameter.
2223 //
2224 // We warn specifically about this case, since it can be rather
2225 // confusing for users.
2226 QualType T = Arg.getArgument().getAsType();
2227 SourceRange SR = Arg.getSourceRange();
2228 if (T->isFunctionType())
2229 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2230 else
2231 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2232 Diag(Param->getLocation(), diag::note_template_param_here);
2233 return true;
2234 }
2235
2236 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002237 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002238 break;
2239 }
2240
2241 return false;
2242 }
2243
2244
2245 // Check template template parameters.
2246 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2247
2248 // Substitute into the template parameter list of the template
2249 // template parameter, since previously-supplied template arguments
2250 // may appear within the template template parameter.
2251 {
2252 // Set up a template instantiation context.
2253 LocalInstantiationScope Scope(*this);
2254 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002255 TempParm, Converted.data(), Converted.size(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002256 SourceRange(TemplateLoc, RAngleLoc));
2257
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002258 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2259 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002260 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2261 SubstDecl(TempParm, CurContext,
2262 MultiLevelTemplateArgumentList(TemplateArgs)));
2263 if (!TempParm)
2264 return true;
2265
2266 // FIXME: TempParam is leaked.
2267 }
2268
2269 switch (Arg.getArgument().getKind()) {
2270 case TemplateArgument::Null:
2271 assert(false && "Should never see a NULL template argument here");
2272 return true;
2273
2274 case TemplateArgument::Template:
2275 if (CheckTemplateArgument(TempParm, Arg))
2276 return true;
2277
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002278 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002279 break;
2280
2281 case TemplateArgument::Expression:
2282 case TemplateArgument::Type:
2283 // We have a template template parameter but the template
2284 // argument does not refer to a template.
2285 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2286 return true;
2287
2288 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002289 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002290 "Declaration argument with template template parameter");
2291 break;
2292 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002293 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002294 "Integral argument with template template parameter");
2295 break;
2296
2297 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002298 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002299 break;
2300 }
2301
2302 return false;
2303}
2304
Douglas Gregord32e0282009-02-09 23:23:08 +00002305/// \brief Check that the given template argument list is well-formed
2306/// for specializing the given template.
2307bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2308 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002309 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002310 bool PartialTemplateArgs,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002311 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002312 TemplateParameterList *Params = Template->getTemplateParameters();
2313 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002314 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002315 bool Invalid = false;
2316
John McCall6b51f282009-11-23 01:53:49 +00002317 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2318
Mike Stump11289f42009-09-09 15:08:12 +00002319 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002320 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002321
Anders Carlsson15201f12009-06-13 02:08:00 +00002322 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002323 (NumArgs < Params->getMinRequiredArguments() &&
2324 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002325 // FIXME: point at either the first arg beyond what we can handle,
2326 // or the '>', depending on whether we have too many or too few
2327 // arguments.
2328 SourceRange Range;
2329 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002330 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002331 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2332 << (NumArgs > NumParams)
2333 << (isa<ClassTemplateDecl>(Template)? 0 :
2334 isa<FunctionTemplateDecl>(Template)? 1 :
2335 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2336 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002337 Diag(Template->getLocation(), diag::note_template_decl_here)
2338 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002339 Invalid = true;
2340 }
Mike Stump11289f42009-09-09 15:08:12 +00002341
2342 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002343 // [...] The type and form of each template-argument specified in
2344 // a template-id shall match the type and form specified for the
2345 // corresponding parameter declared by the template in its
2346 // template-parameter-list.
2347 unsigned ArgIdx = 0;
2348 for (TemplateParameterList::iterator Param = Params->begin(),
2349 ParamEnd = Params->end();
2350 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002351 if (ArgIdx > NumArgs && PartialTemplateArgs)
2352 break;
Mike Stump11289f42009-09-09 15:08:12 +00002353
Douglas Gregoreebed722009-11-11 19:41:09 +00002354 // If we have a template parameter pack, check every remaining template
2355 // argument against that template parameter pack.
2356 if ((*Param)->isTemplateParameterPack()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002357 Diag(TemplateLoc, diag::err_variadic_templates_unsupported);
2358 return true;
Douglas Gregoreebed722009-11-11 19:41:09 +00002359 }
2360
Douglas Gregor84d49a22009-11-11 21:54:23 +00002361 if (ArgIdx < NumArgs) {
2362 // Check the template argument we were given.
2363 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2364 TemplateLoc, RAngleLoc, Converted))
2365 return true;
2366
2367 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002368 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002369
Douglas Gregor84d49a22009-11-11 21:54:23 +00002370 // We have a default template argument that we will use.
2371 TemplateArgumentLoc Arg;
2372
2373 // Retrieve the default template argument from the template
2374 // parameter. For each kind of template parameter, we substitute the
2375 // template arguments provided thus far and any "outer" template arguments
2376 // (when the template parameter was part of a nested template) into
2377 // the default argument.
2378 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2379 if (!TTP->hasDefaultArgument()) {
2380 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2381 break;
2382 }
2383
John McCallbcd03502009-12-07 02:54:59 +00002384 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002385 Template,
2386 TemplateLoc,
2387 RAngleLoc,
2388 TTP,
2389 Converted);
2390 if (!ArgType)
2391 return true;
2392
2393 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2394 ArgType);
2395 } else if (NonTypeTemplateParmDecl *NTTP
2396 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2397 if (!NTTP->hasDefaultArgument()) {
2398 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2399 break;
2400 }
2401
John McCalldadc5752010-08-24 06:29:42 +00002402 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002403 TemplateLoc,
2404 RAngleLoc,
2405 NTTP,
2406 Converted);
2407 if (E.isInvalid())
2408 return true;
2409
2410 Expr *Ex = E.takeAs<Expr>();
2411 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2412 } else {
2413 TemplateTemplateParmDecl *TempParm
2414 = cast<TemplateTemplateParmDecl>(*Param);
2415
2416 if (!TempParm->hasDefaultArgument()) {
2417 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2418 break;
2419 }
2420
2421 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2422 TemplateLoc,
2423 RAngleLoc,
2424 TempParm,
2425 Converted);
2426 if (Name.isNull())
2427 return true;
2428
2429 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2430 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2431 TempParm->getDefaultArgument().getTemplateNameLoc());
2432 }
2433
2434 // Introduce an instantiation record that describes where we are using
2435 // the default template argument.
2436 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002437 Converted.data(), Converted.size(),
Douglas Gregor84d49a22009-11-11 21:54:23 +00002438 SourceRange(TemplateLoc, RAngleLoc));
2439
2440 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002441 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002442 RAngleLoc, Converted))
2443 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002444 }
2445
2446 return Invalid;
2447}
2448
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002449namespace {
2450 class UnnamedLocalNoLinkageFinder
2451 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2452 {
2453 Sema &S;
2454 SourceRange SR;
2455
2456 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2457
2458 public:
2459 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2460
2461 bool Visit(QualType T) {
2462 return inherited::Visit(T.getTypePtr());
2463 }
2464
2465#define TYPE(Class, Parent) \
2466 bool Visit##Class##Type(const Class##Type *);
2467#define ABSTRACT_TYPE(Class, Parent) \
2468 bool Visit##Class##Type(const Class##Type *) { return false; }
2469#define NON_CANONICAL_TYPE(Class, Parent) \
2470 bool Visit##Class##Type(const Class##Type *) { return false; }
2471#include "clang/AST/TypeNodes.def"
2472
2473 bool VisitTagDecl(const TagDecl *Tag);
2474 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2475 };
2476}
2477
2478bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2479 return false;
2480}
2481
2482bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2483 return Visit(T->getElementType());
2484}
2485
2486bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2487 return Visit(T->getPointeeType());
2488}
2489
2490bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2491 const BlockPointerType* T) {
2492 return Visit(T->getPointeeType());
2493}
2494
2495bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2496 const LValueReferenceType* T) {
2497 return Visit(T->getPointeeType());
2498}
2499
2500bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2501 const RValueReferenceType* T) {
2502 return Visit(T->getPointeeType());
2503}
2504
2505bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2506 const MemberPointerType* T) {
2507 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2508}
2509
2510bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2511 const ConstantArrayType* T) {
2512 return Visit(T->getElementType());
2513}
2514
2515bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2516 const IncompleteArrayType* T) {
2517 return Visit(T->getElementType());
2518}
2519
2520bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2521 const VariableArrayType* T) {
2522 return Visit(T->getElementType());
2523}
2524
2525bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2526 const DependentSizedArrayType* T) {
2527 return Visit(T->getElementType());
2528}
2529
2530bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2531 const DependentSizedExtVectorType* T) {
2532 return Visit(T->getElementType());
2533}
2534
2535bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2536 return Visit(T->getElementType());
2537}
2538
2539bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2540 return Visit(T->getElementType());
2541}
2542
2543bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2544 const FunctionProtoType* T) {
2545 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2546 AEnd = T->arg_type_end();
2547 A != AEnd; ++A) {
2548 if (Visit(*A))
2549 return true;
2550 }
2551
2552 return Visit(T->getResultType());
2553}
2554
2555bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2556 const FunctionNoProtoType* T) {
2557 return Visit(T->getResultType());
2558}
2559
2560bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2561 const UnresolvedUsingType*) {
2562 return false;
2563}
2564
2565bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2566 return false;
2567}
2568
2569bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2570 return Visit(T->getUnderlyingType());
2571}
2572
2573bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2574 return false;
2575}
2576
2577bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2578 return VisitTagDecl(T->getDecl());
2579}
2580
2581bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2582 return VisitTagDecl(T->getDecl());
2583}
2584
2585bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2586 const TemplateTypeParmType*) {
2587 return false;
2588}
2589
2590bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2591 const TemplateSpecializationType*) {
2592 return false;
2593}
2594
2595bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2596 const InjectedClassNameType* T) {
2597 return VisitTagDecl(T->getDecl());
2598}
2599
2600bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2601 const DependentNameType* T) {
2602 return VisitNestedNameSpecifier(T->getQualifier());
2603}
2604
2605bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2606 const DependentTemplateSpecializationType* T) {
2607 return VisitNestedNameSpecifier(T->getQualifier());
2608}
2609
2610bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2611 return false;
2612}
2613
2614bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2615 const ObjCInterfaceType *) {
2616 return false;
2617}
2618
2619bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2620 const ObjCObjectPointerType *) {
2621 return false;
2622}
2623
2624bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2625 if (Tag->getDeclContext()->isFunctionOrMethod()) {
2626 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2627 << S.Context.getTypeDeclType(Tag) << SR;
2628 return true;
2629 }
2630
2631 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2632 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2633 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2634 return true;
2635 }
2636
2637 return false;
2638}
2639
2640bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2641 NestedNameSpecifier *NNS) {
2642 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2643 return true;
2644
2645 switch (NNS->getKind()) {
2646 case NestedNameSpecifier::Identifier:
2647 case NestedNameSpecifier::Namespace:
2648 case NestedNameSpecifier::Global:
2649 return false;
2650
2651 case NestedNameSpecifier::TypeSpec:
2652 case NestedNameSpecifier::TypeSpecWithTemplate:
2653 return Visit(QualType(NNS->getAsType(), 0));
2654 }
Fariborz Jahanian26d1e2b2010-10-13 16:19:16 +00002655 return false;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002656}
2657
2658
Douglas Gregord32e0282009-02-09 23:23:08 +00002659/// \brief Check a template argument against its corresponding
2660/// template type parameter.
2661///
2662/// This routine implements the semantics of C++ [temp.arg.type]. It
2663/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002664bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002665 TypeSourceInfo *ArgInfo) {
2666 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002667 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00002668 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00002669
2670 if (Arg->isVariablyModifiedType()) {
2671 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002672 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002673 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002674 }
2675
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002676 // C++03 [temp.arg.type]p2:
2677 // A local type, a type with no linkage, an unnamed type or a type
2678 // compounded from any of these types shall not be used as a
2679 // template-argument for a template type-parameter.
2680 //
2681 // C++0x allows these, and even in C++03 we allow them as an extension with
2682 // a warning.
Douglas Gregor52051cb2010-10-13 18:05:20 +00002683 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002684 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2685 (void)Finder.Visit(Context.getCanonicalType(Arg));
2686 }
2687
Douglas Gregord32e0282009-02-09 23:23:08 +00002688 return false;
2689}
2690
Douglas Gregorccb07762009-02-11 19:52:55 +00002691/// \brief Checks whether the given template argument is the address
2692/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002693static bool
2694CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2695 NonTypeTemplateParmDecl *Param,
2696 QualType ParamType,
2697 Expr *ArgIn,
2698 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002699 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002700 Expr *Arg = ArgIn;
2701 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002702
2703 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002704 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002705 Arg = Cast->getSubExpr();
2706
2707 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002708 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002709 // A template-argument for a non-type, non-template
2710 // template-parameter shall be one of: [...]
2711 //
2712 // -- the address of an object or function with external
2713 // linkage, including function templates and function
2714 // template-ids but excluding non-static class members,
2715 // expressed as & id-expression where the & is optional if
2716 // the name refers to a function or array, or if the
2717 // corresponding template-parameter is a reference; or
2718 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002719
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002720 // In C++98/03 mode, give an extension warning on any extra parentheses.
2721 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2722 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002723 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002724 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002725 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002726 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002727 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002728 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002729 }
2730
2731 Arg = Parens->getSubExpr();
2732 }
2733
Douglas Gregorb242683d2010-04-01 18:32:35 +00002734 bool AddressTaken = false;
2735 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002736 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002737 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002738 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002739 AddressTaken = true;
2740 AddrOpLoc = UnOp->getOperatorLoc();
2741 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002742 } else
2743 DRE = dyn_cast<DeclRefExpr>(Arg);
2744
Douglas Gregorb242683d2010-04-01 18:32:35 +00002745 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002746 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2747 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002748 S.Diag(Param->getLocation(), diag::note_template_param_here);
2749 return true;
2750 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002751
2752 // Stop checking the precise nature of the argument if it is value dependent,
2753 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002754 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00002755 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00002756 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002757 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002758
Douglas Gregorb242683d2010-04-01 18:32:35 +00002759 if (!isa<ValueDecl>(DRE->getDecl())) {
2760 S.Diag(Arg->getSourceRange().getBegin(),
2761 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002762 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002763 S.Diag(Param->getLocation(), diag::note_template_param_here);
2764 return true;
2765 }
2766
2767 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002768
2769 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002770 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2771 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002772 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002773 S.Diag(Param->getLocation(), diag::note_template_param_here);
2774 return true;
2775 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002776
2777 // Cannot refer to non-static member functions
2778 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002779 if (!Method->isStatic()) {
2780 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002781 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002782 S.Diag(Param->getLocation(), diag::note_template_param_here);
2783 return true;
2784 }
Mike Stump11289f42009-09-09 15:08:12 +00002785
Douglas Gregorccb07762009-02-11 19:52:55 +00002786 // Functions must have external linkage.
2787 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002788 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002789 S.Diag(Arg->getSourceRange().getBegin(),
2790 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002791 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002792 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002793 << true;
2794 return true;
2795 }
2796
2797 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002798 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002799
Douglas Gregorb242683d2010-04-01 18:32:35 +00002800 // If the template parameter has pointer type, the function decays.
2801 if (ParamType->isPointerType() && !AddressTaken)
2802 ArgType = S.Context.getPointerType(Func->getType());
2803 else if (AddressTaken && ParamType->isReferenceType()) {
2804 // If we originally had an address-of operator, but the
2805 // parameter has reference type, complain and (if things look
2806 // like they will work) drop the address-of operator.
2807 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2808 ParamType.getNonReferenceType())) {
2809 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2810 << ParamType;
2811 S.Diag(Param->getLocation(), diag::note_template_param_here);
2812 return true;
2813 }
2814
2815 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2816 << ParamType
2817 << FixItHint::CreateRemoval(AddrOpLoc);
2818 S.Diag(Param->getLocation(), diag::note_template_param_here);
2819
2820 ArgType = Func->getType();
2821 }
2822 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002823 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002824 S.Diag(Arg->getSourceRange().getBegin(),
2825 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002826 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002827 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002828 << true;
2829 return true;
2830 }
2831
Douglas Gregorb242683d2010-04-01 18:32:35 +00002832 // A value of reference type is not an object.
2833 if (Var->getType()->isReferenceType()) {
2834 S.Diag(Arg->getSourceRange().getBegin(),
2835 diag::err_template_arg_reference_var)
2836 << Var->getType() << Arg->getSourceRange();
2837 S.Diag(Param->getLocation(), diag::note_template_param_here);
2838 return true;
2839 }
2840
Douglas Gregorccb07762009-02-11 19:52:55 +00002841 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002842 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002843
2844 // If the template parameter has pointer type, we must have taken
2845 // the address of this object.
2846 if (ParamType->isReferenceType()) {
2847 if (AddressTaken) {
2848 // If we originally had an address-of operator, but the
2849 // parameter has reference type, complain and (if things look
2850 // like they will work) drop the address-of operator.
2851 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2852 ParamType.getNonReferenceType())) {
2853 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2854 << ParamType;
2855 S.Diag(Param->getLocation(), diag::note_template_param_here);
2856 return true;
2857 }
2858
2859 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2860 << ParamType
2861 << FixItHint::CreateRemoval(AddrOpLoc);
2862 S.Diag(Param->getLocation(), diag::note_template_param_here);
2863
2864 ArgType = Var->getType();
2865 }
2866 } else if (!AddressTaken && ParamType->isPointerType()) {
2867 if (Var->getType()->isArrayType()) {
2868 // Array-to-pointer decay.
2869 ArgType = S.Context.getArrayDecayedType(Var->getType());
2870 } else {
2871 // If the template parameter has pointer type but the address of
2872 // this object was not taken, complain and (possibly) recover by
2873 // taking the address of the entity.
2874 ArgType = S.Context.getPointerType(Var->getType());
2875 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2876 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2877 << ParamType;
2878 S.Diag(Param->getLocation(), diag::note_template_param_here);
2879 return true;
2880 }
2881
2882 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2883 << ParamType
2884 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2885
2886 S.Diag(Param->getLocation(), diag::note_template_param_here);
2887 }
2888 }
2889 } else {
2890 // We found something else, but we don't know specifically what it is.
2891 S.Diag(Arg->getSourceRange().getBegin(),
2892 diag::err_template_arg_not_object_or_func)
2893 << Arg->getSourceRange();
2894 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2895 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002896 }
Mike Stump11289f42009-09-09 15:08:12 +00002897
Douglas Gregorb242683d2010-04-01 18:32:35 +00002898 if (ParamType->isPointerType() &&
2899 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2900 S.IsQualificationConversion(ArgType, ParamType)) {
2901 // For pointer-to-object types, qualification conversions are
2902 // permitted.
2903 } else {
2904 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2905 if (!ParamRef->getPointeeType()->isFunctionType()) {
2906 // C++ [temp.arg.nontype]p5b3:
2907 // For a non-type template-parameter of type reference to
2908 // object, no conversions apply. The type referred to by the
2909 // reference may be more cv-qualified than the (otherwise
2910 // identical) type of the template- argument. The
2911 // template-parameter is bound directly to the
2912 // template-argument, which shall be an lvalue.
2913
2914 // FIXME: Other qualifiers?
2915 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2916 unsigned ArgQuals = ArgType.getCVRQualifiers();
2917
2918 if ((ParamQuals | ArgQuals) != ParamQuals) {
2919 S.Diag(Arg->getSourceRange().getBegin(),
2920 diag::err_template_arg_ref_bind_ignores_quals)
2921 << ParamType << Arg->getType()
2922 << Arg->getSourceRange();
2923 S.Diag(Param->getLocation(), diag::note_template_param_here);
2924 return true;
2925 }
2926 }
2927 }
2928
2929 // At this point, the template argument refers to an object or
2930 // function with external linkage. We now need to check whether the
2931 // argument and parameter types are compatible.
2932 if (!S.Context.hasSameUnqualifiedType(ArgType,
2933 ParamType.getNonReferenceType())) {
2934 // We can't perform this conversion or binding.
2935 if (ParamType->isReferenceType())
2936 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2937 << ParamType << Arg->getType() << Arg->getSourceRange();
2938 else
2939 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2940 << Arg->getType() << ParamType << Arg->getSourceRange();
2941 S.Diag(Param->getLocation(), diag::note_template_param_here);
2942 return true;
2943 }
2944 }
2945
2946 // Create the template argument.
2947 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002948 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002949 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002950}
2951
2952/// \brief Checks whether the given template argument is a pointer to
2953/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002954bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2955 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002956 bool Invalid = false;
2957
2958 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002959 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002960 Arg = Cast->getSubExpr();
2961
2962 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002963 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002964 // A template-argument for a non-type, non-template
2965 // template-parameter shall be one of: [...]
2966 //
2967 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002968 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002969
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002970 // In C++98/03 mode, give an extension warning on any extra parentheses.
2971 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2972 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002973 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002974 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00002975 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002976 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002977 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002978 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002979 }
2980
2981 Arg = Parens->getSubExpr();
2982 }
2983
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002984 // A pointer-to-member constant written &Class::member.
2985 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002986 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002987 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2988 if (DRE && !DRE->getQualifier())
2989 DRE = 0;
2990 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002991 }
2992 // A constant of pointer-to-member type.
2993 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2994 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2995 if (VD->getType()->isMemberPointerType()) {
2996 if (isa<NonTypeTemplateParmDecl>(VD) ||
2997 (isa<VarDecl>(VD) &&
2998 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2999 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCallc3007a22010-10-26 07:05:15 +00003000 Converted = TemplateArgument(Arg);
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003001 else
3002 Converted = TemplateArgument(VD->getCanonicalDecl());
3003 return Invalid;
3004 }
3005 }
3006 }
3007
3008 DRE = 0;
3009 }
3010
Douglas Gregorccb07762009-02-11 19:52:55 +00003011 if (!DRE)
3012 return Diag(Arg->getSourceRange().getBegin(),
3013 diag::err_template_arg_not_pointer_to_member_form)
3014 << Arg->getSourceRange();
3015
3016 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3017 assert((isa<FieldDecl>(DRE->getDecl()) ||
3018 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3019 "Only non-static member pointers can make it here");
3020
3021 // Okay: this is the address of a non-static member, and therefore
3022 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003023 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCallc3007a22010-10-26 07:05:15 +00003024 Converted = TemplateArgument(Arg);
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003025 else
3026 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00003027 return Invalid;
3028 }
3029
3030 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00003031 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00003032 diag::err_template_arg_not_pointer_to_member_form)
3033 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003034 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00003035 diag::note_template_arg_refers_here);
3036 return true;
3037}
3038
Douglas Gregord32e0282009-02-09 23:23:08 +00003039/// \brief Check a template argument against its corresponding
3040/// non-type template parameter.
3041///
Douglas Gregor463421d2009-03-03 04:44:36 +00003042/// This routine implements the semantics of C++ [temp.arg.nontype].
3043/// It returns true if an error occurred, and false otherwise. \p
3044/// InstantiatedParamType is the type of the non-type template
3045/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003046///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003047/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00003048bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00003049 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003050 TemplateArgument &Converted,
3051 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003052 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3053
Douglas Gregor86560402009-02-10 23:36:10 +00003054 // If either the parameter has a dependent type or the argument is
3055 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00003056 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3057 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003058 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00003059 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003060 }
Douglas Gregor86560402009-02-10 23:36:10 +00003061
3062 // C++ [temp.arg.nontype]p5:
3063 // The following conversions are performed on each expression used
3064 // as a non-type template-argument. If a non-type
3065 // template-argument cannot be converted to the type of the
3066 // corresponding template-parameter then the program is
3067 // ill-formed.
3068 //
3069 // -- for a non-type template-parameter of integral or
3070 // enumeration type, integral promotions (4.5) and integral
3071 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00003072 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003073 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00003074 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00003075 // C++ [temp.arg.nontype]p1:
3076 // A template-argument for a non-type, non-template
3077 // template-parameter shall be one of:
3078 //
3079 // -- an integral constant-expression of integral or enumeration
3080 // type; or
3081 // -- the name of a non-type template-parameter; or
3082 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003083 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00003084 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003085 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00003086 diag::err_template_arg_not_integral_or_enumeral)
3087 << ArgType << Arg->getSourceRange();
3088 Diag(Param->getLocation(), diag::note_template_param_here);
3089 return true;
3090 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003091 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00003092 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3093 << ArgType << Arg->getSourceRange();
3094 return true;
3095 }
3096
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003097 // From here on out, all we care about are the unqualified forms
3098 // of the parameter and argument types.
3099 ParamType = ParamType.getUnqualifiedType();
3100 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00003101
3102 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00003103 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00003104 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003105 } else if (CTAK == CTAK_Deduced) {
3106 // C++ [temp.deduct.type]p17:
3107 // If, in the declaration of a function template with a non-type
3108 // template-parameter, the non-type template- parameter is used
3109 // in an expression in the function parameter-list and, if the
3110 // corresponding template-argument is deduced, the
3111 // template-argument type shall match the type of the
3112 // template-parameter exactly, except that a template-argument
3113 // deduced from an array bound may be of any integral type.
3114 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3115 << ArgType << ParamType;
3116 Diag(Param->getLocation(), diag::note_template_param_here);
John McCall8cb679e2010-11-15 09:13:47 +00003117 return true;
3118 } else if (ParamType->isBooleanType()) {
3119 // This is an integral-to-boolean conversion.
3120 ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean);
Douglas Gregor86560402009-02-10 23:36:10 +00003121 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3122 !ParamType->isEnumeralType()) {
3123 // This is an integral promotion or conversion.
John McCalle3027922010-08-25 11:45:40 +00003124 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00003125 } else {
3126 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003127 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00003128 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003129 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00003130 Diag(Param->getLocation(), diag::note_template_param_here);
3131 return true;
3132 }
3133
Douglas Gregor52aba872009-03-14 00:20:21 +00003134 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00003135 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003136 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00003137
3138 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00003139 llvm::APSInt OldValue = Value;
3140
3141 // Coerce the template argument's value to the value it will have
3142 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00003143 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00003144 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00003145 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00003146 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00003147
3148 // Complain if an unsigned parameter received a negative value.
3149 if (IntegerType->isUnsignedIntegerType()
3150 && (OldValue.isSigned() && OldValue.isNegative())) {
3151 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3152 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3153 << Arg->getSourceRange();
3154 Diag(Param->getLocation(), diag::note_template_param_here);
3155 }
3156
3157 // Complain if we overflowed the template parameter's type.
3158 unsigned RequiredBits;
3159 if (IntegerType->isUnsignedIntegerType())
3160 RequiredBits = OldValue.getActiveBits();
3161 else if (OldValue.isUnsigned())
3162 RequiredBits = OldValue.getActiveBits() + 1;
3163 else
3164 RequiredBits = OldValue.getMinSignedBits();
3165 if (RequiredBits > AllowedBits) {
3166 Diag(Arg->getSourceRange().getBegin(),
3167 diag::warn_template_arg_too_large)
3168 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3169 << Arg->getSourceRange();
3170 Diag(Param->getLocation(), diag::note_template_param_here);
3171 }
Douglas Gregor52aba872009-03-14 00:20:21 +00003172 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003173
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003174 // Add the value of this argument to the list of converted
3175 // arguments. We use the bitwidth and signedness of the template
3176 // parameter.
3177 if (Arg->isValueDependent()) {
3178 // The argument is value-dependent. Create a new
3179 // TemplateArgument with the converted expression.
3180 Converted = TemplateArgument(Arg);
3181 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003182 }
3183
John McCall0ad16662009-10-29 08:12:44 +00003184 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00003185 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003186 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00003187 return false;
3188 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003189
John McCall16df1e52010-03-30 21:47:33 +00003190 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3191
Douglas Gregorb242683d2010-04-01 18:32:35 +00003192 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3193 // from a template argument of type std::nullptr_t to a non-type
3194 // template parameter of type pointer to object, pointer to
3195 // function, or pointer-to-member, respectively.
3196 if (ArgType->isNullPtrType() &&
3197 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3198 Converted = TemplateArgument((NamedDecl *)0);
3199 return false;
3200 }
3201
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003202 // Handle pointer-to-function, reference-to-function, and
3203 // pointer-to-member-function all in (roughly) the same way.
3204 if (// -- For a non-type template-parameter of type pointer to
3205 // function, only the function-to-pointer conversion (4.3) is
3206 // applied. If the template-argument represents a set of
3207 // overloaded functions (or a pointer to such), the matching
3208 // function is selected from the set (13.4).
3209 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003210 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003211 // -- For a non-type template-parameter of type reference to
3212 // function, no conversions apply. If the template-argument
3213 // represents a set of overloaded functions, the matching
3214 // function is selected from the set (13.4).
3215 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003216 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003217 // -- For a non-type template-parameter of type pointer to
3218 // member function, no conversions apply. If the
3219 // template-argument represents a set of overloaded member
3220 // functions, the matching member function is selected from
3221 // the set (13.4).
3222 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003223 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003224 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003225
Douglas Gregor064fdb22010-04-14 23:11:21 +00003226 if (Arg->getType() == Context.OverloadTy) {
3227 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3228 true,
3229 FoundResult)) {
3230 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3231 return true;
3232
3233 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3234 ArgType = Arg->getType();
3235 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00003236 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003237 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00003238
Douglas Gregorb242683d2010-04-01 18:32:35 +00003239 if (!ParamType->isMemberPointerType())
3240 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3241 ParamType,
3242 Arg, Converted);
3243
3244 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCalle3027922010-08-25 11:45:40 +00003245 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00003246 } else if (!Context.hasSameUnqualifiedType(ArgType,
3247 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003248 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003249 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003250 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003251 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003252 Diag(Param->getLocation(), diag::note_template_param_here);
3253 return true;
3254 }
Mike Stump11289f42009-09-09 15:08:12 +00003255
Douglas Gregorb242683d2010-04-01 18:32:35 +00003256 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003257 }
3258
Chris Lattner696197c2009-02-20 21:37:53 +00003259 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003260 // -- for a non-type template-parameter of type pointer to
3261 // object, qualification conversions (4.4) and the
3262 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00003263 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00003264 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003265 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00003266
Douglas Gregorb242683d2010-04-01 18:32:35 +00003267 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3268 ParamType,
3269 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00003270 }
Mike Stump11289f42009-09-09 15:08:12 +00003271
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003272 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003273 // -- For a non-type template-parameter of type reference to
3274 // object, no conversions apply. The type referred to by the
3275 // reference may be more cv-qualified than the (otherwise
3276 // identical) type of the template-argument. The
3277 // template-parameter is bound directly to the
3278 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00003279 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003280 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00003281
Douglas Gregor064fdb22010-04-14 23:11:21 +00003282 if (Arg->getType() == Context.OverloadTy) {
3283 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3284 ParamRefType->getPointeeType(),
3285 true,
3286 FoundResult)) {
3287 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3288 return true;
3289
3290 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3291 ArgType = Arg->getType();
3292 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00003293 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003294 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00003295
Douglas Gregorb242683d2010-04-01 18:32:35 +00003296 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3297 ParamType,
3298 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003299 }
Douglas Gregor0e558532009-02-11 16:16:59 +00003300
3301 // -- For a non-type template-parameter of type pointer to data
3302 // member, qualification conversions (4.4) are applied.
3303 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3304
Douglas Gregor1515f762009-02-11 18:22:40 +00003305 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00003306 // Types match exactly: nothing more to do here.
3307 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCalle3027922010-08-25 11:45:40 +00003308 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00003309 } else {
3310 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003311 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00003312 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003313 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00003314 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003315 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00003316 }
3317
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003318 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00003319}
3320
3321/// \brief Check a template argument against its corresponding
3322/// template template parameter.
3323///
3324/// This routine implements the semantics of C++ [temp.arg.template].
3325/// It returns true if an error occurred, and false otherwise.
3326bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003327 const TemplateArgumentLoc &Arg) {
3328 TemplateName Name = Arg.getArgument().getAsTemplate();
3329 TemplateDecl *Template = Name.getAsTemplateDecl();
3330 if (!Template) {
3331 // Any dependent template name is fine.
3332 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3333 return false;
3334 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003335
3336 // C++ [temp.arg.template]p1:
3337 // A template-argument for a template template-parameter shall be
3338 // the name of a class template, expressed as id-expression. Only
3339 // primary class templates are considered when matching the
3340 // template template argument with the corresponding parameter;
3341 // partial specializations are not considered even if their
3342 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003343 //
3344 // Note that we also allow template template parameters here, which
3345 // will happen when we are dealing with, e.g., class template
3346 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003347 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003348 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003349 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003350 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003351 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003352 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003353 << Template;
3354 }
3355
3356 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3357 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003358 true,
3359 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003360 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003361}
3362
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003363/// \brief Given a non-type template argument that refers to a
3364/// declaration and the type of its corresponding non-type template
3365/// parameter, produce an expression that properly refers to that
3366/// declaration.
John McCalldadc5752010-08-24 06:29:42 +00003367ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003368Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3369 QualType ParamType,
3370 SourceLocation Loc) {
3371 assert(Arg.getKind() == TemplateArgument::Declaration &&
3372 "Only declaration template arguments permitted here");
3373 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3374
3375 if (VD->getDeclContext()->isRecord() &&
3376 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3377 // If the value is a class member, we might have a pointer-to-member.
3378 // Determine whether the non-type template template parameter is of
3379 // pointer-to-member type. If so, we need to build an appropriate
3380 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3381 // would refer to the member itself.
3382 if (ParamType->isMemberPointerType()) {
3383 QualType ClassType
3384 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3385 NestedNameSpecifier *Qualifier
John McCallb268a282010-08-23 23:25:46 +00003386 = NestedNameSpecifier::Create(Context, 0, false,
3387 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003388 CXXScopeSpec SS;
3389 SS.setScopeRep(Qualifier);
John McCallfeb624a2010-11-23 20:48:44 +00003390
3391 // The actual value-ness of this is unimportant, but for
3392 // internal consistency's sake, references to instance methods
3393 // are r-values.
3394 ExprValueKind VK = VK_LValue;
3395 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
3396 VK = VK_RValue;
3397
John McCalldadc5752010-08-24 06:29:42 +00003398 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00003399 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00003400 VK,
John McCall7decc9e2010-11-18 06:31:45 +00003401 Loc,
3402 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003403 if (RefExpr.isInvalid())
3404 return ExprError();
3405
John McCalle3027922010-08-25 11:45:40 +00003406 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003407
3408 // We might need to perform a trailing qualification conversion, since
3409 // the element type on the parameter could be more qualified than the
3410 // element type in the expression we constructed.
3411 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3412 ParamType.getUnqualifiedType())) {
3413 Expr *RefE = RefExpr.takeAs<Expr>();
John McCalle3027922010-08-25 11:45:40 +00003414 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003415 RefExpr = Owned(RefE);
3416 }
3417
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003418 assert(!RefExpr.isInvalid() &&
3419 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003420 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003421 return move(RefExpr);
3422 }
3423 }
3424
3425 QualType T = VD->getType().getNonReferenceType();
3426 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003427 // When the non-type template parameter is a pointer, take the
3428 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00003429 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003430 if (RefExpr.isInvalid())
3431 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003432
3433 if (T->isFunctionType() || T->isArrayType()) {
3434 // Decay functions and arrays.
3435 Expr *RefE = (Expr *)RefExpr.get();
3436 DefaultFunctionArrayConversion(RefE);
3437 if (RefE != RefExpr.get()) {
3438 RefExpr.release();
3439 RefExpr = Owned(RefE);
3440 }
3441
3442 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003443 }
3444
Douglas Gregorb242683d2010-04-01 18:32:35 +00003445 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00003446 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003447 }
3448
John McCall7decc9e2010-11-18 06:31:45 +00003449 ExprValueKind VK = VK_RValue;
3450
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003451 // If the non-type template parameter has reference type, qualify the
3452 // resulting declaration reference with the extra qualifiers on the
3453 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00003454 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
3455 VK = VK_LValue;
3456 T = Context.getQualifiedType(T,
3457 TargetRef->getPointeeType().getQualifiers());
3458 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003459
John McCall7decc9e2010-11-18 06:31:45 +00003460 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003461}
3462
3463/// \brief Construct a new expression that refers to the given
3464/// integral template argument with the given source-location
3465/// information.
3466///
3467/// This routine takes care of the mapping from an integral template
3468/// argument (which may have any integral type) to the appropriate
3469/// literal value.
John McCalldadc5752010-08-24 06:29:42 +00003470ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003471Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3472 SourceLocation Loc) {
3473 assert(Arg.getKind() == TemplateArgument::Integral &&
3474 "Operation is only value for integral template arguments");
3475 QualType T = Arg.getIntegralType();
3476 if (T->isCharType() || T->isWideCharType())
3477 return Owned(new (Context) CharacterLiteral(
3478 Arg.getAsIntegral()->getZExtValue(),
3479 T->isWideCharType(),
3480 T,
3481 Loc));
3482 if (T->isBooleanType())
3483 return Owned(new (Context) CXXBoolLiteralExpr(
3484 Arg.getAsIntegral()->getBoolValue(),
3485 T,
3486 Loc));
3487
Peter Collingbourne03007d72010-12-15 15:06:14 +00003488 QualType BT;
3489 if (const EnumType *ET = T->getAs<EnumType>())
3490 BT = ET->getDecl()->getPromotionType();
3491 else
3492 BT = T;
3493
3494 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
3495 ImpCastExprToType(E, T, CK_IntegralCast);
3496
3497 return Owned(E);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003498}
3499
3500
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003501/// \brief Determine whether the given template parameter lists are
3502/// equivalent.
3503///
Mike Stump11289f42009-09-09 15:08:12 +00003504/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003505/// source code as part of a new template declaration.
3506///
3507/// \param Old The old template parameter list, typically found via
3508/// name lookup of the template declared with this template parameter
3509/// list.
3510///
3511/// \param Complain If true, this routine will produce a diagnostic if
3512/// the template parameter lists are not equivalent.
3513///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003514/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003515///
3516/// \param TemplateArgLoc If this source location is valid, then we
3517/// are actually checking the template parameter list of a template
3518/// argument (New) against the template parameter list of its
3519/// corresponding template template parameter (Old). We produce
3520/// slightly different diagnostics in this scenario.
3521///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003522/// \returns True if the template parameter lists are equal, false
3523/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003524bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003525Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3526 TemplateParameterList *Old,
3527 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003528 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003529 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003530 if (Old->size() != New->size()) {
3531 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003532 unsigned NextDiag = diag::err_template_param_list_different_arity;
3533 if (TemplateArgLoc.isValid()) {
3534 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3535 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003536 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003537 Diag(New->getTemplateLoc(), NextDiag)
3538 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003539 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003540 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003541 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003542 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003543 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3544 }
3545
3546 return false;
3547 }
3548
3549 for (TemplateParameterList::iterator OldParm = Old->begin(),
3550 OldParmEnd = Old->end(), NewParm = New->begin();
3551 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3552 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003553 if (Complain) {
3554 unsigned NextDiag = diag::err_template_param_different_kind;
3555 if (TemplateArgLoc.isValid()) {
3556 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3557 NextDiag = diag::note_template_param_different_kind;
3558 }
3559 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003560 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003561 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003562 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003563 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003564 return false;
3565 }
3566
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003567 if (TemplateTypeParmDecl *OldTTP
3568 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3569 // Template type parameters are equivalent if either both are template
3570 // type parameter packs or neither are (since we know we're at the same
3571 // index).
3572 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3573 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3574 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3575 // allow one to match a template parameter pack in the template
3576 // parameter list of a template template parameter to one or more
3577 // template parameters in the template parameter list of the
3578 // corresponding template template argument.
3579 if (Complain) {
3580 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3581 if (TemplateArgLoc.isValid()) {
3582 Diag(TemplateArgLoc,
3583 diag::err_template_arg_template_params_mismatch);
3584 NextDiag = diag::note_template_parameter_pack_non_pack;
3585 }
3586 Diag(NewTTP->getLocation(), NextDiag)
3587 << 0 << NewTTP->isParameterPack();
3588 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3589 << 0 << OldTTP->isParameterPack();
3590 }
3591 return false;
3592 }
Mike Stump11289f42009-09-09 15:08:12 +00003593 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003594 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3595 // The types of non-type template parameters must agree.
3596 NonTypeTemplateParmDecl *NewNTTP
3597 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003598
3599 // If we are matching a template template argument to a template
3600 // template parameter and one of the non-type template parameter types
3601 // is dependent, then we must wait until template instantiation time
3602 // to actually compare the arguments.
3603 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3604 (OldNTTP->getType()->isDependentType() ||
3605 NewNTTP->getType()->isDependentType()))
3606 continue;
3607
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003608 if (Context.getCanonicalType(OldNTTP->getType()) !=
3609 Context.getCanonicalType(NewNTTP->getType())) {
3610 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003611 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3612 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003613 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003614 diag::err_template_arg_template_params_mismatch);
3615 NextDiag = diag::note_template_nontype_parm_different_type;
3616 }
3617 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003618 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003619 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003620 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003621 diag::note_template_nontype_parm_prev_declaration)
3622 << OldNTTP->getType();
3623 }
3624 return false;
3625 }
3626 } else {
3627 // The template parameter lists of template template
3628 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003629 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003630 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003631 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003632 = cast<TemplateTemplateParmDecl>(*OldParm);
3633 TemplateTemplateParmDecl *NewTTP
3634 = cast<TemplateTemplateParmDecl>(*NewParm);
3635 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3636 OldTTP->getTemplateParameters(),
3637 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003638 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003639 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003640 return false;
3641 }
3642 }
3643
3644 return true;
3645}
3646
3647/// \brief Check whether a template can be declared within this scope.
3648///
3649/// If the template declaration is valid in this scope, returns
3650/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003651bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003652Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003653 // Find the nearest enclosing declaration scope.
3654 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3655 (S->getFlags() & Scope::TemplateParamScope) != 0)
3656 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003657
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003658 // C++ [temp]p2:
3659 // A template-declaration can appear only as a namespace scope or
3660 // class scope declaration.
3661 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003662 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3663 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003664 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003665 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003666
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003667 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003668 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003669
3670 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3671 return false;
3672
Mike Stump11289f42009-09-09 15:08:12 +00003673 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003674 diag::err_template_outside_namespace_or_class_scope)
3675 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003676}
Douglas Gregor67a65642009-02-17 23:15:12 +00003677
Douglas Gregor54888652009-10-07 00:13:32 +00003678/// \brief Determine what kind of template specialization the given declaration
3679/// is.
3680static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3681 if (!D)
3682 return TSK_Undeclared;
3683
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003684 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3685 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003686 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3687 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003688 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3689 return Var->getTemplateSpecializationKind();
3690
Douglas Gregor54888652009-10-07 00:13:32 +00003691 return TSK_Undeclared;
3692}
3693
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003694/// \brief Check whether a specialization is well-formed in the current
3695/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003696///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003697/// This routine determines whether a template specialization can be declared
3698/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003699///
3700/// \param S the semantic analysis object for which this check is being
3701/// performed.
3702///
3703/// \param Specialized the entity being specialized or instantiated, which
3704/// may be a kind of template (class template, function template, etc.) or
3705/// a member of a class template (member function, static data member,
3706/// member class).
3707///
3708/// \param PrevDecl the previous declaration of this entity, if any.
3709///
3710/// \param Loc the location of the explicit specialization or instantiation of
3711/// this entity.
3712///
3713/// \param IsPartialSpecialization whether this is a partial specialization of
3714/// a class template.
3715///
Douglas Gregor54888652009-10-07 00:13:32 +00003716/// \returns true if there was an error that we cannot recover from, false
3717/// otherwise.
3718static bool CheckTemplateSpecializationScope(Sema &S,
3719 NamedDecl *Specialized,
3720 NamedDecl *PrevDecl,
3721 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003722 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003723 // Keep these "kind" numbers in sync with the %select statements in the
3724 // various diagnostics emitted by this routine.
3725 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003726 bool isTemplateSpecialization = false;
3727 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003728 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003729 isTemplateSpecialization = true;
3730 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003731 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003732 isTemplateSpecialization = true;
3733 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003734 EntityKind = 3;
3735 else if (isa<VarDecl>(Specialized))
3736 EntityKind = 4;
3737 else if (isa<RecordDecl>(Specialized))
3738 EntityKind = 5;
3739 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003740 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3741 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003742 return true;
3743 }
3744
Douglas Gregorf47b9112009-02-25 22:02:03 +00003745 // C++ [temp.expl.spec]p2:
3746 // An explicit specialization shall be declared in the namespace
3747 // of which the template is a member, or, for member templates, in
3748 // the namespace of which the enclosing class or enclosing class
3749 // template is a member. An explicit specialization of a member
3750 // function, member class or static data member of a class
3751 // template shall be declared in the namespace of which the class
3752 // template is a member. Such a declaration may also be a
3753 // definition. If the declaration is not a definition, the
3754 // specialization may be defined later in the name- space in which
3755 // the explicit specialization was declared, or in a namespace
3756 // that encloses the one in which the explicit specialization was
3757 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00003758 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00003759 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003760 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003761 return true;
3762 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003763
Douglas Gregor40fb7442009-10-07 17:30:37 +00003764 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3765 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003766 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003767 return true;
3768 }
3769
Douglas Gregore4b05162009-10-07 17:21:34 +00003770 // C++ [temp.class.spec]p6:
3771 // A class template partial specialization may be declared or redeclared
3772 // in any namespace scope in which its definition may be defined (14.5.1
3773 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003774 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003775 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003776 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003777 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003778 if ((!PrevDecl ||
3779 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3780 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregorb1aab432010-09-12 05:08:28 +00003781 // C++ [temp.exp.spec]p2:
3782 // An explicit specialization shall be declared in the namespace of which
3783 // the template is a member, or, for member templates, in the namespace
3784 // of which the enclosing class or enclosing class template is a member.
3785 // An explicit specialization of a member function, member class or
3786 // static data member of a class template shall be declared in the
3787 // namespace of which the class template is a member.
3788 //
3789 // C++0x [temp.expl.spec]p2:
3790 // An explicit specialization shall be declared in a namespace enclosing
3791 // the specialized template.
3792 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3793 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregor8ce63152010-09-12 05:24:55 +00003794 bool IsCPlusPlus0xExtension
3795 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003796 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregor8ce63152010-09-12 05:24:55 +00003797 S.Diag(Loc, IsCPlusPlus0xExtension
3798 ? diag::ext_template_spec_decl_out_of_scope_global
3799 : diag::err_template_spec_decl_out_of_scope_global)
3800 << EntityKind << Specialized;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003801 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregor8ce63152010-09-12 05:24:55 +00003802 S.Diag(Loc, IsCPlusPlus0xExtension
3803 ? diag::ext_template_spec_decl_out_of_scope
3804 : diag::err_template_spec_decl_out_of_scope)
3805 << EntityKind << Specialized
3806 << cast<NamedDecl>(SpecializedContext);
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003807
3808 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3809 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003810 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003811 }
Douglas Gregor54888652009-10-07 00:13:32 +00003812
3813 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003814 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003815 // Note that HandleDeclarator() performs this check for explicit
3816 // specializations of function templates, static data members, and member
3817 // functions, so we skip the check here for those kinds of entities.
3818 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003819 // Should we refactor that check, so that it occurs later?
3820 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003821 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3822 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003823 if (isa<TranslationUnitDecl>(SpecializedContext))
3824 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3825 << EntityKind << Specialized;
3826 else if (isa<NamespaceDecl>(SpecializedContext))
3827 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3828 << EntityKind << Specialized
3829 << cast<NamedDecl>(SpecializedContext);
3830
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003831 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003832 }
Douglas Gregor54888652009-10-07 00:13:32 +00003833
3834 // FIXME: check for specialization-after-instantiation errors and such.
3835
Douglas Gregorf47b9112009-02-25 22:02:03 +00003836 return false;
3837}
Douglas Gregor54888652009-10-07 00:13:32 +00003838
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003839/// \brief Check the non-type template arguments of a class template
3840/// partial specialization according to C++ [temp.class.spec]p9.
3841///
Douglas Gregor09a30232009-06-12 22:08:06 +00003842/// \param TemplateParams the template parameters of the primary class
3843/// template.
3844///
3845/// \param TemplateArg the template arguments of the class template
3846/// partial specialization.
3847///
3848/// \param MirrorsPrimaryTemplate will be set true if the class
3849/// template partial specialization arguments are identical to the
3850/// implicit template arguments of the primary template. This is not
3851/// necessarily an error (C++0x), and it is left to the caller to diagnose
3852/// this condition when it is an error.
3853///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003854/// \returns true if there was an error, false otherwise.
3855bool Sema::CheckClassTemplatePartialSpecializationArgs(
3856 TemplateParameterList *TemplateParams,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003857 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003858 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003859 // FIXME: the interface to this function will have to change to
3860 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003861 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003862
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003863 const TemplateArgument *ArgList = TemplateArgs.data();
Mike Stump11289f42009-09-09 15:08:12 +00003864
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003865 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003866 // Determine whether the template argument list of the partial
3867 // specialization is identical to the implicit argument list of
3868 // the primary template. The caller may need to diagnostic this as
3869 // an error per C++ [temp.class.spec]p9b3.
3870 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003871 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003872 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3873 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003874 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003875 MirrorsPrimaryTemplate = false;
3876 } else if (TemplateTemplateParmDecl *TTP
3877 = dyn_cast<TemplateTemplateParmDecl>(
3878 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003879 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003880 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003881 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003882 if (!ArgDecl ||
3883 ArgDecl->getIndex() != TTP->getIndex() ||
3884 ArgDecl->getDepth() != TTP->getDepth())
3885 MirrorsPrimaryTemplate = false;
3886 }
3887 }
3888
Mike Stump11289f42009-09-09 15:08:12 +00003889 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003890 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003891 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003892 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003893 }
3894
Anders Carlsson40c1d492009-06-13 18:20:51 +00003895 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003896 if (!ArgExpr) {
3897 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003898 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003899 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003900
3901 // C++ [temp.class.spec]p8:
3902 // A non-type argument is non-specialized if it is the name of a
3903 // non-type parameter. All other non-type arguments are
3904 // specialized.
3905 //
3906 // Below, we check the two conditions that only apply to
3907 // specialized non-type arguments, so skip any non-specialized
3908 // arguments.
3909 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003910 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003911 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003912 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003913 (Param->getIndex() != NTTP->getIndex() ||
3914 Param->getDepth() != NTTP->getDepth()))
3915 MirrorsPrimaryTemplate = false;
3916
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003917 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003918 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003919
3920 // C++ [temp.class.spec]p9:
3921 // Within the argument list of a class template partial
3922 // specialization, the following restrictions apply:
3923 // -- A partially specialized non-type argument expression
3924 // shall not involve a template parameter of the partial
3925 // specialization except when the argument expression is a
3926 // simple identifier.
3927 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003928 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003929 diag::err_dependent_non_type_arg_in_partial_spec)
3930 << ArgExpr->getSourceRange();
3931 return true;
3932 }
3933
3934 // -- The type of a template parameter corresponding to a
3935 // specialized non-type argument shall not be dependent on a
3936 // parameter of the specialization.
3937 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003938 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003939 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3940 << Param->getType()
3941 << ArgExpr->getSourceRange();
3942 Diag(Param->getLocation(), diag::note_template_param_here);
3943 return true;
3944 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003945
3946 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003947 }
3948
3949 return false;
3950}
3951
Douglas Gregorc854c662010-02-26 06:03:23 +00003952/// \brief Retrieve the previous declaration of the given declaration.
3953static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3954 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3955 return VD->getPreviousDeclaration();
3956 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3957 return FD->getPreviousDeclaration();
3958 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3959 return TD->getPreviousDeclaration();
3960 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3961 return TD->getPreviousDeclaration();
3962 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3963 return FTD->getPreviousDeclaration();
3964 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3965 return CTD->getPreviousDeclaration();
3966 return 0;
3967}
3968
John McCall48871652010-08-21 09:40:31 +00003969DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003970Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3971 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003972 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003973 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003974 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003975 SourceLocation TemplateNameLoc,
3976 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003977 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003978 SourceLocation RAngleLoc,
3979 AttributeList *Attr,
3980 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003981 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003982
Douglas Gregor67a65642009-02-17 23:15:12 +00003983 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003984 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003985 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003986 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3987
3988 if (!ClassTemplate) {
3989 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3990 << (Name.getAsTemplateDecl() &&
3991 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3992 return true;
3993 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003994
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003995 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003996 bool isPartialSpecialization = false;
3997
Douglas Gregorf47b9112009-02-25 22:02:03 +00003998 // Check the validity of the template headers that introduce this
3999 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00004000 // FIXME: We probably shouldn't complain about these headers for
4001 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00004002 bool Invalid = false;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004003 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00004004 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
4005 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004006 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00004007 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00004008 isExplicitSpecialization,
4009 Invalid);
4010 if (Invalid)
4011 return true;
4012
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004013 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
4014 if (TemplateParams)
4015 --NumMatchedTemplateParamLists;
4016
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004017 if (TemplateParams && TemplateParams->size() > 0) {
4018 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00004019
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004020 // C++ [temp.class.spec]p10:
4021 // The template parameter list of a specialization shall not
4022 // contain default template argument values.
4023 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4024 Decl *Param = TemplateParams->getParam(I);
4025 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4026 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00004027 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004028 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00004029 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004030 }
4031 } else if (NonTypeTemplateParmDecl *NTTP
4032 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4033 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00004034 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004035 diag::err_default_arg_in_partial_spec)
4036 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00004037 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004038 }
4039 } else {
4040 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004041 if (TTP->hasDefaultArgument()) {
4042 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004043 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004044 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00004045 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00004046 }
4047 }
4048 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004049 } else if (TemplateParams) {
4050 if (TUK == TUK_Friend)
4051 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00004052 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004053 SourceRange(TemplateParams->getTemplateLoc(),
4054 TemplateParams->getRAngleLoc()))
4055 << SourceRange(LAngleLoc, RAngleLoc);
4056 else
4057 isExplicitSpecialization = true;
4058 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004059 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00004060 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004061 isExplicitSpecialization = true;
4062 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00004063
Douglas Gregor67a65642009-02-17 23:15:12 +00004064 // Check that the specialization uses the same tag kind as the
4065 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004066 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4067 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004068 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004069 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004070 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004071 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00004072 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004073 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00004074 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004075 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00004076 diag::note_previous_use);
4077 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4078 }
4079
Douglas Gregorc40290e2009-03-09 23:48:35 +00004080 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004081 TemplateArgumentListInfo TemplateArgs;
4082 TemplateArgs.setLAngleLoc(LAngleLoc);
4083 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004084 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00004085
Douglas Gregor67a65642009-02-17 23:15:12 +00004086 // Check that the template argument list is well-formed for this
4087 // template.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004088 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00004089 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4090 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00004091 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00004092
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004093 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregor67a65642009-02-17 23:15:12 +00004094 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004095
Douglas Gregor2373c592009-05-31 09:31:02 +00004096 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00004097 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00004098 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00004099 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00004100 if (CheckClassTemplatePartialSpecializationArgs(
4101 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004102 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00004103 return true;
4104
Douglas Gregor09a30232009-06-12 22:08:06 +00004105 if (MirrorsPrimaryTemplate) {
4106 // C++ [temp.class.spec]p9b3:
4107 //
Mike Stump11289f42009-09-09 15:08:12 +00004108 // -- The argument list of the specialization shall not be identical
4109 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00004110 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00004111 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00004112 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00004113 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00004114 ClassTemplate->getIdentifier(),
4115 TemplateNameLoc,
4116 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004117 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00004118 AS_none);
4119 }
4120
Douglas Gregor2208a292009-09-26 20:57:03 +00004121 // FIXME: Diagnose friend partial specializations
4122
Douglas Gregor92354b62010-02-09 00:37:32 +00004123 if (!Name.isDependent() &&
4124 !TemplateSpecializationType::anyDependentTemplateArguments(
4125 TemplateArgs.getArgumentArray(),
4126 TemplateArgs.size())) {
4127 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4128 << ClassTemplate->getDeclName();
4129 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00004130 }
4131 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004132
Douglas Gregor67a65642009-02-17 23:15:12 +00004133 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00004134 ClassTemplateSpecializationDecl *PrevDecl = 0;
4135
4136 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004137 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00004138 PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004139 = ClassTemplate->findPartialSpecialization(Converted.data(),
4140 Converted.size(),
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004141 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00004142 else
4143 PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004144 = ClassTemplate->findSpecialization(Converted.data(),
4145 Converted.size(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00004146
4147 ClassTemplateSpecializationDecl *Specialization = 0;
4148
Douglas Gregorf47b9112009-02-25 22:02:03 +00004149 // Check whether we can declare a class template specialization in
4150 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00004151 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00004152 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004153 TemplateNameLoc,
4154 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00004155 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004156
Douglas Gregor15301382009-07-30 17:40:51 +00004157 // The canonical type
4158 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00004159 if (PrevDecl &&
4160 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00004161 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00004162 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00004163 // arguments was referenced but not declared, or we're only
4164 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00004165 // declaration node as our own, updating its source location to
4166 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00004167 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00004168 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00004169 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00004170 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00004171 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00004172 // Build the canonical type that describes the converted template
4173 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00004174 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4175 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004176 Converted.data(),
4177 Converted.size());
Douglas Gregor15301382009-07-30 17:40:51 +00004178
Douglas Gregor2373c592009-05-31 09:31:02 +00004179 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00004180 ClassTemplatePartialSpecializationDecl *PrevPartial
4181 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00004182 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004183 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump11289f42009-09-09 15:08:12 +00004184 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00004185 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00004186 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00004187 TemplateNameLoc,
4188 TemplateParams,
4189 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004190 Converted.data(),
4191 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00004192 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00004193 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00004194 PrevPartial,
4195 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00004196 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00004197 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00004198 Partial->setTemplateParameterListsInfo(Context,
4199 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004200 (TemplateParameterList**) TemplateParameterLists.release());
4201 }
Douglas Gregor2373c592009-05-31 09:31:02 +00004202
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004203 if (!PrevPartial)
4204 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00004205 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00004206
Douglas Gregor21610382009-10-29 00:04:11 +00004207 // If we are providing an explicit specialization of a member class
4208 // template specialization, make a note of that.
4209 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4210 PrevPartial->setMemberSpecialization();
4211
Douglas Gregor91772d12009-06-13 00:26:55 +00004212 // Check that all of the template parameters of the class template
4213 // partial specialization are deducible from the template
4214 // arguments. If not, this class template partial specialization
4215 // will never be used.
4216 llvm::SmallVector<bool, 8> DeducibleParams;
4217 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004218 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00004219 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004220 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00004221 unsigned NumNonDeducible = 0;
4222 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4223 if (!DeducibleParams[I])
4224 ++NumNonDeducible;
4225
4226 if (NumNonDeducible) {
4227 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4228 << (NumNonDeducible > 1)
4229 << SourceRange(TemplateNameLoc, RAngleLoc);
4230 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4231 if (!DeducibleParams[I]) {
4232 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4233 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00004234 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00004235 diag::note_partial_spec_unused_parameter)
4236 << Param->getDeclName();
4237 else
Mike Stump11289f42009-09-09 15:08:12 +00004238 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00004239 diag::note_partial_spec_unused_parameter)
Benjamin Kramere8394df2010-08-11 14:47:12 +00004240 << "<anonymous>";
Douglas Gregor91772d12009-06-13 00:26:55 +00004241 }
4242 }
4243 }
Douglas Gregor67a65642009-02-17 23:15:12 +00004244 } else {
4245 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00004246 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00004247 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004248 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00004249 ClassTemplate->getDeclContext(),
4250 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004251 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004252 Converted.data(),
4253 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00004254 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004255 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00004256 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00004257 Specialization->setTemplateParameterListsInfo(Context,
4258 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004259 (TemplateParameterList**) TemplateParameterLists.release());
4260 }
Douglas Gregor67a65642009-02-17 23:15:12 +00004261
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004262 if (!PrevDecl)
4263 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00004264
4265 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00004266 }
4267
Douglas Gregor06db9f52009-10-12 20:18:28 +00004268 // C++ [temp.expl.spec]p6:
4269 // If a template, a member template or the member of a class template is
4270 // explicitly specialized then that specialization shall be declared
4271 // before the first use of that specialization that would cause an implicit
4272 // instantiation to take place, in every translation unit in which such a
4273 // use occurs; no diagnostic is required.
4274 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00004275 bool Okay = false;
4276 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4277 // Is there any previous explicit specialization declaration?
4278 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4279 Okay = true;
4280 break;
4281 }
4282 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00004283
Douglas Gregorc854c662010-02-26 06:03:23 +00004284 if (!Okay) {
4285 SourceRange Range(TemplateNameLoc, RAngleLoc);
4286 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4287 << Context.getTypeDeclType(Specialization) << Range;
4288
4289 Diag(PrevDecl->getPointOfInstantiation(),
4290 diag::note_instantiation_required_here)
4291 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00004292 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00004293 return true;
4294 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00004295 }
4296
Douglas Gregor2208a292009-09-26 20:57:03 +00004297 // If this is not a friend, note that this is an explicit specialization.
4298 if (TUK != TUK_Friend)
4299 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00004300
4301 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00004302 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004303 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00004304 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004305 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00004306 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00004307 Diag(Def->getLocation(), diag::note_previous_definition);
4308 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00004309 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00004310 }
4311 }
4312
Douglas Gregord56a91e2009-02-26 22:19:44 +00004313 // Build the fully-sugared type for this class template
4314 // specialization as the user wrote in the specialization
4315 // itself. This means that we'll pretty-print the type retrieved
4316 // from the specialization's declaration the way that the user
4317 // actually wrote the specialization, rather than formatting the
4318 // name based on the "canonical" representation used to store the
4319 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004320 TypeSourceInfo *WrittenTy
4321 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4322 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004323 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00004324 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregord890b732010-07-06 18:33:12 +00004325 if (TemplateParams)
4326 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnara8075c852010-06-12 07:44:57 +00004327 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00004328 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00004329
Douglas Gregor1e249f82009-02-25 22:18:32 +00004330 // C++ [temp.expl.spec]p9:
4331 // A template explicit specialization is in the scope of the
4332 // namespace in which the template was defined.
4333 //
4334 // We actually implement this paragraph where we set the semantic
4335 // context (in the creation of the ClassTemplateSpecializationDecl),
4336 // but we also maintain the lexical context where the actual
4337 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00004338 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00004339
Douglas Gregor67a65642009-02-17 23:15:12 +00004340 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00004341 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00004342 Specialization->startDefinition();
4343
Douglas Gregor2208a292009-09-26 20:57:03 +00004344 if (TUK == TUK_Friend) {
4345 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4346 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00004347 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00004348 /*FIXME:*/KWLoc);
4349 Friend->setAccess(AS_public);
4350 CurContext->addDecl(Friend);
4351 } else {
4352 // Add the specialization into its lexical context, so that it can
4353 // be seen when iterating through the list of declarations in that
4354 // context. However, specializations are not found by name lookup.
4355 CurContext->addDecl(Specialization);
4356 }
John McCall48871652010-08-21 09:40:31 +00004357 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00004358}
Douglas Gregor333489b2009-03-27 23:10:48 +00004359
John McCall48871652010-08-21 09:40:31 +00004360Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004361 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004362 Declarator &D) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004363 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4364}
4365
John McCall48871652010-08-21 09:40:31 +00004366Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004367 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004368 Declarator &D) {
Douglas Gregor17a7c122009-06-24 00:54:41 +00004369 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004370 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump11289f42009-09-09 15:08:12 +00004371
Douglas Gregor17a7c122009-06-24 00:54:41 +00004372 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004373 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004374 }
Mike Stump11289f42009-09-09 15:08:12 +00004375
Douglas Gregor17a7c122009-06-24 00:54:41 +00004376 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004377
John McCall48871652010-08-21 09:40:31 +00004378 Decl *DP = HandleDeclarator(ParentScope, D,
4379 move(TemplateParameterLists),
4380 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004381 if (FunctionTemplateDecl *FunctionTemplate
John McCall48871652010-08-21 09:40:31 +00004382 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump11289f42009-09-09 15:08:12 +00004383 return ActOnStartOfFunctionDef(FnBodyScope,
John McCall48871652010-08-21 09:40:31 +00004384 FunctionTemplate->getTemplatedDecl());
4385 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4386 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4387 return 0;
Douglas Gregor17a7c122009-06-24 00:54:41 +00004388}
4389
John McCall4f7ced62010-02-11 01:33:53 +00004390/// \brief Strips various properties off an implicit instantiation
4391/// that has just been explicitly specialized.
4392static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004393 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00004394
4395 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4396 FD->setInlineSpecified(false);
4397 }
4398}
4399
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004400/// \brief Diagnose cases where we have an explicit template specialization
4401/// before/after an explicit template instantiation, producing diagnostics
4402/// for those cases where they are required and determining whether the
4403/// new specialization/instantiation will have any effect.
4404///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004405/// \param NewLoc the location of the new explicit specialization or
4406/// instantiation.
4407///
4408/// \param NewTSK the kind of the new explicit specialization or instantiation.
4409///
4410/// \param PrevDecl the previous declaration of the entity.
4411///
4412/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4413///
4414/// \param PrevPointOfInstantiation if valid, indicates where the previus
4415/// declaration was instantiated (either implicitly or explicitly).
4416///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004417/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004418/// specialization or instantiation has no effect and should be ignored.
4419///
4420/// \returns true if there was an error that should prevent the introduction of
4421/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004422bool
4423Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4424 TemplateSpecializationKind NewTSK,
4425 NamedDecl *PrevDecl,
4426 TemplateSpecializationKind PrevTSK,
4427 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004428 bool &HasNoEffect) {
4429 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004430
4431 switch (NewTSK) {
4432 case TSK_Undeclared:
4433 case TSK_ImplicitInstantiation:
4434 assert(false && "Don't check implicit instantiations here");
4435 return false;
4436
4437 case TSK_ExplicitSpecialization:
4438 switch (PrevTSK) {
4439 case TSK_Undeclared:
4440 case TSK_ExplicitSpecialization:
4441 // Okay, we're just specializing something that is either already
4442 // explicitly specialized or has merely been mentioned without any
4443 // instantiation.
4444 return false;
4445
4446 case TSK_ImplicitInstantiation:
4447 if (PrevPointOfInstantiation.isInvalid()) {
4448 // The declaration itself has not actually been instantiated, so it is
4449 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004450 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004451 return false;
4452 }
4453 // Fall through
4454
4455 case TSK_ExplicitInstantiationDeclaration:
4456 case TSK_ExplicitInstantiationDefinition:
4457 assert((PrevTSK == TSK_ImplicitInstantiation ||
4458 PrevPointOfInstantiation.isValid()) &&
4459 "Explicit instantiation without point of instantiation?");
4460
4461 // C++ [temp.expl.spec]p6:
4462 // If a template, a member template or the member of a class template
4463 // is explicitly specialized then that specialization shall be declared
4464 // before the first use of that specialization that would cause an
4465 // implicit instantiation to take place, in every translation unit in
4466 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004467 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4468 // Is there any previous explicit specialization declaration?
4469 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4470 return false;
4471 }
4472
Douglas Gregor1d957a32009-10-27 18:42:08 +00004473 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004474 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004475 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004476 << (PrevTSK != TSK_ImplicitInstantiation);
4477
4478 return true;
4479 }
4480 break;
4481
4482 case TSK_ExplicitInstantiationDeclaration:
4483 switch (PrevTSK) {
4484 case TSK_ExplicitInstantiationDeclaration:
4485 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004486 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004487 return false;
4488
4489 case TSK_Undeclared:
4490 case TSK_ImplicitInstantiation:
4491 // We're explicitly instantiating something that may have already been
4492 // implicitly instantiated; that's fine.
4493 return false;
4494
4495 case TSK_ExplicitSpecialization:
4496 // C++0x [temp.explicit]p4:
4497 // For a given set of template parameters, if an explicit instantiation
4498 // of a template appears after a declaration of an explicit
4499 // specialization for that template, the explicit instantiation has no
4500 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004501 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004502 return false;
4503
4504 case TSK_ExplicitInstantiationDefinition:
4505 // C++0x [temp.explicit]p10:
4506 // If an entity is the subject of both an explicit instantiation
4507 // declaration and an explicit instantiation definition in the same
4508 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004509 Diag(NewLoc,
4510 diag::err_explicit_instantiation_declaration_after_definition);
4511 Diag(PrevPointOfInstantiation,
4512 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004513 assert(PrevPointOfInstantiation.isValid() &&
4514 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004515 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004516 return false;
4517 }
4518 break;
4519
4520 case TSK_ExplicitInstantiationDefinition:
4521 switch (PrevTSK) {
4522 case TSK_Undeclared:
4523 case TSK_ImplicitInstantiation:
4524 // We're explicitly instantiating something that may have already been
4525 // implicitly instantiated; that's fine.
4526 return false;
4527
4528 case TSK_ExplicitSpecialization:
4529 // C++ DR 259, C++0x [temp.explicit]p4:
4530 // For a given set of template parameters, if an explicit
4531 // instantiation of a template appears after a declaration of
4532 // an explicit specialization for that template, the explicit
4533 // instantiation has no effect.
4534 //
4535 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004536 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004537 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004538 if (!getLangOptions().CPlusPlus0x) {
4539 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004540 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004541 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004542 diag::note_previous_template_specialization);
4543 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004544 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004545 return false;
4546
4547 case TSK_ExplicitInstantiationDeclaration:
4548 // We're explicity instantiating a definition for something for which we
4549 // were previously asked to suppress instantiations. That's fine.
4550 return false;
4551
4552 case TSK_ExplicitInstantiationDefinition:
4553 // C++0x [temp.spec]p5:
4554 // For a given template and a given set of template-arguments,
4555 // - an explicit instantiation definition shall appear at most once
4556 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004557 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004558 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004559 Diag(PrevPointOfInstantiation,
4560 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004561 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004562 return false;
4563 }
4564 break;
4565 }
4566
4567 assert(false && "Missing specialization/instantiation case?");
4568
4569 return false;
4570}
4571
John McCallb9c78482010-04-08 09:05:18 +00004572/// \brief Perform semantic analysis for the given dependent function
4573/// template specialization. The only possible way to get a dependent
4574/// function template specialization is with a friend declaration,
4575/// like so:
4576///
4577/// template <class T> void foo(T);
4578/// template <class T> class A {
4579/// friend void foo<>(T);
4580/// };
4581///
4582/// There really isn't any useful analysis we can do here, so we
4583/// just store the information.
4584bool
4585Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4586 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4587 LookupResult &Previous) {
4588 // Remove anything from Previous that isn't a function template in
4589 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00004590 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00004591 LookupResult::Filter F = Previous.makeFilter();
4592 while (F.hasNext()) {
4593 NamedDecl *D = F.next()->getUnderlyingDecl();
4594 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00004595 !FDLookupContext->InEnclosingNamespaceSetOf(
4596 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00004597 F.erase();
4598 }
4599 F.done();
4600
4601 // Should this be diagnosed here?
4602 if (Previous.empty()) return true;
4603
4604 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4605 ExplicitTemplateArgs);
4606 return false;
4607}
4608
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004609/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004610/// specialization.
4611///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004612/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004613/// explicit function template specialization. On successful completion,
4614/// the function declaration \p FD will become a function template
4615/// specialization.
4616///
4617/// \param FD the function declaration, which will be updated to become a
4618/// function template specialization.
4619///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004620/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4621/// if any. Note that this may be valid info even when 0 arguments are
4622/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4623/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004624///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004625/// \param PrevDecl the set of declarations that may be specialized by
4626/// this function specialization.
4627bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004628Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004629 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004630 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004631 // The set of function template specializations that could match this
4632 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004633 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004634
Sebastian Redl50c68252010-08-31 00:36:30 +00004635 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00004636 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4637 I != E; ++I) {
4638 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4639 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004640 // Only consider templates found within the same semantic lookup scope as
4641 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00004642 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4643 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004644 continue;
4645
4646 // C++ [temp.expl.spec]p11:
4647 // A trailing template-argument can be left unspecified in the
4648 // template-id naming an explicit function template specialization
4649 // provided it can be deduced from the function argument type.
4650 // Perform template argument deduction to determine whether we may be
4651 // specializing this template.
4652 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004653 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004654 FunctionDecl *Specialization = 0;
4655 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004656 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004657 FD->getType(),
4658 Specialization,
4659 Info)) {
4660 // FIXME: Template argument deduction failed; record why it failed, so
4661 // that we can provide nifty diagnostics.
4662 (void)TDK;
4663 continue;
4664 }
4665
4666 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004667 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004668 }
4669 }
4670
Douglas Gregor5de279c2009-09-26 03:41:46 +00004671 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004672 UnresolvedSetIterator Result
4673 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4674 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004675 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004676 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004677 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004678 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004679 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004680 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004681 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004682
4683 // Ignore access information; it doesn't figure into redeclaration checking.
4684 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004685 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004686
4687 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004688 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004689
4690 // If this is a friend declaration, then we're not really declaring
4691 // an explicit specialization.
4692 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004693
Douglas Gregor54888652009-10-07 00:13:32 +00004694 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004695 if (!isFriend &&
4696 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004697 Specialization->getPrimaryTemplate(),
4698 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004699 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004700 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004701
4702 // C++ [temp.expl.spec]p6:
4703 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004704 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004705 // before the first use of that specialization that would cause an implicit
4706 // instantiation to take place, in every translation unit in which such a
4707 // use occurs; no diagnostic is required.
4708 FunctionTemplateSpecializationInfo *SpecInfo
4709 = Specialization->getTemplateSpecializationInfo();
4710 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004711
Abramo Bagnara8075c852010-06-12 07:44:57 +00004712 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004713 if (!isFriend &&
4714 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004715 TSK_ExplicitSpecialization,
4716 Specialization,
4717 SpecInfo->getTemplateSpecializationKind(),
4718 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004719 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004720 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004721
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004722 // Mark the prior declaration as an explicit specialization, so that later
4723 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004724 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00004725 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004726 MarkUnusedFileScopedDecl(Specialization);
4727 }
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004728
4729 // Turn the given function declaration into a function template
4730 // specialization, with the template arguments from the previous
4731 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004732 // Take copies of (semantic and syntactic) template argument lists.
4733 const TemplateArgumentList* TemplArgs = new (Context)
4734 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4735 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4736 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004737 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004738 TemplArgs, /*InsertPos=*/0,
4739 SpecInfo->getTemplateSpecializationKind(),
4740 TemplArgsAsWritten);
4741
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004742 // The "previous declaration" for this function template specialization is
4743 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004744 Previous.clear();
4745 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004746 return false;
4747}
4748
Douglas Gregor86d142a2009-10-08 07:24:58 +00004749/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004750/// specialization.
4751///
4752/// This routine performs all of the semantic analysis required for an
4753/// explicit member function specialization. On successful completion,
4754/// the function declaration \p FD will become a member function
4755/// specialization.
4756///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004757/// \param Member the member declaration, which will be updated to become a
4758/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004759///
John McCall1f82f242009-11-18 22:49:29 +00004760/// \param Previous the set of declarations, one of which may be specialized
4761/// by this function specialization; the set will be modified to contain the
4762/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004763bool
John McCall1f82f242009-11-18 22:49:29 +00004764Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004765 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004766
Douglas Gregor86d142a2009-10-08 07:24:58 +00004767 // Try to find the member we are instantiating.
4768 NamedDecl *Instantiation = 0;
4769 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004770 MemberSpecializationInfo *MSInfo = 0;
4771
John McCall1f82f242009-11-18 22:49:29 +00004772 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004773 // Nowhere to look anyway.
4774 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004775 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4776 I != E; ++I) {
4777 NamedDecl *D = (*I)->getUnderlyingDecl();
4778 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004779 if (Context.hasSameType(Function->getType(), Method->getType())) {
4780 Instantiation = Method;
4781 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004782 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004783 break;
4784 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004785 }
4786 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004787 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004788 VarDecl *PrevVar;
4789 if (Previous.isSingleResult() &&
4790 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004791 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004792 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004793 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004794 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004795 }
4796 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004797 CXXRecordDecl *PrevRecord;
4798 if (Previous.isSingleResult() &&
4799 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4800 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004801 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004802 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004803 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004804 }
4805
4806 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004807 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004808 // specializations are always out-of-line, the caller will complain about
4809 // this mismatch later.
4810 return false;
4811 }
John McCalle820e5e2010-04-13 20:37:33 +00004812
4813 // If this is a friend, just bail out here before we start turning
4814 // things into explicit specializations.
4815 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4816 // Preserve instantiation information.
4817 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4818 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4819 cast<CXXMethodDecl>(InstantiatedFrom),
4820 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4821 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4822 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4823 cast<CXXRecordDecl>(InstantiatedFrom),
4824 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4825 }
4826
4827 Previous.clear();
4828 Previous.addDecl(Instantiation);
4829 return false;
4830 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004831
Douglas Gregor86d142a2009-10-08 07:24:58 +00004832 // Make sure that this is a specialization of a member.
4833 if (!InstantiatedFrom) {
4834 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4835 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004836 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4837 return true;
4838 }
4839
Douglas Gregor06db9f52009-10-12 20:18:28 +00004840 // C++ [temp.expl.spec]p6:
4841 // If a template, a member template or the member of a class template is
4842 // explicitly specialized then that spe- cialization shall be declared
4843 // before the first use of that specialization that would cause an implicit
4844 // instantiation to take place, in every translation unit in which such a
4845 // use occurs; no diagnostic is required.
4846 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004847
Abramo Bagnara8075c852010-06-12 07:44:57 +00004848 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004849 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4850 TSK_ExplicitSpecialization,
4851 Instantiation,
4852 MSInfo->getTemplateSpecializationKind(),
4853 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004854 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004855 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004856
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004857 // Check the scope of this explicit specialization.
4858 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004859 InstantiatedFrom,
4860 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004861 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004862 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004863
Douglas Gregor86d142a2009-10-08 07:24:58 +00004864 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004865 // the original declaration to note that it is an explicit specialization
4866 // (if it was previously an implicit instantiation). This latter step
4867 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004868 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004869 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4870 if (InstantiationFunction->getTemplateSpecializationKind() ==
4871 TSK_ImplicitInstantiation) {
4872 InstantiationFunction->setTemplateSpecializationKind(
4873 TSK_ExplicitSpecialization);
4874 InstantiationFunction->setLocation(Member->getLocation());
4875 }
4876
Douglas Gregor86d142a2009-10-08 07:24:58 +00004877 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4878 cast<CXXMethodDecl>(InstantiatedFrom),
4879 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004880 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004881 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004882 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4883 if (InstantiationVar->getTemplateSpecializationKind() ==
4884 TSK_ImplicitInstantiation) {
4885 InstantiationVar->setTemplateSpecializationKind(
4886 TSK_ExplicitSpecialization);
4887 InstantiationVar->setLocation(Member->getLocation());
4888 }
4889
Douglas Gregor86d142a2009-10-08 07:24:58 +00004890 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4891 cast<VarDecl>(InstantiatedFrom),
4892 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004893 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004894 } else {
4895 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004896 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4897 if (InstantiationClass->getTemplateSpecializationKind() ==
4898 TSK_ImplicitInstantiation) {
4899 InstantiationClass->setTemplateSpecializationKind(
4900 TSK_ExplicitSpecialization);
4901 InstantiationClass->setLocation(Member->getLocation());
4902 }
4903
Douglas Gregor86d142a2009-10-08 07:24:58 +00004904 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004905 cast<CXXRecordDecl>(InstantiatedFrom),
4906 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004907 }
4908
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004909 // Save the caller the trouble of having to figure out which declaration
4910 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004911 Previous.clear();
4912 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004913 return false;
4914}
4915
Douglas Gregore47f5a72009-10-14 23:41:34 +00004916/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004917///
4918/// \returns true if a serious error occurs, false otherwise.
4919static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004920 SourceLocation InstLoc,
4921 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00004922 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
4923 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregore47f5a72009-10-14 23:41:34 +00004924
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004925 if (CurContext->isRecord()) {
4926 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4927 << D;
4928 return true;
4929 }
4930
Douglas Gregore47f5a72009-10-14 23:41:34 +00004931 // C++0x [temp.explicit]p2:
4932 // An explicit instantiation shall appear in an enclosing namespace of its
4933 // template.
4934 //
4935 // This is DR275, which we do not retroactively apply to C++98/03.
4936 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004937 !CurContext->Encloses(OrigContext)) {
4938 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004939 S.Diag(InstLoc,
4940 S.getLangOptions().CPlusPlus0x?
4941 diag::err_explicit_instantiation_out_of_scope
4942 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004943 << D << NS;
4944 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004945 S.Diag(InstLoc,
4946 S.getLangOptions().CPlusPlus0x?
4947 diag::err_explicit_instantiation_must_be_global
4948 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004949 << D;
4950 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004951 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004952 }
Sebastian Redl50c68252010-08-31 00:36:30 +00004953
Douglas Gregore47f5a72009-10-14 23:41:34 +00004954 // C++0x [temp.explicit]p2:
4955 // If the name declared in the explicit instantiation is an unqualified
4956 // name, the explicit instantiation shall appear in the namespace where
4957 // its template is declared or, if that namespace is inline (7.3.1), any
4958 // namespace from its enclosing namespace set.
4959 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004960 return false;
Sebastian Redl50c68252010-08-31 00:36:30 +00004961
4962 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004963 return false;
Sebastian Redl50c68252010-08-31 00:36:30 +00004964
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004965 S.Diag(InstLoc,
4966 S.getLangOptions().CPlusPlus0x?
4967 diag::err_explicit_instantiation_unqualified_wrong_namespace
4968 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl50c68252010-08-31 00:36:30 +00004969 << D << OrigContext;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004970 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004971 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004972}
4973
4974/// \brief Determine whether the given scope specifier has a template-id in it.
4975static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4976 if (!SS.isSet())
4977 return false;
4978
4979 // C++0x [temp.explicit]p2:
4980 // If the explicit instantiation is for a member function, a member class
4981 // or a static data member of a class template specialization, the name of
4982 // the class template specialization in the qualified-id for the member
4983 // name shall be a simple-template-id.
4984 //
4985 // C++98 has the same restriction, just worded differently.
4986 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4987 NNS; NNS = NNS->getPrefix())
4988 if (Type *T = NNS->getAsType())
4989 if (isa<TemplateSpecializationType>(T))
4990 return true;
4991
4992 return false;
4993}
4994
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004995// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00004996DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004997Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004998 SourceLocation ExternLoc,
4999 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005000 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00005001 SourceLocation KWLoc,
5002 const CXXScopeSpec &SS,
5003 TemplateTy TemplateD,
5004 SourceLocation TemplateNameLoc,
5005 SourceLocation LAngleLoc,
5006 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00005007 SourceLocation RAngleLoc,
5008 AttributeList *Attr) {
5009 // Find the class template we're specializing
5010 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00005011 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00005012 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
5013
5014 // Check that the specialization uses the same tag kind as the
5015 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00005016 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5017 assert(Kind != TTK_Enum &&
5018 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00005019 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00005020 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00005021 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00005022 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00005023 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00005024 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00005025 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00005026 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00005027 diag::note_previous_use);
5028 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5029 }
5030
Douglas Gregore47f5a72009-10-14 23:41:34 +00005031 // C++0x [temp.explicit]p2:
5032 // There are two forms of explicit instantiation: an explicit instantiation
5033 // definition and an explicit instantiation declaration. An explicit
5034 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00005035 TemplateSpecializationKind TSK
5036 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5037 : TSK_ExplicitInstantiationDeclaration;
5038
Douglas Gregora1f49972009-05-13 00:25:59 +00005039 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00005040 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00005041 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00005042
5043 // Check that the template argument list is well-formed for this
5044 // template.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005045 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00005046 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5047 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00005048 return true;
5049
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005050 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregora1f49972009-05-13 00:25:59 +00005051 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00005052
Douglas Gregora1f49972009-05-13 00:25:59 +00005053 // Find the class template specialization declaration that
5054 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00005055 void *InsertPos = 0;
5056 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005057 = ClassTemplate->findSpecialization(Converted.data(),
5058 Converted.size(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00005059
Abramo Bagnara8075c852010-06-12 07:44:57 +00005060 TemplateSpecializationKind PrevDecl_TSK
5061 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5062
Douglas Gregor54888652009-10-07 00:13:32 +00005063 // C++0x [temp.explicit]p2:
5064 // [...] An explicit instantiation shall appear in an enclosing
5065 // namespace of its template. [...]
5066 //
5067 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00005068 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5069 SS.isSet()))
5070 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00005071
Douglas Gregora1f49972009-05-13 00:25:59 +00005072 ClassTemplateSpecializationDecl *Specialization = 0;
5073
Douglas Gregor0681a352009-11-25 06:01:46 +00005074 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005075 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00005076 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00005077 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00005078 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00005079 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005080 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00005081 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00005082
Abramo Bagnara8075c852010-06-12 07:44:57 +00005083 // Even though HasNoEffect == true means that this explicit instantiation
5084 // has no effect on semantics, we go on to put its syntax in the AST.
5085
5086 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5087 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00005088 // Since the only prior class template specialization with these
5089 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00005090 // declaration node as our own, updating the source location
5091 // for the template name to reflect our new declaration.
5092 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00005093 Specialization = PrevDecl;
5094 Specialization->setLocation(TemplateNameLoc);
5095 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00005096 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00005097 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00005098 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00005099
Douglas Gregor4aa04b12009-09-11 21:19:12 +00005100 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00005101 // Create a new class template specialization declaration node for
5102 // this explicit specialization.
5103 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00005104 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00005105 ClassTemplate->getDeclContext(),
5106 TemplateNameLoc,
5107 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005108 Converted.data(),
5109 Converted.size(),
5110 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00005111 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00005112
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00005113 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005114 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00005115 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00005116 }
Douglas Gregora1f49972009-05-13 00:25:59 +00005117 }
5118
5119 // Build the fully-sugared type for this explicit instantiation as
5120 // the user wrote in the explicit instantiation itself. This means
5121 // that we'll pretty-print the type retrieved from the
5122 // specialization's declaration the way that the user actually wrote
5123 // the explicit instantiation, rather than formatting the name based
5124 // on the "canonical" representation used to store the template
5125 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00005126 TypeSourceInfo *WrittenTy
5127 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5128 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00005129 Context.getTypeDeclType(Specialization));
5130 Specialization->setTypeAsWritten(WrittenTy);
5131 TemplateArgsIn.release();
5132
Abramo Bagnara8075c852010-06-12 07:44:57 +00005133 // Set source locations for keywords.
5134 Specialization->setExternLoc(ExternLoc);
5135 Specialization->setTemplateKeywordLoc(TemplateLoc);
5136
5137 // Add the explicit instantiation into its lexical context. However,
5138 // since explicit instantiations are never found by name lookup, we
5139 // just put it into the declaration context directly.
5140 Specialization->setLexicalDeclContext(CurContext);
5141 CurContext->addDecl(Specialization);
5142
5143 // Syntax is now OK, so return if it has no other effect on semantics.
5144 if (HasNoEffect) {
5145 // Set the template specialization kind.
5146 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00005147 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00005148 }
Douglas Gregora1f49972009-05-13 00:25:59 +00005149
5150 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00005151 // A definition of a class template or class member template
5152 // shall be in scope at the point of the explicit instantiation of
5153 // the class template or class member template.
5154 //
5155 // This check comes when we actually try to perform the
5156 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00005157 ClassTemplateSpecializationDecl *Def
5158 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005159 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00005160 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00005161 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00005162 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00005163 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00005164 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5165 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00005166
Douglas Gregor1d957a32009-10-27 18:42:08 +00005167 // Instantiate the members of this class template specialization.
5168 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005169 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00005170 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00005171 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5172
5173 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5174 // TSK_ExplicitInstantiationDefinition
5175 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5176 TSK == TSK_ExplicitInstantiationDefinition)
5177 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00005178
Douglas Gregor12e49d32009-10-15 22:53:21 +00005179 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00005180 }
Douglas Gregora1f49972009-05-13 00:25:59 +00005181
Abramo Bagnara8075c852010-06-12 07:44:57 +00005182 // Set the template specialization kind.
5183 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00005184 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00005185}
5186
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005187// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00005188DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00005189Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00005190 SourceLocation ExternLoc,
5191 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005192 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005193 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005194 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005195 IdentifierInfo *Name,
5196 SourceLocation NameLoc,
5197 AttributeList *Attr) {
5198
Douglas Gregord6ab8742009-05-28 23:31:59 +00005199 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00005200 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00005201 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00005202 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5203 MultiTemplateParamsArg(*this, 0, 0),
Abramo Bagnara0e05e242010-12-03 18:54:17 +00005204 Owned, IsDependent, false, false,
Douglas Gregor0bf31402010-10-08 23:50:27 +00005205 TypeResult());
John McCall7f41d982009-09-11 04:59:25 +00005206 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5207
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005208 if (!TagD)
5209 return true;
5210
John McCall48871652010-08-21 09:40:31 +00005211 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005212 if (Tag->isEnum()) {
5213 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5214 << Context.getTypeDeclType(Tag);
5215 return true;
5216 }
5217
Douglas Gregorb8006faf2009-05-27 17:30:49 +00005218 if (Tag->isInvalidDecl())
5219 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005220
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005221 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5222 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5223 if (!Pattern) {
5224 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5225 << Context.getTypeDeclType(Record);
5226 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5227 return true;
5228 }
5229
Douglas Gregore47f5a72009-10-14 23:41:34 +00005230 // C++0x [temp.explicit]p2:
5231 // If the explicit instantiation is for a class or member class, the
5232 // elaborated-type-specifier in the declaration shall include a
5233 // simple-template-id.
5234 //
5235 // C++98 has the same restriction, just worded differently.
5236 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00005237 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005238 << Record << SS.getRange();
5239
5240 // C++0x [temp.explicit]p2:
5241 // There are two forms of explicit instantiation: an explicit instantiation
5242 // definition and an explicit instantiation declaration. An explicit
5243 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00005244 TemplateSpecializationKind TSK
5245 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5246 : TSK_ExplicitInstantiationDeclaration;
5247
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005248 // C++0x [temp.explicit]p2:
5249 // [...] An explicit instantiation shall appear in an enclosing
5250 // namespace of its template. [...]
5251 //
5252 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00005253 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005254
5255 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00005256 CXXRecordDecl *PrevDecl
5257 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005258 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00005259 PrevDecl = Record;
5260 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005261 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00005262 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005263 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00005264 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005265 PrevDecl,
5266 MSInfo->getTemplateSpecializationKind(),
5267 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005268 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005269 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005270 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005271 return TagD;
5272 }
5273
Douglas Gregor12e49d32009-10-15 22:53:21 +00005274 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005275 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00005276 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00005277 // C++ [temp.explicit]p3:
5278 // A definition of a member class of a class template shall be in scope
5279 // at the point of an explicit instantiation of the member class.
5280 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005281 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00005282 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00005283 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5284 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00005285 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5286 << Pattern;
5287 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005288 } else {
5289 if (InstantiateClass(NameLoc, Record, Def,
5290 getTemplateInstantiationArgs(Record),
5291 TSK))
5292 return true;
5293
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005294 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00005295 if (!RecordDef)
5296 return true;
5297 }
5298 }
5299
5300 // Instantiate all of the members of the class.
5301 InstantiateClassMembers(NameLoc, RecordDef,
5302 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005303
Douglas Gregor88d292c2010-05-13 16:44:06 +00005304 if (TSK == TSK_ExplicitInstantiationDefinition)
5305 MarkVTableUsed(NameLoc, RecordDef, true);
5306
Mike Stump87c57ac2009-05-16 07:39:55 +00005307 // FIXME: We don't have any representation for explicit instantiations of
5308 // member classes. Such a representation is not needed for compilation, but it
5309 // should be available for clients that want to see all of the declarations in
5310 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005311 return TagD;
5312}
5313
John McCallfaf5fb42010-08-26 23:41:50 +00005314DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5315 SourceLocation ExternLoc,
5316 SourceLocation TemplateLoc,
5317 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005318 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005319 // TODO: check if/when DNInfo should replace Name.
5320 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5321 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00005322 if (!Name) {
5323 if (!D.isInvalidType())
5324 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5325 diag::err_explicit_instantiation_requires_name)
5326 << D.getDeclSpec().getSourceRange()
5327 << D.getSourceRange();
5328
5329 return true;
5330 }
5331
5332 // The scope passed in may not be a decl scope. Zip up the scope tree until
5333 // we find one that is.
5334 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5335 (S->getFlags() & Scope::TemplateParamScope) != 0)
5336 S = S->getParent();
5337
5338 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00005339 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5340 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00005341 if (R.isNull())
5342 return true;
5343
5344 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5345 // Cannot explicitly instantiate a typedef.
5346 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5347 << Name;
5348 return true;
5349 }
5350
Douglas Gregor3c74d412009-10-14 20:14:33 +00005351 // C++0x [temp.explicit]p1:
5352 // [...] An explicit instantiation of a function template shall not use the
5353 // inline or constexpr specifiers.
5354 // Presumably, this also applies to member functions of class templates as
5355 // well.
5356 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5357 Diag(D.getDeclSpec().getInlineSpecLoc(),
5358 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00005359 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00005360
5361 // FIXME: check for constexpr specifier.
5362
Douglas Gregore47f5a72009-10-14 23:41:34 +00005363 // C++0x [temp.explicit]p2:
5364 // There are two forms of explicit instantiation: an explicit instantiation
5365 // definition and an explicit instantiation declaration. An explicit
5366 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005367 TemplateSpecializationKind TSK
5368 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5369 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005370
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005371 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005372 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005373
5374 if (!R->isFunctionType()) {
5375 // C++ [temp.explicit]p1:
5376 // A [...] static data member of a class template can be explicitly
5377 // instantiated from the member definition associated with its class
5378 // template.
John McCall27b18f82009-11-17 02:14:36 +00005379 if (Previous.isAmbiguous())
5380 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005381
John McCall67c00872009-12-02 08:25:40 +00005382 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005383 if (!Prev || !Prev->isStaticDataMember()) {
5384 // We expect to see a data data member here.
5385 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5386 << Name;
5387 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5388 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005389 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005390 return true;
5391 }
5392
5393 if (!Prev->getInstantiatedFromStaticDataMember()) {
5394 // FIXME: Check for explicit specialization?
5395 Diag(D.getIdentifierLoc(),
5396 diag::err_explicit_instantiation_data_member_not_instantiated)
5397 << Prev;
5398 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5399 // FIXME: Can we provide a note showing where this was declared?
5400 return true;
5401 }
5402
Douglas Gregore47f5a72009-10-14 23:41:34 +00005403 // C++0x [temp.explicit]p2:
5404 // If the explicit instantiation is for a member function, a member class
5405 // or a static data member of a class template specialization, the name of
5406 // the class template specialization in the qualified-id for the member
5407 // name shall be a simple-template-id.
5408 //
5409 // C++98 has the same restriction, just worded differently.
5410 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5411 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005412 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005413 << Prev << D.getCXXScopeSpec().getRange();
5414
5415 // Check the scope of this explicit instantiation.
5416 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5417
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005418 // Verify that it is okay to explicitly instantiate here.
5419 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5420 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005421 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005422 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005423 MSInfo->getTemplateSpecializationKind(),
5424 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005425 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005426 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005427 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005428 return (Decl*) 0;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005429
Douglas Gregor450f00842009-09-25 18:43:00 +00005430 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005431 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005432 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005433 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregor450f00842009-09-25 18:43:00 +00005434
5435 // FIXME: Create an ExplicitInstantiation node?
John McCall48871652010-08-21 09:40:31 +00005436 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005437 }
5438
Douglas Gregor0e876e02009-09-25 23:53:26 +00005439 // If the declarator is a template-id, translate the parser's template
5440 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005441 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005442 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005443 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5444 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005445 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5446 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005447 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5448 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005449 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005450 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005451 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005452 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005453 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005454
Douglas Gregor450f00842009-09-25 18:43:00 +00005455 // C++ [temp.explicit]p1:
5456 // A [...] function [...] can be explicitly instantiated from its template.
5457 // A member function [...] of a class template can be explicitly
5458 // instantiated from the member definition associated with its class
5459 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005460 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005461 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5462 P != PEnd; ++P) {
5463 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005464 if (!HasExplicitTemplateArgs) {
5465 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5466 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5467 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005468
John McCall58cc69d2010-01-27 01:50:18 +00005469 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005470 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5471 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005472 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005473 }
5474 }
5475
5476 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5477 if (!FunTmpl)
5478 continue;
5479
John McCallbc077cf2010-02-08 23:07:23 +00005480 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005481 FunctionDecl *Specialization = 0;
5482 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005483 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005484 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005485 R, Specialization, Info)) {
5486 // FIXME: Keep track of almost-matches?
5487 (void)TDK;
5488 continue;
5489 }
5490
John McCall58cc69d2010-01-27 01:50:18 +00005491 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005492 }
5493
5494 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005495 UnresolvedSetIterator Result
5496 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005497 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005498 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5499 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5500 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005501
John McCall58cc69d2010-01-27 01:50:18 +00005502 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005503 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005504
5505 // Ignore access control bits, we don't need them for redeclaration checking.
5506 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005507
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005508 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005509 Diag(D.getIdentifierLoc(),
5510 diag::err_explicit_instantiation_member_function_not_instantiated)
5511 << Specialization
5512 << (Specialization->getTemplateSpecializationKind() ==
5513 TSK_ExplicitSpecialization);
5514 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5515 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005516 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005517
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005518 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005519 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5520 PrevDecl = Specialization;
5521
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005522 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005523 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005524 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005525 PrevDecl,
5526 PrevDecl->getTemplateSpecializationKind(),
5527 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005528 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005529 return true;
5530
5531 // FIXME: We may still want to build some representation of this
5532 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005533 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005534 return (Decl*) 0;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005535 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005536
5537 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005538
5539 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005540 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005541
Douglas Gregore47f5a72009-10-14 23:41:34 +00005542 // C++0x [temp.explicit]p2:
5543 // If the explicit instantiation is for a member function, a member class
5544 // or a static data member of a class template specialization, the name of
5545 // the class template specialization in the qualified-id for the member
5546 // name shall be a simple-template-id.
5547 //
5548 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005549 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005550 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005551 D.getCXXScopeSpec().isSet() &&
5552 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5553 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005554 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005555 << Specialization << D.getCXXScopeSpec().getRange();
5556
5557 CheckExplicitInstantiationScope(*this,
5558 FunTmpl? (NamedDecl *)FunTmpl
5559 : Specialization->getInstantiatedFromMemberFunction(),
5560 D.getIdentifierLoc(),
5561 D.getCXXScopeSpec().isSet());
5562
Douglas Gregor450f00842009-09-25 18:43:00 +00005563 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCall48871652010-08-21 09:40:31 +00005564 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005565}
5566
John McCallfaf5fb42010-08-26 23:41:50 +00005567TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005568Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5569 const CXXScopeSpec &SS, IdentifierInfo *Name,
5570 SourceLocation TagLoc, SourceLocation NameLoc) {
5571 // This has to hold, because SS is expected to be defined.
5572 assert(Name && "Expected a name in a dependent tag");
5573
5574 NestedNameSpecifier *NNS
5575 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5576 if (!NNS)
5577 return true;
5578
Abramo Bagnara6150c882010-05-11 21:36:43 +00005579 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005580
Douglas Gregorba41d012010-04-24 16:38:41 +00005581 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5582 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005583 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005584 return true;
5585 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005586
5587 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallba7bf592010-08-24 05:47:05 +00005588 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCall7f41d982009-09-11 04:59:25 +00005589}
5590
John McCallfaf5fb42010-08-26 23:41:50 +00005591TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005592Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5593 const CXXScopeSpec &SS, const IdentifierInfo &II,
5594 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005595 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005596 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5597 if (!NNS)
5598 return true;
5599
Douglas Gregorf7d77712010-06-16 22:31:08 +00005600 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5601 !getLangOptions().CPlusPlus0x)
5602 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5603 << FixItHint::CreateRemoval(TypenameLoc);
5604
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005605 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005606 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005607 if (T.isNull())
5608 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005609
5610 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5611 if (isa<DependentNameType>(T)) {
5612 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005613 TL.setKeywordLoc(TypenameLoc);
5614 TL.setQualifierRange(SS.getRange());
5615 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005616 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005617 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005618 TL.setKeywordLoc(TypenameLoc);
5619 TL.setQualifierRange(SS.getRange());
5620 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005621 }
5622
John McCallba7bf592010-08-24 05:47:05 +00005623 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00005624}
5625
John McCallfaf5fb42010-08-26 23:41:50 +00005626TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005627Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5628 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallba7bf592010-08-24 05:47:05 +00005629 ParsedType Ty) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00005630 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5631 !getLangOptions().CPlusPlus0x)
5632 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5633 << FixItHint::CreateRemoval(TypenameLoc);
5634
John McCallf7bcc812010-05-28 23:32:21 +00005635 TypeSourceInfo *InnerTSI = 0;
5636 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCallf7bcc812010-05-28 23:32:21 +00005637
5638 assert(isa<TemplateSpecializationType>(T) &&
5639 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005640
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005641 if (computeDeclContext(SS, false)) {
5642 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005643 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005644 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005645
5646 // Push the inner type, preserving its source locations if possible.
5647 TypeLocBuilder Builder;
5648 if (InnerTSI)
5649 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5650 else
5651 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5652
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005653 /* Note: NNS already embedded in template specialization type T. */
5654 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCallf7bcc812010-05-28 23:32:21 +00005655 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5656 TL.setKeywordLoc(TypenameLoc);
5657 TL.setQualifierRange(SS.getRange());
5658
5659 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallba7bf592010-08-24 05:47:05 +00005660 return CreateParsedType(T, TSI);
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005661 }
Mike Stump11289f42009-09-09 15:08:12 +00005662
John McCallc392f372010-06-11 00:33:02 +00005663 // TODO: it's really silly that we make a template specialization
5664 // type earlier only to drop it again here.
5665 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5666 DependentTemplateName *DTN =
5667 TST->getTemplateName().getAsDependentTemplateName();
5668 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005669 assert(DTN->getQualifier()
5670 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5671 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5672 DTN->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00005673 DTN->getIdentifier(),
5674 TST->getNumArgs(),
5675 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005676 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005677 DependentTemplateSpecializationTypeLoc TL =
5678 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5679 if (InnerTSI) {
5680 TemplateSpecializationTypeLoc TSTL =
5681 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5682 TL.setLAngleLoc(TSTL.getLAngleLoc());
5683 TL.setRAngleLoc(TSTL.getRAngleLoc());
5684 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5685 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5686 } else {
5687 TL.initializeLocal(SourceLocation());
5688 }
John McCallf7bcc812010-05-28 23:32:21 +00005689 TL.setKeywordLoc(TypenameLoc);
5690 TL.setQualifierRange(SS.getRange());
John McCallba7bf592010-08-24 05:47:05 +00005691 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00005692}
5693
Douglas Gregor333489b2009-03-27 23:10:48 +00005694/// \brief Build the type that describes a C++ typename specifier,
5695/// e.g., "typename T::type".
5696QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005697Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5698 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005699 SourceLocation KeywordLoc, SourceRange NNSRange,
5700 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005701 CXXScopeSpec SS;
5702 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005703 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005704
John McCall0b66eb32010-05-01 00:40:08 +00005705 DeclContext *Ctx = computeDeclContext(SS);
5706 if (!Ctx) {
5707 // If the nested-name-specifier is dependent and couldn't be
5708 // resolved to a type, build a typename type.
5709 assert(NNS->isDependent());
5710 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005711 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005712
John McCall0b66eb32010-05-01 00:40:08 +00005713 // If the nested-name-specifier refers to the current instantiation,
5714 // the "typename" keyword itself is superfluous. In C++03, the
5715 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5716 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005717 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005718
John McCall0b66eb32010-05-01 00:40:08 +00005719 if (RequireCompleteDeclContext(SS, Ctx))
5720 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005721
5722 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005723 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005724 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005725 unsigned DiagID = 0;
5726 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005727 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005728 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005729 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005730 break;
Douglas Gregoraed2efb2010-12-09 00:06:27 +00005731
5732 case LookupResult::FoundUnresolvedValue: {
5733 // We found a using declaration that is a value. Most likely, the using
5734 // declaration itself is meant to have the 'typename' keyword.
5735 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5736 IILoc);
5737 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
5738 << Name << Ctx << FullRange;
5739 if (UnresolvedUsingValueDecl *Using
5740 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
5741 SourceLocation Loc = Using->getTargetNestedNameRange().getBegin();
5742 Diag(Loc, diag::note_using_value_decl_missing_typename)
5743 << FixItHint::CreateInsertion(Loc, "typename ");
5744 }
5745 }
5746 // Fall through to create a dependent typename type, from which we can recover
5747 // better.
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005748
5749 case LookupResult::NotFoundInCurrentInstantiation:
5750 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005751 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005752
5753 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005754 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005755 // We found a type. Build an ElaboratedType, since the
5756 // typename-specifier was just sugar.
5757 return Context.getElaboratedType(ETK_Typename, NNS,
5758 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005759 }
5760
5761 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005762 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005763 break;
5764
Douglas Gregoraed2efb2010-12-09 00:06:27 +00005765
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005766 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005767 return QualType();
5768
Douglas Gregor333489b2009-03-27 23:10:48 +00005769 case LookupResult::FoundOverloaded:
5770 DiagID = diag::err_typename_nested_not_type;
5771 Referenced = *Result.begin();
5772 break;
5773
John McCall6538c932009-10-10 05:48:19 +00005774 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005775 return QualType();
5776 }
5777
5778 // If we get here, it's because name lookup did not find a
5779 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005780 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5781 IILoc);
5782 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005783 if (Referenced)
5784 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5785 << Name;
5786 return QualType();
5787}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005788
5789namespace {
5790 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005791 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005792 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005793 SourceLocation Loc;
5794 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005795
Douglas Gregor15acfb92009-08-06 16:20:37 +00005796 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005797 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5798
Mike Stump11289f42009-09-09 15:08:12 +00005799 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005800 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005801 DeclarationName Entity)
5802 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005803 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005804
5805 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005806 /// transformed.
5807 ///
5808 /// For the purposes of type reconstruction, a type has already been
5809 /// transformed if it is NULL or if it is not dependent.
5810 bool AlreadyTransformed(QualType T) {
5811 return T.isNull() || !T->isDependentType();
5812 }
Mike Stump11289f42009-09-09 15:08:12 +00005813
5814 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005815 /// rebuilt.
5816 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005817
Douglas Gregor15acfb92009-08-06 16:20:37 +00005818 /// \brief Returns the name of the entity whose type is being rebuilt.
5819 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005820
Douglas Gregoref6ab412009-10-27 06:26:26 +00005821 /// \brief Sets the "base" location and entity when that
5822 /// information is known based on another transformation.
5823 void setBase(SourceLocation Loc, DeclarationName Entity) {
5824 this->Loc = Loc;
5825 this->Entity = Entity;
5826 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005827 };
5828}
5829
Douglas Gregor15acfb92009-08-06 16:20:37 +00005830/// \brief Rebuilds a type within the context of the current instantiation.
5831///
Mike Stump11289f42009-09-09 15:08:12 +00005832/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005833/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005834/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005835/// partial specialization thereof). This routine will rebuild that type now
5836/// that we have entered the declarator's scope, which may produce different
5837/// canonical types, e.g.,
5838///
5839/// \code
5840/// template<typename T>
5841/// struct X {
5842/// typedef T* pointer;
5843/// pointer data();
5844/// };
5845///
5846/// template<typename T>
5847/// typename X<T>::pointer X<T>::data() { ... }
5848/// \endcode
5849///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005850/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005851/// since we do not know that we can look into X<T> when we parsed the type.
5852/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005853/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005854/// as the canonical type of T*, allowing the return types of the out-of-line
5855/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005856TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5857 SourceLocation Loc,
5858 DeclarationName Name) {
5859 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005860 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005861
Douglas Gregor15acfb92009-08-06 16:20:37 +00005862 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5863 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005864}
Douglas Gregorbe999392009-09-15 16:23:51 +00005865
John McCalldadc5752010-08-24 06:29:42 +00005866ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00005867 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5868 DeclarationName());
5869 return Rebuilder.TransformExpr(E);
5870}
5871
John McCall99b2fe52010-04-29 23:50:39 +00005872bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5873 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005874
5875 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5876 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5877 DeclarationName());
5878 NestedNameSpecifier *Rebuilt =
5879 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005880 if (!Rebuilt) return true;
5881
5882 SS.setScopeRep(Rebuilt);
5883 return false;
John McCall2408e322010-04-27 00:57:59 +00005884}
5885
Douglas Gregorbe999392009-09-15 16:23:51 +00005886/// \brief Produces a formatted string that describes the binding of
5887/// template parameters to template arguments.
5888std::string
5889Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5890 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005891 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00005892}
5893
5894std::string
5895Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5896 const TemplateArgument *Args,
5897 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005898 std::string Result;
5899
Douglas Gregore62e6a02009-11-11 19:13:48 +00005900 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005901 return Result;
5902
5903 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005904 if (I >= NumArgs)
5905 break;
5906
Douglas Gregorbe999392009-09-15 16:23:51 +00005907 if (I == 0)
5908 Result += "[with ";
5909 else
5910 Result += ", ";
5911
5912 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5913 Result += Id->getName();
5914 } else {
5915 Result += '$';
5916 Result += llvm::utostr(I);
5917 }
5918
5919 Result += " = ";
5920
5921 switch (Args[I].getKind()) {
5922 case TemplateArgument::Null:
5923 Result += "<no value>";
5924 break;
5925
5926 case TemplateArgument::Type: {
5927 std::string TypeStr;
5928 Args[I].getAsType().getAsStringInternal(TypeStr,
5929 Context.PrintingPolicy);
5930 Result += TypeStr;
5931 break;
5932 }
5933
5934 case TemplateArgument::Declaration: {
5935 bool Unnamed = true;
5936 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5937 if (ND->getDeclName()) {
5938 Unnamed = false;
5939 Result += ND->getNameAsString();
5940 }
5941 }
5942
5943 if (Unnamed) {
5944 Result += "<anonymous>";
5945 }
5946 break;
5947 }
5948
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005949 case TemplateArgument::Template: {
5950 std::string Str;
5951 llvm::raw_string_ostream OS(Str);
5952 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5953 Result += OS.str();
5954 break;
5955 }
5956
Douglas Gregorbe999392009-09-15 16:23:51 +00005957 case TemplateArgument::Integral: {
5958 Result += Args[I].getAsIntegral()->toString(10);
5959 break;
5960 }
5961
5962 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005963 // FIXME: This is non-optimal, since we're regurgitating the
5964 // expression we were given.
5965 std::string Str;
5966 {
5967 llvm::raw_string_ostream OS(Str);
5968 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5969 Context.PrintingPolicy);
5970 }
5971 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005972 break;
5973 }
5974
5975 case TemplateArgument::Pack:
5976 // FIXME: Format template argument packs
5977 Result += "<template argument pack>";
5978 break;
5979 }
5980 }
5981
5982 Result += ']';
5983 return Result;
5984}
Douglas Gregor506bd562010-12-13 22:49:22 +00005985