blob: f54b8b02e1d0980b43ce415f0fd530c9de21f69b [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
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000012#include "clang/Sema/Sema.h"
13#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"
Douglas Gregor15acfb92009-08-06 16:20:37 +000016#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000018#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000019#include "clang/AST/ExprCXX.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000020#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000021#include "clang/AST/DeclTemplate.h"
John McCall8b0666c2010-08-20 18:27:03 +000022#include "clang/Sema/DeclSpec.h"
23#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000024#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000025#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000026#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000027using namespace clang;
28
Douglas Gregorb7bfe792009-09-02 22:59:36 +000029/// \brief Determine whether the declaration found is acceptable as the name
30/// of a template and, if so, return that template declaration. Otherwise,
31/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000032static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
33 NamedDecl *Orig) {
34 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000035
Douglas Gregorb7bfe792009-09-02 22:59:36 +000036 if (isa<TemplateDecl>(D))
John McCalle9cccd82010-06-16 08:42:20 +000037 return Orig;
Mike Stump11289f42009-09-09 15:08:12 +000038
Douglas Gregorb7bfe792009-09-02 22:59:36 +000039 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
40 // C++ [temp.local]p1:
41 // Like normal (non-template) classes, class templates have an
42 // injected-class-name (Clause 9). The injected-class-name
43 // can be used with or without a template-argument-list. When
44 // it is used without a template-argument-list, it is
45 // equivalent to the injected-class-name followed by the
46 // template-parameters of the class template enclosed in
47 // <>. When it is used with a template-argument-list, it
48 // refers to the specified class template specialization,
49 // which could be the current specialization or another
50 // specialization.
51 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000052 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000053 if (Record->getDescribedClassTemplate())
54 return Record->getDescribedClassTemplate();
55
56 if (ClassTemplateSpecializationDecl *Spec
57 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
58 return Spec->getSpecializedTemplate();
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Douglas Gregorb7bfe792009-09-02 22:59:36 +000061 return 0;
62 }
Mike Stump11289f42009-09-09 15:08:12 +000063
Douglas Gregorb7bfe792009-09-02 22:59:36 +000064 return 0;
65}
66
John McCalle66edc12009-11-24 19:00:30 +000067static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor41f90302010-04-12 20:54:26 +000068 // The set of class templates we've already seen.
69 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000070 LookupResult::Filter filter = R.makeFilter();
71 while (filter.hasNext()) {
72 NamedDecl *Orig = filter.next();
John McCalle9cccd82010-06-16 08:42:20 +000073 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCalle66edc12009-11-24 19:00:30 +000074 if (!Repl)
75 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000076 else if (Repl != Orig) {
77
78 // C++ [temp.local]p3:
79 // A lookup that finds an injected-class-name (10.2) can result in an
80 // ambiguity in certain cases (for example, if it is found in more than
81 // one base class). If all of the injected-class-names that are found
82 // refer to specializations of the same class template, and if the name
83 // is followed by a template-argument-list, the reference refers to the
84 // class template itself and not a specialization thereof, and is not
85 // ambiguous.
86 //
87 // FIXME: Will we eventually have to do the same for alias templates?
88 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
89 if (!ClassTemplates.insert(ClassTmpl)) {
90 filter.erase();
91 continue;
92 }
John McCallbd8062d2010-08-13 07:02:08 +000093
94 // FIXME: we promote access to public here as a workaround to
95 // the fact that LookupResult doesn't let us remember that we
96 // found this template through a particular injected class name,
97 // which means we end up doing nasty things to the invariants.
98 // Pretending that access is public is *much* safer.
99 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000100 }
John McCalle66edc12009-11-24 19:00:30 +0000101 }
102 filter.done();
103}
104
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000105TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000106 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000107 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000108 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000109 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000110 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000111 TemplateTy &TemplateResult,
112 bool &MemberOfUnknownSpecialization) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000113 assert(getLangOptions().CPlusPlus && "No template names in C!");
114
Douglas Gregor3cf81312009-11-03 23:16:33 +0000115 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000116 MemberOfUnknownSpecialization = false;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000117
118 switch (Name.getKind()) {
119 case UnqualifiedId::IK_Identifier:
120 TName = DeclarationName(Name.Identifier);
121 break;
122
123 case UnqualifiedId::IK_OperatorFunctionId:
124 TName = Context.DeclarationNames.getCXXOperatorName(
125 Name.OperatorFunctionId.Operator);
126 break;
127
Alexis Hunted0530f2009-11-28 08:58:14 +0000128 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000129 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
130 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000131
Douglas Gregor3cf81312009-11-03 23:16:33 +0000132 default:
133 return TNK_Non_template;
134 }
Mike Stump11289f42009-09-09 15:08:12 +0000135
John McCallba7bf592010-08-24 05:47:05 +0000136 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000137
Douglas Gregorff18cc12009-12-31 08:11:17 +0000138 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
139 LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000140 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
141 MemberOfUnknownSpecialization);
John McCalldcc71402010-08-13 02:23:42 +0000142 if (R.empty() || R.isAmbiguous()) {
143 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000144 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000145 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000146
John McCalld28ae272009-12-02 08:04:21 +0000147 TemplateName Template;
148 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000149
John McCalld28ae272009-12-02 08:04:21 +0000150 unsigned ResultCount = R.end() - R.begin();
151 if (ResultCount > 1) {
152 // We assume that we'll preserve the qualifier from a function
153 // template name in other ways.
154 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
155 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000156
157 // We'll do this lookup again later.
158 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000159 } else {
John McCalld28ae272009-12-02 08:04:21 +0000160 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
161
162 if (SS.isSet() && !SS.isInvalid()) {
163 NestedNameSpecifier *Qualifier
164 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000165 Template = Context.getQualifiedTemplateName(Qualifier,
166 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000167 } else {
168 Template = TemplateName(TD);
169 }
170
John McCalldcc71402010-08-13 02:23:42 +0000171 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000172 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000173
174 // We'll do this lookup again later.
175 R.suppressDiagnostics();
176 } else {
John McCalld28ae272009-12-02 08:04:21 +0000177 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
178 TemplateKind = TNK_Type_template;
179 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000180 }
Mike Stump11289f42009-09-09 15:08:12 +0000181
John McCalld28ae272009-12-02 08:04:21 +0000182 TemplateResult = TemplateTy::make(Template);
183 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000184}
185
Douglas Gregor18473f32010-01-12 21:28:44 +0000186bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
187 SourceLocation IILoc,
188 Scope *S,
189 const CXXScopeSpec *SS,
190 TemplateTy &SuggestedTemplate,
191 TemplateNameKind &SuggestedKind) {
192 // We can't recover unless there's a dependent scope specifier preceding the
193 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000194 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000195 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
196 computeDeclContext(*SS))
197 return false;
198
199 // The code is missing a 'template' keyword prior to the dependent template
200 // name.
201 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
202 Diag(IILoc, diag::err_template_kw_missing)
203 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000204 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000205 SuggestedTemplate
206 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
207 SuggestedKind = TNK_Dependent_template_name;
208 return true;
209}
210
John McCalle66edc12009-11-24 19:00:30 +0000211void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000212 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000213 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000214 bool EnteringContext,
215 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000216 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000217 MemberOfUnknownSpecialization = false;
John McCalle66edc12009-11-24 19:00:30 +0000218 DeclContext *LookupCtx = 0;
219 bool isDependent = false;
220 if (!ObjectType.isNull()) {
221 // This nested-name-specifier occurs in a member access expression, e.g.,
222 // x->B::f, and we are looking into the type of the object.
223 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
224 LookupCtx = computeDeclContext(ObjectType);
225 isDependent = ObjectType->isDependentType();
226 assert((isDependent || !ObjectType->isIncompleteType()) &&
227 "Caller should have completed object type");
228 } else if (SS.isSet()) {
229 // This nested-name-specifier occurs after another nested-name-specifier,
230 // so long into the context associated with the prior nested-name-specifier.
231 LookupCtx = computeDeclContext(SS, EnteringContext);
232 isDependent = isDependentScopeSpecifier(SS);
233
234 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000235 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000236 return;
237 }
238
239 bool ObjectTypeSearchedInScope = false;
240 if (LookupCtx) {
241 // Perform "qualified" name lookup into the declaration context we
242 // computed, which is either the type of the base of a member access
243 // expression or the declaration context associated with a prior
244 // nested-name-specifier.
245 LookupQualifiedName(Found, LookupCtx);
246
247 if (!ObjectType.isNull() && Found.empty()) {
248 // C++ [basic.lookup.classref]p1:
249 // In a class member access expression (5.2.5), if the . or -> token is
250 // immediately followed by an identifier followed by a <, the
251 // identifier must be looked up to determine whether the < is the
252 // beginning of a template argument list (14.2) or a less-than operator.
253 // The identifier is first looked up in the class of the object
254 // expression. If the identifier is not found, it is then looked up in
255 // the context of the entire postfix-expression and shall name a class
256 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000257 if (S) LookupName(Found, S);
258 ObjectTypeSearchedInScope = true;
259 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000260 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000261 // We cannot look into a dependent object type or nested nme
262 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000263 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000264 return;
265 } else {
266 // Perform unqualified name lookup in the current scope.
267 LookupName(Found, S);
268 }
269
Douglas Gregorc119dd52010-01-12 17:06:20 +0000270 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000271 // If we did not find any names, attempt to correct any typos.
272 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000273 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregorc048c522010-06-29 19:27:42 +0000274 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000275 FilterAcceptableTemplateNames(Context, Found);
John McCalle9cccd82010-06-16 08:42:20 +0000276 if (!Found.empty()) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000277 if (LookupCtx)
278 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
279 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000280 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000281 Found.getLookupName().getAsString());
282 else
283 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
284 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000285 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000286 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000287 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
288 Diag(Template->getLocation(), diag::note_previous_decl)
289 << Template->getDeclName();
John McCalle9cccd82010-06-16 08:42:20 +0000290 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000291 } else {
292 Found.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +0000293 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000294 }
295 }
296
John McCalle66edc12009-11-24 19:00:30 +0000297 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000298 if (Found.empty()) {
299 if (isDependent)
300 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000301 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000302 }
John McCalle66edc12009-11-24 19:00:30 +0000303
304 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
305 // C++ [basic.lookup.classref]p1:
306 // [...] If the lookup in the class of the object expression finds a
307 // template, the name is also looked up in the context of the entire
308 // postfix-expression and [...]
309 //
310 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
311 LookupOrdinaryName);
312 LookupName(FoundOuter, S);
313 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000314
John McCalle66edc12009-11-24 19:00:30 +0000315 if (FoundOuter.empty()) {
316 // - if the name is not found, the name found in the class of the
317 // object expression is used, otherwise
318 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
319 // - if the name is found in the context of the entire
320 // postfix-expression and does not name a class template, the name
321 // found in the class of the object expression is used, otherwise
John McCalle9cccd82010-06-16 08:42:20 +0000322 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000323 // - if the name found is a class template, it must refer to the same
324 // entity as the one found in the class of the object expression,
325 // otherwise the program is ill-formed.
326 if (!Found.isSingleResult() ||
327 Found.getFoundDecl()->getCanonicalDecl()
328 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
329 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000330 diag::ext_nested_name_member_ref_lookup_ambiguous)
331 << Found.getLookupName()
332 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000333 Diag(Found.getRepresentativeDecl()->getLocation(),
334 diag::note_ambig_member_ref_object_type)
335 << ObjectType;
336 Diag(FoundOuter.getFoundDecl()->getLocation(),
337 diag::note_ambig_member_ref_scope);
338
339 // Recover by taking the template that we found in the object
340 // expression's type.
341 }
342 }
343 }
344}
345
John McCallcd4b4772009-12-02 03:53:29 +0000346/// ActOnDependentIdExpression - Handle a dependent id-expression that
347/// was just parsed. This is only possible with an explicit scope
348/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000349ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000350Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000351 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000352 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000353 const TemplateArgumentListInfo *TemplateArgs) {
354 NestedNameSpecifier *Qualifier
355 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall87fe5d52010-05-20 01:18:31 +0000356
357 DeclContext *DC = getFunctionLevelDeclContext();
John McCalle66edc12009-11-24 19:00:30 +0000358
John McCallcd4b4772009-12-02 03:53:29 +0000359 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000360 isa<CXXMethodDecl>(DC) &&
361 cast<CXXMethodDecl>(DC)->isInstance()) {
362 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallcd4b4772009-12-02 03:53:29 +0000363
John McCalle66edc12009-11-24 19:00:30 +0000364 // Since the 'this' expression is synthesized, we don't need to
365 // perform the double-lookup check.
366 NamedDecl *FirstQualifierInScope = 0;
367
John McCall2d74de92009-12-01 22:10:20 +0000368 return Owned(CXXDependentScopeMemberExpr::Create(Context,
369 /*This*/ 0, ThisType,
370 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000371 /*Op*/ SourceLocation(),
372 Qualifier, SS.getRange(),
373 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000374 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000375 TemplateArgs));
376 }
377
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000378 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000379}
380
John McCalldadc5752010-08-24 06:29:42 +0000381ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000382Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000383 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000384 const TemplateArgumentListInfo *TemplateArgs) {
385 return Owned(DependentScopeDeclRefExpr::Create(Context,
386 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
387 SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000388 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000389 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000390}
391
Douglas Gregor5101c242008-12-05 18:15:24 +0000392/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
393/// that the template parameter 'PrevDecl' is being shadowed by a new
394/// declaration at location Loc. Returns true to indicate that this is
395/// an error, and false otherwise.
396bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000397 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000398
399 // Microsoft Visual C++ permits template parameters to be shadowed.
400 if (getLangOptions().Microsoft)
401 return false;
402
403 // C++ [temp.local]p4:
404 // A template-parameter shall not be redeclared within its
405 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000406 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000407 << cast<NamedDecl>(PrevDecl)->getDeclName();
408 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
409 return true;
410}
411
Douglas Gregor463421d2009-03-03 04:44:36 +0000412/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000413/// the parameter D to reference the templated declaration and return a pointer
414/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000415TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
416 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
417 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000418 return Temp;
419 }
420 return 0;
421}
422
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000423static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
424 const ParsedTemplateArgument &Arg) {
425
426 switch (Arg.getKind()) {
427 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000428 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000429 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
430 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000431 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000432 return TemplateArgumentLoc(TemplateArgument(T), DI);
433 }
434
435 case ParsedTemplateArgument::NonType: {
436 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
437 return TemplateArgumentLoc(TemplateArgument(E), E);
438 }
439
440 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000441 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000442 return TemplateArgumentLoc(TemplateArgument(Template),
443 Arg.getScopeSpec().getRange(),
444 Arg.getLocation());
445 }
446 }
447
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000448 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000449 return TemplateArgumentLoc();
450}
451
452/// \brief Translates template arguments as provided by the parser
453/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000454void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
455 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000456 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000457 TemplateArgs.addArgument(translateTemplateArgument(*this,
458 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000459}
460
Douglas Gregor5101c242008-12-05 18:15:24 +0000461/// ActOnTypeParameter - Called when a C++ template type parameter
462/// (e.g., "typename T") has been parsed. Typename specifies whether
463/// the keyword "typename" was used to declare the type parameter
464/// (otherwise, "class" was used), and KeyLoc is the location of the
465/// "class" or "typename" keyword. ParamName is the name of the
466/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregor2ebcae12010-06-16 15:23:05 +0000467/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000468/// If the type parameter has a default argument, it will be added
469/// later via ActOnTypeParameterDefault.
John McCall48871652010-08-21 09:40:31 +0000470Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
471 SourceLocation EllipsisLoc,
472 SourceLocation KeyLoc,
473 IdentifierInfo *ParamName,
474 SourceLocation ParamNameLoc,
475 unsigned Depth, unsigned Position,
476 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000477 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000478 assert(S->isTemplateParamScope() &&
479 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000480 bool Invalid = false;
481
482 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000483 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000484 LookupOrdinaryName,
485 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000486 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000487 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000488 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000489 }
490
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000491 SourceLocation Loc = ParamNameLoc;
492 if (!ParamName)
493 Loc = KeyLoc;
494
Douglas Gregor5101c242008-12-05 18:15:24 +0000495 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000496 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
497 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000498 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000499 if (Invalid)
500 Param->setInvalidDecl();
501
502 if (ParamName) {
503 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000504 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000505 IdResolver.AddDecl(Param);
506 }
507
Douglas Gregordc13ded2010-07-01 00:00:45 +0000508 // Handle the default argument, if provided.
509 if (DefaultArg) {
510 TypeSourceInfo *DefaultTInfo;
511 GetTypeFromParser(DefaultArg, &DefaultTInfo);
512
513 assert(DefaultTInfo && "expected source information for type");
514
515 // C++0x [temp.param]p9:
516 // A default template-argument may be specified for any kind of
517 // template-parameter that is not a template parameter pack.
518 if (Ellipsis) {
519 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
John McCall48871652010-08-21 09:40:31 +0000520 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000521 }
522
523 // Check the template argument itself.
524 if (CheckTemplateArgument(Param, DefaultTInfo)) {
525 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000526 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000527 }
528
529 Param->setDefaultArgument(DefaultTInfo, false);
530 }
531
John McCall48871652010-08-21 09:40:31 +0000532 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000533}
534
Douglas Gregor463421d2009-03-03 04:44:36 +0000535/// \brief Check that the type of a non-type template parameter is
536/// well-formed.
537///
538/// \returns the (possibly-promoted) parameter type if valid;
539/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000540QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000541Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000542 // We don't allow variably-modified types as the type of non-type template
543 // parameters.
544 if (T->isVariablyModifiedType()) {
545 Diag(Loc, diag::err_variably_modified_nontype_template_param)
546 << T;
547 return QualType();
548 }
549
Douglas Gregor463421d2009-03-03 04:44:36 +0000550 // C++ [temp.param]p4:
551 //
552 // A non-type template-parameter shall have one of the following
553 // (optionally cv-qualified) types:
554 //
555 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000556 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000557 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000558 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000559 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000560 T->isReferenceType() ||
561 // -- pointer to member.
562 T->isMemberPointerType() ||
563 // If T is a dependent type, we can't do the check now, so we
564 // assume that it is well-formed.
565 T->isDependentType())
566 return T;
567 // C++ [temp.param]p8:
568 //
569 // A non-type template-parameter of type "array of T" or
570 // "function returning T" is adjusted to be of type "pointer to
571 // T" or "pointer to function returning T", respectively.
572 else if (T->isArrayType())
573 // FIXME: Keep the type prior to promotion?
574 return Context.getArrayDecayedType(T);
575 else if (T->isFunctionType())
576 // FIXME: Keep the type prior to promotion?
577 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000578
Douglas Gregor463421d2009-03-03 04:44:36 +0000579 Diag(Loc, diag::err_template_nontype_parm_bad_type)
580 << T;
581
582 return QualType();
583}
584
John McCall48871652010-08-21 09:40:31 +0000585Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
586 unsigned Depth,
587 unsigned Position,
588 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000589 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000590 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
591 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000592
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000593 assert(S->isTemplateParamScope() &&
594 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000595 bool Invalid = false;
596
597 IdentifierInfo *ParamName = D.getIdentifier();
598 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000599 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000600 LookupOrdinaryName,
601 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000602 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000603 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000604 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000605 }
606
Douglas Gregor463421d2009-03-03 04:44:36 +0000607 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000608 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000609 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000610 Invalid = true;
611 }
Douglas Gregor81338792009-02-10 17:43:50 +0000612
Douglas Gregor5101c242008-12-05 18:15:24 +0000613 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000614 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
615 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000616 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000617 if (Invalid)
618 Param->setInvalidDecl();
619
620 if (D.getIdentifier()) {
621 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000622 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000623 IdResolver.AddDecl(Param);
624 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000625
626 // Check the well-formedness of the default template argument, if provided.
John McCallb268a282010-08-23 23:25:46 +0000627 if (Default) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000628 TemplateArgument Converted;
629 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
630 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000631 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000632 }
633
John McCallb268a282010-08-23 23:25:46 +0000634 Param->setDefaultArgument(Default, false);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000635 }
636
John McCall48871652010-08-21 09:40:31 +0000637 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000638}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000639
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000640/// ActOnTemplateTemplateParameter - Called when a C++ template template
641/// parameter (e.g. T in template <template <typename> class T> class array)
642/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000643Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
644 SourceLocation TmpLoc,
645 TemplateParamsTy *Params,
646 IdentifierInfo *Name,
647 SourceLocation NameLoc,
648 unsigned Depth,
649 unsigned Position,
650 SourceLocation EqualLoc,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000651 const ParsedTemplateArgument &Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000652 assert(S->isTemplateParamScope() &&
653 "Template template parameter not in template parameter scope!");
654
655 // Construct the parameter object.
656 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000657 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
658 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000659 (TemplateParameterList*)Params);
660
Douglas Gregordc13ded2010-07-01 00:00:45 +0000661 // If the template template parameter has a name, then link the identifier
662 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000663 if (Name) {
John McCall48871652010-08-21 09:40:31 +0000664 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000665 IdResolver.AddDecl(Param);
666 }
667
Douglas Gregordc13ded2010-07-01 00:00:45 +0000668 if (!Default.isInvalid()) {
669 // Check only that we have a template template argument. We don't want to
670 // try to check well-formedness now, because our template template parameter
671 // might have dependent types in its template parameters, which we wouldn't
672 // be able to match now.
673 //
674 // If none of the template template parameter's template arguments mention
675 // other template parameters, we could actually perform more checking here.
676 // However, it isn't worth doing.
677 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
678 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
679 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
680 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000681 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000682 }
683
684 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000685 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000686
John McCall48871652010-08-21 09:40:31 +0000687 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000688}
689
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000690/// ActOnTemplateParameterList - Builds a TemplateParameterList that
691/// contains the template parameters in Params/NumParams.
692Sema::TemplateParamsTy *
693Sema::ActOnTemplateParameterList(unsigned Depth,
694 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000695 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000696 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000697 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000698 SourceLocation RAngleLoc) {
699 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000700 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000701
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000702 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000703 (NamedDecl**)Params, NumParams,
704 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000705}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000706
John McCall3e11ebe2010-03-15 10:12:16 +0000707static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
708 if (SS.isSet())
709 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
710 SS.getRange());
711}
712
Douglas Gregorc08f4892009-03-25 00:13:59 +0000713Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000714Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000715 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000716 IdentifierInfo *Name, SourceLocation NameLoc,
717 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000718 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000719 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000720 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000721 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000722 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000723 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000724
725 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000726 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000727 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000728
Abramo Bagnara6150c882010-05-11 21:36:43 +0000729 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
730 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000731
732 // There is no such thing as an unnamed class template.
733 if (!Name) {
734 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000735 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000736 }
737
738 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000739 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000740 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000741 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000742 if (SS.isNotEmpty() && !SS.isInvalid()) {
743 SemanticContext = computeDeclContext(SS, true);
744 if (!SemanticContext) {
745 // FIXME: Produce a reasonable diagnostic here
746 return true;
747 }
Mike Stump11289f42009-09-09 15:08:12 +0000748
John McCall0b66eb32010-05-01 00:40:08 +0000749 if (RequireCompleteDeclContext(SS, SemanticContext))
750 return true;
751
John McCall27b18f82009-11-17 02:14:36 +0000752 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000753 } else {
754 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000755 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000756 }
Mike Stump11289f42009-09-09 15:08:12 +0000757
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000758 if (Previous.isAmbiguous())
759 return true;
760
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000761 NamedDecl *PrevDecl = 0;
762 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000763 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000764
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000765 // If there is a previous declaration with the same name, check
766 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000767 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000768 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000769
770 // We may have found the injected-class-name of a class template,
771 // class template partial specialization, or class template specialization.
772 // In these cases, grab the template that is being defined or specialized.
773 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
774 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
775 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
776 PrevClassTemplate
777 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
778 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
779 PrevClassTemplate
780 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
781 ->getSpecializedTemplate();
782 }
783 }
784
John McCalld43784f2009-12-18 11:25:59 +0000785 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000786 // C++ [namespace.memdef]p3:
787 // [...] When looking for a prior declaration of a class or a function
788 // declared as a friend, and when the name of the friend class or
789 // function is neither a qualified name nor a template-id, scopes outside
790 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000791 if (!SS.isSet()) {
792 DeclContext *OutermostContext = CurContext;
793 while (!OutermostContext->isFileContext())
794 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000795
Douglas Gregorb74b1032010-04-18 17:37:40 +0000796 if (PrevDecl &&
797 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
798 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
799 SemanticContext = PrevDecl->getDeclContext();
800 } else {
801 // Declarations in outer scopes don't matter. However, the outermost
802 // context we computed is the semantic context for our new
803 // declaration.
804 PrevDecl = PrevClassTemplate = 0;
805 SemanticContext = OutermostContext;
806 }
John McCall90d3bb92009-12-17 23:21:11 +0000807 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000808
John McCall90d3bb92009-12-17 23:21:11 +0000809 if (CurContext->isDependentContext()) {
810 // If this is a dependent context, we don't want to link the friend
811 // class template to the template in scope, because that would perform
812 // checking of the template parameter lists that can't be performed
813 // until the outer context is instantiated.
814 PrevDecl = PrevClassTemplate = 0;
815 }
816 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
817 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000818
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000819 if (PrevClassTemplate) {
820 // Ensure that the template parameter lists are compatible.
821 if (!TemplateParameterListsAreEqual(TemplateParams,
822 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000823 /*Complain=*/true,
824 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000825 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000826
827 // C++ [temp.class]p4:
828 // In a redeclaration, partial specialization, explicit
829 // specialization or explicit instantiation of a class template,
830 // the class-key shall agree in kind with the original class
831 // template declaration (7.1.5.3).
832 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000833 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000834 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000835 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000836 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000837 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000838 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000839 }
840
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000841 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000842 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000843 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000844 Diag(NameLoc, diag::err_redefinition) << Name;
845 Diag(Def->getLocation(), diag::note_previous_definition);
846 // FIXME: Would it make sense to try to "forget" the previous
847 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000848 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000849 }
850 }
851 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
852 // Maybe we will complain about the shadowed template parameter.
853 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
854 // Just pretend that we didn't see the previous declaration.
855 PrevDecl = 0;
856 } else if (PrevDecl) {
857 // C++ [temp]p5:
858 // A class template shall not have the same name as any other
859 // template, class, function, object, enumeration, enumerator,
860 // namespace, or type in the same scope (3.3), except as specified
861 // in (14.5.4).
862 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
863 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000864 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000865 }
866
Douglas Gregordba32632009-02-10 19:49:53 +0000867 // Check the template parameter list of this declaration, possibly
868 // merging in the template parameter list from the previous class
869 // template declaration.
870 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000871 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
872 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000873 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000874
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000875 if (SS.isSet()) {
876 // If the name of the template was qualified, we must be defining the
877 // template out-of-line.
878 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
879 !(TUK == TUK_Friend && CurContext->isDependentContext()))
880 Diag(NameLoc, diag::err_member_def_does_not_match)
881 << Name << SemanticContext << SS.getRange();
882 }
883
Mike Stump11289f42009-09-09 15:08:12 +0000884 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000885 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000886 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000887 PrevClassTemplate->getTemplatedDecl() : 0,
888 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000889 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000890
891 ClassTemplateDecl *NewTemplate
892 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
893 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000894 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000895 NewClass->setDescribedClassTemplate(NewTemplate);
896
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000897 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000898 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +0000899 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000900 assert(T->isDependentType() && "Class template type is not dependent?");
901 (void)T;
902
Douglas Gregorcf915552009-10-13 16:30:37 +0000903 // If we are providing an explicit specialization of a member that is a
904 // class template, make a note of that.
905 if (PrevClassTemplate &&
906 PrevClassTemplate->getInstantiatedFromMemberTemplate())
907 PrevClassTemplate->setMemberSpecialization();
908
Anders Carlsson137108d2009-03-26 01:24:28 +0000909 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000910 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000911 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000912
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000913 // Set the lexical context of these templates
914 NewClass->setLexicalDeclContext(CurContext);
915 NewTemplate->setLexicalDeclContext(CurContext);
916
John McCall9bb74a52009-07-31 02:45:11 +0000917 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000918 NewClass->startDefinition();
919
920 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000921 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000922
John McCall27b5c252009-09-14 21:59:20 +0000923 if (TUK != TUK_Friend)
924 PushOnScopeChains(NewTemplate, S);
925 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000926 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000927 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000928 NewClass->setAccess(PrevClassTemplate->getAccess());
929 }
John McCall27b5c252009-09-14 21:59:20 +0000930
Douglas Gregor3dad8422009-09-26 06:47:28 +0000931 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
932 PrevClassTemplate != NULL);
933
John McCall27b5c252009-09-14 21:59:20 +0000934 // Friend templates are visible in fairly strange ways.
935 if (!CurContext->isDependentContext()) {
936 DeclContext *DC = SemanticContext->getLookupContext();
937 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
938 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
939 PushOnScopeChains(NewTemplate, EnclosingScope,
940 /* AddToContext = */ false);
941 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000942
943 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
944 NewClass->getLocation(),
945 NewTemplate,
946 /*FIXME:*/NewClass->getLocation());
947 Friend->setAccess(AS_public);
948 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000949 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000950
Douglas Gregordba32632009-02-10 19:49:53 +0000951 if (Invalid) {
952 NewTemplate->setInvalidDecl();
953 NewClass->setInvalidDecl();
954 }
John McCall48871652010-08-21 09:40:31 +0000955 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000956}
957
Douglas Gregored5731f2009-11-25 17:50:39 +0000958/// \brief Diagnose the presence of a default template argument on a
959/// template parameter, which is ill-formed in certain contexts.
960///
961/// \returns true if the default template argument should be dropped.
962static bool DiagnoseDefaultTemplateArgument(Sema &S,
963 Sema::TemplateParamListContext TPC,
964 SourceLocation ParamLoc,
965 SourceRange DefArgRange) {
966 switch (TPC) {
967 case Sema::TPC_ClassTemplate:
968 return false;
969
970 case Sema::TPC_FunctionTemplate:
971 // C++ [temp.param]p9:
972 // A default template-argument shall not be specified in a
973 // function template declaration or a function template
974 // definition [...]
975 // (This sentence is not in C++0x, per DR226).
976 if (!S.getLangOptions().CPlusPlus0x)
977 S.Diag(ParamLoc,
978 diag::err_template_parameter_default_in_function_template)
979 << DefArgRange;
980 return false;
981
982 case Sema::TPC_ClassTemplateMember:
983 // C++0x [temp.param]p9:
984 // A default template-argument shall not be specified in the
985 // template-parameter-lists of the definition of a member of a
986 // class template that appears outside of the member's class.
987 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
988 << DefArgRange;
989 return true;
990
991 case Sema::TPC_FriendFunctionTemplate:
992 // C++ [temp.param]p9:
993 // A default template-argument shall not be specified in a
994 // friend template declaration.
995 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
996 << DefArgRange;
997 return true;
998
999 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1000 // for friend function templates if there is only a single
1001 // declaration (and it is a definition). Strange!
1002 }
1003
1004 return false;
1005}
1006
Douglas Gregordba32632009-02-10 19:49:53 +00001007/// \brief Checks the validity of a template parameter list, possibly
1008/// considering the template parameter list from a previous
1009/// declaration.
1010///
1011/// If an "old" template parameter list is provided, it must be
1012/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1013/// template parameter list.
1014///
1015/// \param NewParams Template parameter list for a new template
1016/// declaration. This template parameter list will be updated with any
1017/// default arguments that are carried through from the previous
1018/// template parameter list.
1019///
1020/// \param OldParams If provided, template parameter list from a
1021/// previous declaration of the same template. Default template
1022/// arguments will be merged from the old template parameter list to
1023/// the new template parameter list.
1024///
Douglas Gregored5731f2009-11-25 17:50:39 +00001025/// \param TPC Describes the context in which we are checking the given
1026/// template parameter list.
1027///
Douglas Gregordba32632009-02-10 19:49:53 +00001028/// \returns true if an error occurred, false otherwise.
1029bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001030 TemplateParameterList *OldParams,
1031 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001032 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001033
Douglas Gregordba32632009-02-10 19:49:53 +00001034 // C++ [temp.param]p10:
1035 // The set of default template-arguments available for use with a
1036 // template declaration or definition is obtained by merging the
1037 // default arguments from the definition (if in scope) and all
1038 // declarations in scope in the same way default function
1039 // arguments are (8.3.6).
1040 bool SawDefaultArgument = false;
1041 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001042
Anders Carlsson327865d2009-06-12 23:20:15 +00001043 bool SawParameterPack = false;
1044 SourceLocation ParameterPackLoc;
1045
Mike Stumpc89c8e32009-02-11 23:03:27 +00001046 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001047 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001048 if (OldParams)
1049 OldParam = OldParams->begin();
1050
1051 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1052 NewParamEnd = NewParams->end();
1053 NewParam != NewParamEnd; ++NewParam) {
1054 // Variables used to diagnose redundant default arguments
1055 bool RedundantDefaultArg = false;
1056 SourceLocation OldDefaultLoc;
1057 SourceLocation NewDefaultLoc;
1058
1059 // Variables used to diagnose missing default arguments
1060 bool MissingDefaultArg = false;
1061
Anders Carlsson327865d2009-06-12 23:20:15 +00001062 // C++0x [temp.param]p11:
1063 // If a template parameter of a class template is a template parameter pack,
1064 // it must be the last template parameter.
1065 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001066 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001067 diag::err_template_param_pack_must_be_last_template_parameter);
1068 Invalid = true;
1069 }
1070
Douglas Gregordba32632009-02-10 19:49:53 +00001071 if (TemplateTypeParmDecl *NewTypeParm
1072 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001073 // Check the presence of a default argument here.
1074 if (NewTypeParm->hasDefaultArgument() &&
1075 DiagnoseDefaultTemplateArgument(*this, TPC,
1076 NewTypeParm->getLocation(),
1077 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001078 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001079 NewTypeParm->removeDefaultArgument();
1080
1081 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001082 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001083 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001084
Anders Carlsson327865d2009-06-12 23:20:15 +00001085 if (NewTypeParm->isParameterPack()) {
1086 assert(!NewTypeParm->hasDefaultArgument() &&
1087 "Parameter packs can't have a default argument!");
1088 SawParameterPack = true;
1089 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001090 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001091 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001092 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1093 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1094 SawDefaultArgument = true;
1095 RedundantDefaultArg = true;
1096 PreviousDefaultArgLoc = NewDefaultLoc;
1097 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1098 // Merge the default argument from the old declaration to the
1099 // new declaration.
1100 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001101 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001102 true);
1103 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1104 } else if (NewTypeParm->hasDefaultArgument()) {
1105 SawDefaultArgument = true;
1106 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1107 } else if (SawDefaultArgument)
1108 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001109 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001110 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001111 // Check the presence of a default argument here.
1112 if (NewNonTypeParm->hasDefaultArgument() &&
1113 DiagnoseDefaultTemplateArgument(*this, TPC,
1114 NewNonTypeParm->getLocation(),
1115 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001116 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001117 }
1118
Mike Stump12b8ce12009-08-04 21:02:39 +00001119 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001120 NonTypeTemplateParmDecl *OldNonTypeParm
1121 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001122 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001123 NewNonTypeParm->hasDefaultArgument()) {
1124 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1125 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1126 SawDefaultArgument = true;
1127 RedundantDefaultArg = true;
1128 PreviousDefaultArgLoc = NewDefaultLoc;
1129 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1130 // Merge the default argument from the old declaration to the
1131 // new declaration.
1132 SawDefaultArgument = true;
1133 // FIXME: We need to create a new kind of "default argument"
1134 // expression that points to a previous template template
1135 // parameter.
1136 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001137 OldNonTypeParm->getDefaultArgument(),
1138 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001139 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1140 } else if (NewNonTypeParm->hasDefaultArgument()) {
1141 SawDefaultArgument = true;
1142 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1143 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001144 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001145 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001146 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001147 TemplateTemplateParmDecl *NewTemplateParm
1148 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001149 if (NewTemplateParm->hasDefaultArgument() &&
1150 DiagnoseDefaultTemplateArgument(*this, TPC,
1151 NewTemplateParm->getLocation(),
1152 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001153 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001154
1155 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001156 TemplateTemplateParmDecl *OldTemplateParm
1157 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001158 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001159 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001160 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1161 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001162 SawDefaultArgument = true;
1163 RedundantDefaultArg = true;
1164 PreviousDefaultArgLoc = NewDefaultLoc;
1165 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1166 // Merge the default argument from the old declaration to the
1167 // new declaration.
1168 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001169 // FIXME: We need to create a new kind of "default argument" expression
1170 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001171 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001172 OldTemplateParm->getDefaultArgument(),
1173 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001174 PreviousDefaultArgLoc
1175 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001176 } else if (NewTemplateParm->hasDefaultArgument()) {
1177 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001178 PreviousDefaultArgLoc
1179 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001180 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001181 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001182 }
1183
1184 if (RedundantDefaultArg) {
1185 // C++ [temp.param]p12:
1186 // A template-parameter shall not be given default arguments
1187 // by two different declarations in the same scope.
1188 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1189 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1190 Invalid = true;
1191 } else if (MissingDefaultArg) {
1192 // C++ [temp.param]p11:
1193 // If a template-parameter has a default template-argument,
1194 // all subsequent template-parameters shall have a default
1195 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001196 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001197 diag::err_template_param_default_arg_missing);
1198 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1199 Invalid = true;
1200 }
1201
1202 // If we have an old template parameter list that we're merging
1203 // in, move on to the next parameter.
1204 if (OldParams)
1205 ++OldParam;
1206 }
1207
1208 return Invalid;
1209}
Douglas Gregord32e0282009-02-09 23:23:08 +00001210
Mike Stump11289f42009-09-09 15:08:12 +00001211/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001212/// specifier, returning the template parameter list that applies to the
1213/// name.
1214///
1215/// \param DeclStartLoc the start of the declaration that has a scope
1216/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001217///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001218/// \param SS the scope specifier that will be matched to the given template
1219/// parameter lists. This scope specifier precedes a qualified name that is
1220/// being declared.
1221///
1222/// \param ParamLists the template parameter lists, from the outermost to the
1223/// innermost template parameter lists.
1224///
1225/// \param NumParamLists the number of template parameter lists in ParamLists.
1226///
John McCalle820e5e2010-04-13 20:37:33 +00001227/// \param IsFriend Whether to apply the slightly different rules for
1228/// matching template parameters to scope specifiers in friend
1229/// declarations.
1230///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001231/// \param IsExplicitSpecialization will be set true if the entity being
1232/// declared is an explicit specialization, false otherwise.
1233///
Mike Stump11289f42009-09-09 15:08:12 +00001234/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001235/// name that is preceded by the scope specifier @p SS. This template
1236/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001237/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001238/// template specialization), or may be NULL (if we were's declaring isn't
1239/// itself a template).
1240TemplateParameterList *
1241Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1242 const CXXScopeSpec &SS,
1243 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001244 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001245 bool IsFriend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001246 bool &IsExplicitSpecialization,
1247 bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001248 IsExplicitSpecialization = false;
1249
Douglas Gregord8d297c2009-07-21 23:53:31 +00001250 // Find the template-ids that occur within the nested-name-specifier. These
1251 // template-ids will match up with the template parameter lists.
1252 llvm::SmallVector<const TemplateSpecializationType *, 4>
1253 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001254 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1255 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001256 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1257 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001258 const Type *T = NNS->getAsType();
1259 if (!T) break;
1260
1261 // C++0x [temp.expl.spec]p17:
1262 // A member or a member template may be nested within many
1263 // enclosing class templates. In an explicit specialization for
1264 // such a member, the member declaration shall be preceded by a
1265 // template<> for each enclosing class template that is
1266 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001267 //
1268 // Following the existing practice of GNU and EDG, we allow a typedef of a
1269 // template specialization type.
1270 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1271 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001272
Mike Stump11289f42009-09-09 15:08:12 +00001273 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001274 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001275 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1276 if (!Template)
1277 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001278
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001279 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001280 ClassTemplateSpecializationDecl *SpecDecl
1281 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1282 // If the nested name specifier refers to an explicit specialization,
1283 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001284 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1285 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001286 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001287 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001288 }
Mike Stump11289f42009-09-09 15:08:12 +00001289
Douglas Gregord8d297c2009-07-21 23:53:31 +00001290 TemplateIdsInSpecifier.push_back(SpecType);
1291 }
1292 }
Mike Stump11289f42009-09-09 15:08:12 +00001293
Douglas Gregord8d297c2009-07-21 23:53:31 +00001294 // Reverse the list of template-ids in the scope specifier, so that we can
1295 // more easily match up the template-ids and the template parameter lists.
1296 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001297
Douglas Gregord8d297c2009-07-21 23:53:31 +00001298 SourceLocation FirstTemplateLoc = DeclStartLoc;
1299 if (NumParamLists)
1300 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001301
Douglas Gregord8d297c2009-07-21 23:53:31 +00001302 // Match the template-ids found in the specifier to the template parameter
1303 // lists.
1304 unsigned Idx = 0;
1305 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1306 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001307 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1308 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001309 if (Idx >= NumParamLists) {
1310 // We have a template-id without a corresponding template parameter
1311 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001312
1313 // ...which is fine if this is a friend declaration.
1314 if (IsFriend) {
1315 IsExplicitSpecialization = true;
1316 break;
1317 }
1318
Douglas Gregord8d297c2009-07-21 23:53:31 +00001319 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001320 // FIXME: the location information here isn't great.
1321 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001322 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001323 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001324 << SS.getRange();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001325 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001326 } else {
1327 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1328 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001329 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001330 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001331 }
1332 return 0;
1333 }
Mike Stump11289f42009-09-09 15:08:12 +00001334
Douglas Gregord8d297c2009-07-21 23:53:31 +00001335 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001336 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001337 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001338
John McCall2408e322010-04-27 00:57:59 +00001339 // Are there cases in (e.g.) friends where this won't match?
1340 if (const InjectedClassNameType *Injected
1341 = TemplateId->getAs<InjectedClassNameType>()) {
1342 CXXRecordDecl *Record = Injected->getDecl();
1343 if (ClassTemplatePartialSpecializationDecl *Partial =
1344 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1345 ExpectedTemplateParams = Partial->getTemplateParameters();
1346 else
1347 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1348 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001349 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001350
John McCall2408e322010-04-27 00:57:59 +00001351 if (ExpectedTemplateParams)
1352 TemplateParameterListsAreEqual(ParamLists[Idx],
1353 ExpectedTemplateParams,
1354 true, TPL_TemplateMatch);
1355
Douglas Gregored5731f2009-11-25 17:50:39 +00001356 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001357 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001358 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001359 diag::err_template_param_list_matches_nontemplate)
1360 << TemplateId
1361 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001362 else
1363 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001364 }
Mike Stump11289f42009-09-09 15:08:12 +00001365
Douglas Gregord8d297c2009-07-21 23:53:31 +00001366 // If there were at least as many template-ids as there were template
1367 // parameter lists, then there are no template parameter lists remaining for
1368 // the declaration itself.
Douglas Gregor5be1eb82010-08-20 03:26:10 +00001369 if (Idx >= NumParamLists)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001370 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001371
Douglas Gregord8d297c2009-07-21 23:53:31 +00001372 // If there were too many template parameter lists, complain about that now.
1373 if (Idx != NumParamLists - 1) {
1374 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001375 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001376 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001377 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1378 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001379 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1380 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001381
1382 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1383 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1384 diag::note_explicit_template_spec_does_not_need_header)
1385 << ExplicitSpecializationsInSpecifier.back();
1386 ExplicitSpecializationsInSpecifier.pop_back();
1387 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001388
1389 // We have a template parameter list with no corresponding scope, which
1390 // means that the resulting template declaration can't be instantiated
1391 // properly (we'll end up with dependent nodes when we shouldn't).
1392 if (!isExplicitSpecHeader)
1393 Invalid = true;
1394
Douglas Gregord8d297c2009-07-21 23:53:31 +00001395 ++Idx;
1396 }
1397 }
Mike Stump11289f42009-09-09 15:08:12 +00001398
Douglas Gregord8d297c2009-07-21 23:53:31 +00001399 // Return the last template parameter list, which corresponds to the
1400 // entity being declared.
1401 return ParamLists[NumParamLists - 1];
1402}
1403
Douglas Gregordc572a32009-03-30 22:58:21 +00001404QualType Sema::CheckTemplateIdType(TemplateName Name,
1405 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001406 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001407 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001408 if (!Template) {
1409 // The template name does not resolve to a template, so we just
1410 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001411 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001412 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001413
Douglas Gregorc40290e2009-03-09 23:48:35 +00001414 // Check that the template argument list is well-formed for this
1415 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001416 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001417 TemplateArgs.size());
1418 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001419 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001420 return QualType();
1421
Mike Stump11289f42009-09-09 15:08:12 +00001422 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001423 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001424 "Converted template argument list is too short!");
1425
1426 QualType CanonType;
1427
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001428 if (Name.isDependent() ||
1429 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001430 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001431 // This class template specialization is a dependent
1432 // type. Therefore, its canonical type is another class template
1433 // specialization type that contains all of the converted
1434 // arguments in canonical form. This ensures that, e.g., A<T> and
1435 // A<T, T> have identical types when A is declared as:
1436 //
1437 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001438 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001439 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001440 Converted.getFlatArguments(),
1441 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001442
Douglas Gregora8e02e72009-07-28 23:00:59 +00001443 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001444 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001445 // In the future, we need to teach getTemplateSpecializationType to only
1446 // build the canonical type and return that to us.
1447 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001448
1449 // This might work out to be a current instantiation, in which
1450 // case the canonical type needs to be the InjectedClassNameType.
1451 //
1452 // TODO: in theory this could be a simple hashtable lookup; most
1453 // changes to CurContext don't change the set of current
1454 // instantiations.
1455 if (isa<ClassTemplateDecl>(Template)) {
1456 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1457 // If we get out to a namespace, we're done.
1458 if (Ctx->isFileContext()) break;
1459
1460 // If this isn't a record, keep looking.
1461 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1462 if (!Record) continue;
1463
1464 // Look for one of the two cases with InjectedClassNameTypes
1465 // and check whether it's the same template.
1466 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1467 !Record->getDescribedClassTemplate())
1468 continue;
1469
1470 // Fetch the injected class name type and check whether its
1471 // injected type is equal to the type we just built.
1472 QualType ICNT = Context.getTypeDeclType(Record);
1473 QualType Injected = cast<InjectedClassNameType>(ICNT)
1474 ->getInjectedSpecializationType();
1475
1476 if (CanonType != Injected->getCanonicalTypeInternal())
1477 continue;
1478
1479 // If so, the canonical type of this TST is the injected
1480 // class name type of the record we just found.
1481 assert(ICNT.isCanonical());
1482 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001483 break;
1484 }
1485 }
Mike Stump11289f42009-09-09 15:08:12 +00001486 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001487 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001488 // Find the class template specialization declaration that
1489 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001490 void *InsertPos = 0;
1491 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001492 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1493 Converted.flatSize(), InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001494 if (!Decl) {
1495 // This is the first time we have referenced this class template
1496 // specialization. Create the canonical declaration and add it to
1497 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001498 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001499 ClassTemplate->getTemplatedDecl()->getTagKind(),
1500 ClassTemplate->getDeclContext(),
1501 ClassTemplate->getLocation(),
1502 ClassTemplate,
1503 Converted, 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001504 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001505 Decl->setLexicalDeclContext(CurContext);
1506 }
1507
1508 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001509 assert(isa<RecordType>(CanonType) &&
1510 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001511 }
Mike Stump11289f42009-09-09 15:08:12 +00001512
Douglas Gregorc40290e2009-03-09 23:48:35 +00001513 // Build the fully-sugared type for this class template
1514 // specialization, which refers back to the class template
1515 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001516 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001517}
1518
Douglas Gregor67a65642009-02-17 23:15:12 +00001519Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001520Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001521 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001522 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001523 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001524 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001525
Douglas Gregorc40290e2009-03-09 23:48:35 +00001526 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001527 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001528 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001529
John McCall6b51f282009-11-23 01:53:49 +00001530 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001531 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001532
1533 if (Result.isNull())
1534 return true;
1535
John McCallbcd03502009-12-07 02:54:59 +00001536 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001537 TemplateSpecializationTypeLoc TL
1538 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1539 TL.setTemplateNameLoc(TemplateLoc);
1540 TL.setLAngleLoc(LAngleLoc);
1541 TL.setRAngleLoc(RAngleLoc);
1542 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1543 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1544
John McCallba7bf592010-08-24 05:47:05 +00001545 return CreateParsedType(Result, DI);
John McCalld8fe9af2009-09-08 17:47:29 +00001546}
John McCall06f6fe8d2009-09-04 01:14:41 +00001547
John McCalld8fe9af2009-09-08 17:47:29 +00001548Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1549 TagUseKind TUK,
1550 DeclSpec::TST TagSpec,
1551 SourceLocation TagLoc) {
1552 if (TypeResult.isInvalid())
1553 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001554
John McCall0ad16662009-10-29 08:12:44 +00001555 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001556 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001557 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001558
John McCalld8fe9af2009-09-08 17:47:29 +00001559 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001560 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001561
John McCalld8fe9af2009-09-08 17:47:29 +00001562 if (const RecordType *RT = Type->getAs<RecordType>()) {
1563 RecordDecl *D = RT->getDecl();
1564
1565 IdentifierInfo *Id = D->getIdentifier();
1566 assert(Id && "templated class must have an identifier");
1567
1568 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1569 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001570 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001571 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001572 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001573 }
1574 }
1575
Abramo Bagnara6150c882010-05-11 21:36:43 +00001576 ElaboratedTypeKeyword Keyword
1577 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1578 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001579
John McCallba7bf592010-08-24 05:47:05 +00001580 return ParsedType::make(ElabType);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001581}
1582
John McCalldadc5752010-08-24 06:29:42 +00001583ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001584 LookupResult &R,
1585 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001586 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001587 // FIXME: Can we do any checking at this point? I guess we could check the
1588 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001589 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001590 // though.
John McCalle66edc12009-11-24 19:00:30 +00001591
1592 // These should be filtered out by our callers.
1593 assert(!R.empty() && "empty lookup results when building templateid");
1594 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1595
1596 NestedNameSpecifier *Qualifier = 0;
1597 SourceRange QualifierRange;
1598 if (SS.isSet()) {
1599 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1600 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001601 }
John McCall58cc69d2010-01-27 01:50:18 +00001602
1603 // We don't want lookup warnings at this point.
1604 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001605
John McCalle66edc12009-11-24 19:00:30 +00001606 bool Dependent
1607 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1608 &TemplateArgs);
1609 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001610 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001611 Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001612 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001613 RequiresADL, TemplateArgs,
1614 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001615
1616 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001617}
1618
John McCalle66edc12009-11-24 19:00:30 +00001619// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00001620ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001621Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001622 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +00001623 const TemplateArgumentListInfo &TemplateArgs) {
1624 DeclContext *DC;
1625 if (!(DC = computeDeclContext(SS, false)) ||
1626 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001627 RequireCompleteDeclContext(SS, DC))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001628 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001629
Douglas Gregor786123d2010-05-21 23:18:07 +00001630 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001631 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001632 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1633 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001634
John McCalle66edc12009-11-24 19:00:30 +00001635 if (R.isAmbiguous())
1636 return ExprError();
1637
1638 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001639 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1640 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001641 return ExprError();
1642 }
1643
1644 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001645 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1646 << (NestedNameSpecifier*) SS.getScopeRep()
1647 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001648 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1649 return ExprError();
1650 }
1651
1652 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001653}
1654
Douglas Gregorb67535d2009-03-31 00:43:58 +00001655/// \brief Form a dependent template name.
1656///
1657/// This action forms a dependent template name given the template
1658/// name and its (presumably dependent) scope specifier. For
1659/// example, given "MetaFun::template apply", the scope specifier \p
1660/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1661/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregorbb119652010-06-16 23:00:59 +00001662TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1663 SourceLocation TemplateKWLoc,
1664 CXXScopeSpec &SS,
1665 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00001666 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00001667 bool EnteringContext,
1668 TemplateTy &Result) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001669 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1670 !getLangOptions().CPlusPlus0x)
1671 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1672 << FixItHint::CreateRemoval(TemplateKWLoc);
1673
Douglas Gregor9abe2372010-01-19 16:01:07 +00001674 DeclContext *LookupCtx = 0;
1675 if (SS.isSet())
1676 LookupCtx = computeDeclContext(SS, EnteringContext);
1677 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00001678 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00001679 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001680 // C++0x [temp.names]p5:
1681 // If a name prefixed by the keyword template is not the name of
1682 // a template, the program is ill-formed. [Note: the keyword
1683 // template may not be applied to non-template members of class
1684 // templates. -end note ] [ Note: as is the case with the
1685 // typename prefix, the template prefix is allowed in cases
1686 // where it is not strictly necessary; i.e., when the
1687 // nested-name-specifier or the expression on the left of the ->
1688 // or . is not dependent on a template-parameter, or the use
1689 // does not appear in the scope of a template. -end note]
1690 //
1691 // Note: C++03 was more strict here, because it banned the use of
1692 // the "template" keyword prior to a template-name that was not a
1693 // dependent name. C++ DR468 relaxed this requirement (the
1694 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001695 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00001696 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001697 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1698 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00001699 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001700 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1701 isa<CXXRecordDecl>(LookupCtx) &&
1702 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregorbb119652010-06-16 23:00:59 +00001703 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00001704 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001705 Diag(Name.getSourceRange().getBegin(),
1706 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001707 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001708 << Name.getSourceRange()
1709 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001710 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00001711 } else {
1712 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00001713 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001714 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001715 }
1716
Mike Stump11289f42009-09-09 15:08:12 +00001717 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001718 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001719
1720 switch (Name.getKind()) {
1721 case UnqualifiedId::IK_Identifier:
Douglas Gregorbb119652010-06-16 23:00:59 +00001722 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1723 Name.Identifier));
1724 return TNK_Dependent_template_name;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001725
Douglas Gregor71395fa2009-11-04 00:56:37 +00001726 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00001727 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001728 Name.OperatorFunctionId.Operator));
Douglas Gregorbb119652010-06-16 23:00:59 +00001729 return TNK_Dependent_template_name;
Alexis Hunted0530f2009-11-28 08:58:14 +00001730
1731 case UnqualifiedId::IK_LiteralOperatorId:
1732 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1733
Douglas Gregor3cf81312009-11-03 23:16:33 +00001734 default:
1735 break;
1736 }
1737
1738 Diag(Name.getSourceRange().getBegin(),
1739 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001740 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001741 << Name.getSourceRange()
1742 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001743 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001744}
1745
Mike Stump11289f42009-09-09 15:08:12 +00001746bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001747 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001748 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001749 const TemplateArgument &Arg = AL.getArgument();
1750
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001751 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001752 switch(Arg.getKind()) {
1753 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001754 // C++ [temp.arg.type]p1:
1755 // A template-argument for a template-parameter which is a
1756 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001757 break;
1758 case TemplateArgument::Template: {
1759 // We have a template type parameter but the template argument
1760 // is a template without any arguments.
1761 SourceRange SR = AL.getSourceRange();
1762 TemplateName Name = Arg.getAsTemplate();
1763 Diag(SR.getBegin(), diag::err_template_missing_args)
1764 << Name << SR;
1765 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1766 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001767
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001768 return true;
1769 }
1770 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001771 // We have a template type parameter but the template argument
1772 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001773 SourceRange SR = AL.getSourceRange();
1774 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001775 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001776
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001777 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001778 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001779 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001780
John McCallbcd03502009-12-07 02:54:59 +00001781 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001782 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001783
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001784 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001785 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001786 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001787 return false;
1788}
1789
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001790/// \brief Substitute template arguments into the default template argument for
1791/// the given template type parameter.
1792///
1793/// \param SemaRef the semantic analysis object for which we are performing
1794/// the substitution.
1795///
1796/// \param Template the template that we are synthesizing template arguments
1797/// for.
1798///
1799/// \param TemplateLoc the location of the template name that started the
1800/// template-id we are checking.
1801///
1802/// \param RAngleLoc the location of the right angle bracket ('>') that
1803/// terminates the template-id.
1804///
1805/// \param Param the template template parameter whose default we are
1806/// substituting into.
1807///
1808/// \param Converted the list of template arguments provided for template
1809/// parameters that precede \p Param in the template parameter list.
1810///
1811/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001812static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001813SubstDefaultTemplateArgument(Sema &SemaRef,
1814 TemplateDecl *Template,
1815 SourceLocation TemplateLoc,
1816 SourceLocation RAngleLoc,
1817 TemplateTypeParmDecl *Param,
1818 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001819 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001820
1821 // If the argument type is dependent, instantiate it now based
1822 // on the previously-computed template arguments.
1823 if (ArgType->getType()->isDependentType()) {
1824 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1825 /*TakeArgs=*/false);
1826
1827 MultiLevelTemplateArgumentList AllTemplateArgs
1828 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1829
1830 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1831 Template, Converted.getFlatArguments(),
1832 Converted.flatSize(),
1833 SourceRange(TemplateLoc, RAngleLoc));
1834
1835 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1836 Param->getDefaultArgumentLoc(),
1837 Param->getDeclName());
1838 }
1839
1840 return ArgType;
1841}
1842
1843/// \brief Substitute template arguments into the default template argument for
1844/// the given non-type template parameter.
1845///
1846/// \param SemaRef the semantic analysis object for which we are performing
1847/// the substitution.
1848///
1849/// \param Template the template that we are synthesizing template arguments
1850/// for.
1851///
1852/// \param TemplateLoc the location of the template name that started the
1853/// template-id we are checking.
1854///
1855/// \param RAngleLoc the location of the right angle bracket ('>') that
1856/// terminates the template-id.
1857///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001858/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001859/// substituting into.
1860///
1861/// \param Converted the list of template arguments provided for template
1862/// parameters that precede \p Param in the template parameter list.
1863///
1864/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00001865static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001866SubstDefaultTemplateArgument(Sema &SemaRef,
1867 TemplateDecl *Template,
1868 SourceLocation TemplateLoc,
1869 SourceLocation RAngleLoc,
1870 NonTypeTemplateParmDecl *Param,
1871 TemplateArgumentListBuilder &Converted) {
1872 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1873 /*TakeArgs=*/false);
1874
1875 MultiLevelTemplateArgumentList AllTemplateArgs
1876 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1877
1878 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1879 Template, Converted.getFlatArguments(),
1880 Converted.flatSize(),
1881 SourceRange(TemplateLoc, RAngleLoc));
1882
1883 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1884}
1885
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001886/// \brief Substitute template arguments into the default template argument for
1887/// the given template template parameter.
1888///
1889/// \param SemaRef the semantic analysis object for which we are performing
1890/// the substitution.
1891///
1892/// \param Template the template that we are synthesizing template arguments
1893/// for.
1894///
1895/// \param TemplateLoc the location of the template name that started the
1896/// template-id we are checking.
1897///
1898/// \param RAngleLoc the location of the right angle bracket ('>') that
1899/// terminates the template-id.
1900///
1901/// \param Param the template template parameter whose default we are
1902/// substituting into.
1903///
1904/// \param Converted the list of template arguments provided for template
1905/// parameters that precede \p Param in the template parameter list.
1906///
1907/// \returns the substituted template argument, or NULL if an error occurred.
1908static TemplateName
1909SubstDefaultTemplateArgument(Sema &SemaRef,
1910 TemplateDecl *Template,
1911 SourceLocation TemplateLoc,
1912 SourceLocation RAngleLoc,
1913 TemplateTemplateParmDecl *Param,
1914 TemplateArgumentListBuilder &Converted) {
1915 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1916 /*TakeArgs=*/false);
1917
1918 MultiLevelTemplateArgumentList AllTemplateArgs
1919 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1920
1921 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1922 Template, Converted.getFlatArguments(),
1923 Converted.flatSize(),
1924 SourceRange(TemplateLoc, RAngleLoc));
1925
1926 return SemaRef.SubstTemplateName(
1927 Param->getDefaultArgument().getArgument().getAsTemplate(),
1928 Param->getDefaultArgument().getTemplateNameLoc(),
1929 AllTemplateArgs);
1930}
1931
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001932/// \brief If the given template parameter has a default template
1933/// argument, substitute into that default template argument and
1934/// return the corresponding template argument.
1935TemplateArgumentLoc
1936Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1937 SourceLocation TemplateLoc,
1938 SourceLocation RAngleLoc,
1939 Decl *Param,
1940 TemplateArgumentListBuilder &Converted) {
1941 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1942 if (!TypeParm->hasDefaultArgument())
1943 return TemplateArgumentLoc();
1944
John McCallbcd03502009-12-07 02:54:59 +00001945 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001946 TemplateLoc,
1947 RAngleLoc,
1948 TypeParm,
1949 Converted);
1950 if (DI)
1951 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1952
1953 return TemplateArgumentLoc();
1954 }
1955
1956 if (NonTypeTemplateParmDecl *NonTypeParm
1957 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1958 if (!NonTypeParm->hasDefaultArgument())
1959 return TemplateArgumentLoc();
1960
John McCalldadc5752010-08-24 06:29:42 +00001961 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001962 TemplateLoc,
1963 RAngleLoc,
1964 NonTypeParm,
1965 Converted);
1966 if (Arg.isInvalid())
1967 return TemplateArgumentLoc();
1968
1969 Expr *ArgE = Arg.takeAs<Expr>();
1970 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1971 }
1972
1973 TemplateTemplateParmDecl *TempTempParm
1974 = cast<TemplateTemplateParmDecl>(Param);
1975 if (!TempTempParm->hasDefaultArgument())
1976 return TemplateArgumentLoc();
1977
1978 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1979 TemplateLoc,
1980 RAngleLoc,
1981 TempTempParm,
1982 Converted);
1983 if (TName.isNull())
1984 return TemplateArgumentLoc();
1985
1986 return TemplateArgumentLoc(TemplateArgument(TName),
1987 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1988 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1989}
1990
Douglas Gregorda0fb532009-11-11 19:31:23 +00001991/// \brief Check that the given template argument corresponds to the given
1992/// template parameter.
1993bool Sema::CheckTemplateArgument(NamedDecl *Param,
1994 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001995 TemplateDecl *Template,
1996 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001997 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001998 TemplateArgumentListBuilder &Converted,
1999 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00002000 // Check template type parameters.
2001 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002002 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002003
Douglas Gregoreebed722009-11-11 19:41:09 +00002004 // Check non-type template parameters.
2005 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002006 // Do substitution on the type of the non-type template parameter
2007 // with the template arguments we've seen thus far.
2008 QualType NTTPType = NTTP->getType();
2009 if (NTTPType->isDependentType()) {
2010 // Do substitution on the type of the non-type template parameter.
2011 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2012 NTTP, Converted.getFlatArguments(),
2013 Converted.flatSize(),
2014 SourceRange(TemplateLoc, RAngleLoc));
2015
2016 TemplateArgumentList TemplateArgs(Context, Converted,
2017 /*TakeArgs=*/false);
2018 NTTPType = SubstType(NTTPType,
2019 MultiLevelTemplateArgumentList(TemplateArgs),
2020 NTTP->getLocation(),
2021 NTTP->getDeclName());
2022 // If that worked, check the non-type template parameter type
2023 // for validity.
2024 if (!NTTPType.isNull())
2025 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2026 NTTP->getLocation());
2027 if (NTTPType.isNull())
2028 return true;
2029 }
2030
2031 switch (Arg.getArgument().getKind()) {
2032 case TemplateArgument::Null:
2033 assert(false && "Should never see a NULL template argument here");
2034 return true;
2035
2036 case TemplateArgument::Expression: {
2037 Expr *E = Arg.getArgument().getAsExpr();
2038 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002039 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002040 return true;
2041
2042 Converted.Append(Result);
2043 break;
2044 }
2045
2046 case TemplateArgument::Declaration:
2047 case TemplateArgument::Integral:
2048 // We've already checked this template argument, so just copy
2049 // it to the list of converted arguments.
2050 Converted.Append(Arg.getArgument());
2051 break;
2052
2053 case TemplateArgument::Template:
2054 // We were given a template template argument. It may not be ill-formed;
2055 // see below.
2056 if (DependentTemplateName *DTN
2057 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2058 // We have a template argument such as \c T::template X, which we
2059 // parsed as a template template argument. However, since we now
2060 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002061 // template name into an expression.
2062
2063 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2064 Arg.getTemplateNameLoc());
2065
John McCalle66edc12009-11-24 19:00:30 +00002066 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2067 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002068 Arg.getTemplateQualifierRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002069 NameInfo);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002070
2071 TemplateArgument Result;
2072 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2073 return true;
2074
2075 Converted.Append(Result);
2076 break;
2077 }
2078
2079 // We have a template argument that actually does refer to a class
2080 // template, template alias, or template template parameter, and
2081 // therefore cannot be a non-type template argument.
2082 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2083 << Arg.getSourceRange();
2084
2085 Diag(Param->getLocation(), diag::note_template_param_here);
2086 return true;
2087
2088 case TemplateArgument::Type: {
2089 // We have a non-type template parameter but the template
2090 // argument is a type.
2091
2092 // C++ [temp.arg]p2:
2093 // In a template-argument, an ambiguity between a type-id and
2094 // an expression is resolved to a type-id, regardless of the
2095 // form of the corresponding template-parameter.
2096 //
2097 // We warn specifically about this case, since it can be rather
2098 // confusing for users.
2099 QualType T = Arg.getArgument().getAsType();
2100 SourceRange SR = Arg.getSourceRange();
2101 if (T->isFunctionType())
2102 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2103 else
2104 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2105 Diag(Param->getLocation(), diag::note_template_param_here);
2106 return true;
2107 }
2108
2109 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002110 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002111 break;
2112 }
2113
2114 return false;
2115 }
2116
2117
2118 // Check template template parameters.
2119 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2120
2121 // Substitute into the template parameter list of the template
2122 // template parameter, since previously-supplied template arguments
2123 // may appear within the template template parameter.
2124 {
2125 // Set up a template instantiation context.
2126 LocalInstantiationScope Scope(*this);
2127 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2128 TempParm, Converted.getFlatArguments(),
2129 Converted.flatSize(),
2130 SourceRange(TemplateLoc, RAngleLoc));
2131
2132 TemplateArgumentList TemplateArgs(Context, Converted,
2133 /*TakeArgs=*/false);
2134 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2135 SubstDecl(TempParm, CurContext,
2136 MultiLevelTemplateArgumentList(TemplateArgs)));
2137 if (!TempParm)
2138 return true;
2139
2140 // FIXME: TempParam is leaked.
2141 }
2142
2143 switch (Arg.getArgument().getKind()) {
2144 case TemplateArgument::Null:
2145 assert(false && "Should never see a NULL template argument here");
2146 return true;
2147
2148 case TemplateArgument::Template:
2149 if (CheckTemplateArgument(TempParm, Arg))
2150 return true;
2151
2152 Converted.Append(Arg.getArgument());
2153 break;
2154
2155 case TemplateArgument::Expression:
2156 case TemplateArgument::Type:
2157 // We have a template template parameter but the template
2158 // argument does not refer to a template.
2159 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2160 return true;
2161
2162 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002163 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002164 "Declaration argument with template template parameter");
2165 break;
2166 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002167 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002168 "Integral argument with template template parameter");
2169 break;
2170
2171 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002172 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002173 break;
2174 }
2175
2176 return false;
2177}
2178
Douglas Gregord32e0282009-02-09 23:23:08 +00002179/// \brief Check that the given template argument list is well-formed
2180/// for specializing the given template.
2181bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2182 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002183 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002184 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002185 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002186 TemplateParameterList *Params = Template->getTemplateParameters();
2187 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002188 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002189 bool Invalid = false;
2190
John McCall6b51f282009-11-23 01:53:49 +00002191 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2192
Mike Stump11289f42009-09-09 15:08:12 +00002193 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002194 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002195
Anders Carlsson15201f12009-06-13 02:08:00 +00002196 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002197 (NumArgs < Params->getMinRequiredArguments() &&
2198 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002199 // FIXME: point at either the first arg beyond what we can handle,
2200 // or the '>', depending on whether we have too many or too few
2201 // arguments.
2202 SourceRange Range;
2203 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002204 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002205 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2206 << (NumArgs > NumParams)
2207 << (isa<ClassTemplateDecl>(Template)? 0 :
2208 isa<FunctionTemplateDecl>(Template)? 1 :
2209 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2210 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002211 Diag(Template->getLocation(), diag::note_template_decl_here)
2212 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002213 Invalid = true;
2214 }
Mike Stump11289f42009-09-09 15:08:12 +00002215
2216 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002217 // [...] The type and form of each template-argument specified in
2218 // a template-id shall match the type and form specified for the
2219 // corresponding parameter declared by the template in its
2220 // template-parameter-list.
2221 unsigned ArgIdx = 0;
2222 for (TemplateParameterList::iterator Param = Params->begin(),
2223 ParamEnd = Params->end();
2224 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002225 if (ArgIdx > NumArgs && PartialTemplateArgs)
2226 break;
Mike Stump11289f42009-09-09 15:08:12 +00002227
Douglas Gregoreebed722009-11-11 19:41:09 +00002228 // If we have a template parameter pack, check every remaining template
2229 // argument against that template parameter pack.
2230 if ((*Param)->isTemplateParameterPack()) {
2231 Converted.BeginPack();
2232 for (; ArgIdx < NumArgs; ++ArgIdx) {
2233 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2234 TemplateLoc, RAngleLoc, Converted)) {
2235 Invalid = true;
2236 break;
2237 }
2238 }
2239 Converted.EndPack();
2240 continue;
2241 }
2242
Douglas Gregor84d49a22009-11-11 21:54:23 +00002243 if (ArgIdx < NumArgs) {
2244 // Check the template argument we were given.
2245 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2246 TemplateLoc, RAngleLoc, Converted))
2247 return true;
2248
2249 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002250 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002251
Douglas Gregor84d49a22009-11-11 21:54:23 +00002252 // We have a default template argument that we will use.
2253 TemplateArgumentLoc Arg;
2254
2255 // Retrieve the default template argument from the template
2256 // parameter. For each kind of template parameter, we substitute the
2257 // template arguments provided thus far and any "outer" template arguments
2258 // (when the template parameter was part of a nested template) into
2259 // the default argument.
2260 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2261 if (!TTP->hasDefaultArgument()) {
2262 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2263 break;
2264 }
2265
John McCallbcd03502009-12-07 02:54:59 +00002266 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002267 Template,
2268 TemplateLoc,
2269 RAngleLoc,
2270 TTP,
2271 Converted);
2272 if (!ArgType)
2273 return true;
2274
2275 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2276 ArgType);
2277 } else if (NonTypeTemplateParmDecl *NTTP
2278 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2279 if (!NTTP->hasDefaultArgument()) {
2280 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2281 break;
2282 }
2283
John McCalldadc5752010-08-24 06:29:42 +00002284 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002285 TemplateLoc,
2286 RAngleLoc,
2287 NTTP,
2288 Converted);
2289 if (E.isInvalid())
2290 return true;
2291
2292 Expr *Ex = E.takeAs<Expr>();
2293 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2294 } else {
2295 TemplateTemplateParmDecl *TempParm
2296 = cast<TemplateTemplateParmDecl>(*Param);
2297
2298 if (!TempParm->hasDefaultArgument()) {
2299 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2300 break;
2301 }
2302
2303 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2304 TemplateLoc,
2305 RAngleLoc,
2306 TempParm,
2307 Converted);
2308 if (Name.isNull())
2309 return true;
2310
2311 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2312 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2313 TempParm->getDefaultArgument().getTemplateNameLoc());
2314 }
2315
2316 // Introduce an instantiation record that describes where we are using
2317 // the default template argument.
2318 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2319 Converted.getFlatArguments(),
2320 Converted.flatSize(),
2321 SourceRange(TemplateLoc, RAngleLoc));
2322
2323 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002324 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002325 RAngleLoc, Converted))
2326 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002327 }
2328
2329 return Invalid;
2330}
2331
2332/// \brief Check a template argument against its corresponding
2333/// template type parameter.
2334///
2335/// This routine implements the semantics of C++ [temp.arg.type]. It
2336/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002337bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002338 TypeSourceInfo *ArgInfo) {
2339 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002340 QualType Arg = ArgInfo->getType();
2341
Douglas Gregord32e0282009-02-09 23:23:08 +00002342 // C++ [temp.arg.type]p2:
2343 // A local type, a type with no linkage, an unnamed type or a type
2344 // compounded from any of these types shall not be used as a
2345 // template-argument for a template type-parameter.
2346 //
Douglas Gregor959d5a02010-05-22 16:17:30 +00002347 // FIXME: Perform the unnamed type check.
2348 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002349 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002350 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002351 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002352 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002353 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002354 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002355 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00002356 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2357 << QualType(Tag, 0) << SR;
2358 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002359 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002360 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002361 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2362 return true;
Douglas Gregor959d5a02010-05-22 16:17:30 +00002363 } else if (Arg->isVariablyModifiedType()) {
2364 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2365 << Arg;
2366 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002367 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002368 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002369 }
2370
2371 return false;
2372}
2373
Douglas Gregorccb07762009-02-11 19:52:55 +00002374/// \brief Checks whether the given template argument is the address
2375/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002376static bool
2377CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2378 NonTypeTemplateParmDecl *Param,
2379 QualType ParamType,
2380 Expr *ArgIn,
2381 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002382 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002383 Expr *Arg = ArgIn;
2384 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002385
2386 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002387 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002388 Arg = Cast->getSubExpr();
2389
2390 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002391 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002392 // A template-argument for a non-type, non-template
2393 // template-parameter shall be one of: [...]
2394 //
2395 // -- the address of an object or function with external
2396 // linkage, including function templates and function
2397 // template-ids but excluding non-static class members,
2398 // expressed as & id-expression where the & is optional if
2399 // the name refers to a function or array, or if the
2400 // corresponding template-parameter is a reference; or
2401 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002402
Douglas Gregorccb07762009-02-11 19:52:55 +00002403 // Ignore (and complain about) any excess parentheses.
2404 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2405 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002406 S.Diag(Arg->getSourceRange().getBegin(),
2407 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002408 << Arg->getSourceRange();
2409 Invalid = true;
2410 }
2411
2412 Arg = Parens->getSubExpr();
2413 }
2414
Douglas Gregorb242683d2010-04-01 18:32:35 +00002415 bool AddressTaken = false;
2416 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002417 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002418 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002419 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002420 AddressTaken = true;
2421 AddrOpLoc = UnOp->getOperatorLoc();
2422 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002423 } else
2424 DRE = dyn_cast<DeclRefExpr>(Arg);
2425
Douglas Gregorb242683d2010-04-01 18:32:35 +00002426 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002427 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2428 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002429 S.Diag(Param->getLocation(), diag::note_template_param_here);
2430 return true;
2431 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002432
2433 // Stop checking the precise nature of the argument if it is value dependent,
2434 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002435 if (Arg->isValueDependent()) {
2436 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002437 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002438 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002439
Douglas Gregorb242683d2010-04-01 18:32:35 +00002440 if (!isa<ValueDecl>(DRE->getDecl())) {
2441 S.Diag(Arg->getSourceRange().getBegin(),
2442 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002443 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002444 S.Diag(Param->getLocation(), diag::note_template_param_here);
2445 return true;
2446 }
2447
2448 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002449
2450 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002451 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2452 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002453 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002454 S.Diag(Param->getLocation(), diag::note_template_param_here);
2455 return true;
2456 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002457
2458 // Cannot refer to non-static member functions
2459 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002460 if (!Method->isStatic()) {
2461 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002462 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002463 S.Diag(Param->getLocation(), diag::note_template_param_here);
2464 return true;
2465 }
Mike Stump11289f42009-09-09 15:08:12 +00002466
Douglas Gregorccb07762009-02-11 19:52:55 +00002467 // Functions must have external linkage.
2468 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002469 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002470 S.Diag(Arg->getSourceRange().getBegin(),
2471 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002472 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002473 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002474 << true;
2475 return true;
2476 }
2477
2478 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002479 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002480
Douglas Gregorb242683d2010-04-01 18:32:35 +00002481 // If the template parameter has pointer type, the function decays.
2482 if (ParamType->isPointerType() && !AddressTaken)
2483 ArgType = S.Context.getPointerType(Func->getType());
2484 else if (AddressTaken && ParamType->isReferenceType()) {
2485 // If we originally had an address-of operator, but the
2486 // parameter has reference type, complain and (if things look
2487 // like they will work) drop the address-of operator.
2488 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2489 ParamType.getNonReferenceType())) {
2490 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2491 << ParamType;
2492 S.Diag(Param->getLocation(), diag::note_template_param_here);
2493 return true;
2494 }
2495
2496 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2497 << ParamType
2498 << FixItHint::CreateRemoval(AddrOpLoc);
2499 S.Diag(Param->getLocation(), diag::note_template_param_here);
2500
2501 ArgType = Func->getType();
2502 }
2503 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002504 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002505 S.Diag(Arg->getSourceRange().getBegin(),
2506 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002507 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002508 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002509 << true;
2510 return true;
2511 }
2512
Douglas Gregorb242683d2010-04-01 18:32:35 +00002513 // A value of reference type is not an object.
2514 if (Var->getType()->isReferenceType()) {
2515 S.Diag(Arg->getSourceRange().getBegin(),
2516 diag::err_template_arg_reference_var)
2517 << Var->getType() << Arg->getSourceRange();
2518 S.Diag(Param->getLocation(), diag::note_template_param_here);
2519 return true;
2520 }
2521
Douglas Gregorccb07762009-02-11 19:52:55 +00002522 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002523 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002524
2525 // If the template parameter has pointer type, we must have taken
2526 // the address of this object.
2527 if (ParamType->isReferenceType()) {
2528 if (AddressTaken) {
2529 // If we originally had an address-of operator, but the
2530 // parameter has reference type, complain and (if things look
2531 // like they will work) drop the address-of operator.
2532 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2533 ParamType.getNonReferenceType())) {
2534 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2535 << ParamType;
2536 S.Diag(Param->getLocation(), diag::note_template_param_here);
2537 return true;
2538 }
2539
2540 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2541 << ParamType
2542 << FixItHint::CreateRemoval(AddrOpLoc);
2543 S.Diag(Param->getLocation(), diag::note_template_param_here);
2544
2545 ArgType = Var->getType();
2546 }
2547 } else if (!AddressTaken && ParamType->isPointerType()) {
2548 if (Var->getType()->isArrayType()) {
2549 // Array-to-pointer decay.
2550 ArgType = S.Context.getArrayDecayedType(Var->getType());
2551 } else {
2552 // If the template parameter has pointer type but the address of
2553 // this object was not taken, complain and (possibly) recover by
2554 // taking the address of the entity.
2555 ArgType = S.Context.getPointerType(Var->getType());
2556 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2557 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2558 << ParamType;
2559 S.Diag(Param->getLocation(), diag::note_template_param_here);
2560 return true;
2561 }
2562
2563 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2564 << ParamType
2565 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2566
2567 S.Diag(Param->getLocation(), diag::note_template_param_here);
2568 }
2569 }
2570 } else {
2571 // We found something else, but we don't know specifically what it is.
2572 S.Diag(Arg->getSourceRange().getBegin(),
2573 diag::err_template_arg_not_object_or_func)
2574 << Arg->getSourceRange();
2575 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2576 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002577 }
Mike Stump11289f42009-09-09 15:08:12 +00002578
Douglas Gregorb242683d2010-04-01 18:32:35 +00002579 if (ParamType->isPointerType() &&
2580 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2581 S.IsQualificationConversion(ArgType, ParamType)) {
2582 // For pointer-to-object types, qualification conversions are
2583 // permitted.
2584 } else {
2585 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2586 if (!ParamRef->getPointeeType()->isFunctionType()) {
2587 // C++ [temp.arg.nontype]p5b3:
2588 // For a non-type template-parameter of type reference to
2589 // object, no conversions apply. The type referred to by the
2590 // reference may be more cv-qualified than the (otherwise
2591 // identical) type of the template- argument. The
2592 // template-parameter is bound directly to the
2593 // template-argument, which shall be an lvalue.
2594
2595 // FIXME: Other qualifiers?
2596 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2597 unsigned ArgQuals = ArgType.getCVRQualifiers();
2598
2599 if ((ParamQuals | ArgQuals) != ParamQuals) {
2600 S.Diag(Arg->getSourceRange().getBegin(),
2601 diag::err_template_arg_ref_bind_ignores_quals)
2602 << ParamType << Arg->getType()
2603 << Arg->getSourceRange();
2604 S.Diag(Param->getLocation(), diag::note_template_param_here);
2605 return true;
2606 }
2607 }
2608 }
2609
2610 // At this point, the template argument refers to an object or
2611 // function with external linkage. We now need to check whether the
2612 // argument and parameter types are compatible.
2613 if (!S.Context.hasSameUnqualifiedType(ArgType,
2614 ParamType.getNonReferenceType())) {
2615 // We can't perform this conversion or binding.
2616 if (ParamType->isReferenceType())
2617 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2618 << ParamType << Arg->getType() << Arg->getSourceRange();
2619 else
2620 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2621 << Arg->getType() << ParamType << Arg->getSourceRange();
2622 S.Diag(Param->getLocation(), diag::note_template_param_here);
2623 return true;
2624 }
2625 }
2626
2627 // Create the template argument.
2628 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002629 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002630 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002631}
2632
2633/// \brief Checks whether the given template argument is a pointer to
2634/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002635bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2636 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002637 bool Invalid = false;
2638
2639 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002640 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002641 Arg = Cast->getSubExpr();
2642
2643 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002644 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002645 // A template-argument for a non-type, non-template
2646 // template-parameter shall be one of: [...]
2647 //
2648 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002649 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002650
2651 // Ignore (and complain about) any excess parentheses.
2652 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2653 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002654 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002655 diag::err_template_arg_extra_parens)
2656 << Arg->getSourceRange();
2657 Invalid = true;
2658 }
2659
2660 Arg = Parens->getSubExpr();
2661 }
2662
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002663 // A pointer-to-member constant written &Class::member.
2664 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002665 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2666 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2667 if (DRE && !DRE->getQualifier())
2668 DRE = 0;
2669 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002670 }
2671 // A constant of pointer-to-member type.
2672 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2673 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2674 if (VD->getType()->isMemberPointerType()) {
2675 if (isa<NonTypeTemplateParmDecl>(VD) ||
2676 (isa<VarDecl>(VD) &&
2677 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2678 if (Arg->isTypeDependent() || Arg->isValueDependent())
2679 Converted = TemplateArgument(Arg->Retain());
2680 else
2681 Converted = TemplateArgument(VD->getCanonicalDecl());
2682 return Invalid;
2683 }
2684 }
2685 }
2686
2687 DRE = 0;
2688 }
2689
Douglas Gregorccb07762009-02-11 19:52:55 +00002690 if (!DRE)
2691 return Diag(Arg->getSourceRange().getBegin(),
2692 diag::err_template_arg_not_pointer_to_member_form)
2693 << Arg->getSourceRange();
2694
2695 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2696 assert((isa<FieldDecl>(DRE->getDecl()) ||
2697 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2698 "Only non-static member pointers can make it here");
2699
2700 // Okay: this is the address of a non-static member, and therefore
2701 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002702 if (Arg->isTypeDependent() || Arg->isValueDependent())
2703 Converted = TemplateArgument(Arg->Retain());
2704 else
2705 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002706 return Invalid;
2707 }
2708
2709 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002710 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002711 diag::err_template_arg_not_pointer_to_member_form)
2712 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002713 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002714 diag::note_template_arg_refers_here);
2715 return true;
2716}
2717
Douglas Gregord32e0282009-02-09 23:23:08 +00002718/// \brief Check a template argument against its corresponding
2719/// non-type template parameter.
2720///
Douglas Gregor463421d2009-03-03 04:44:36 +00002721/// This routine implements the semantics of C++ [temp.arg.nontype].
2722/// It returns true if an error occurred, and false otherwise. \p
2723/// InstantiatedParamType is the type of the non-type template
2724/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002725///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002726/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002727bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002728 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002729 TemplateArgument &Converted,
2730 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002731 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2732
Douglas Gregor86560402009-02-10 23:36:10 +00002733 // If either the parameter has a dependent type or the argument is
2734 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002735 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2736 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002737 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002738 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002739 }
Douglas Gregor86560402009-02-10 23:36:10 +00002740
2741 // C++ [temp.arg.nontype]p5:
2742 // The following conversions are performed on each expression used
2743 // as a non-type template-argument. If a non-type
2744 // template-argument cannot be converted to the type of the
2745 // corresponding template-parameter then the program is
2746 // ill-formed.
2747 //
2748 // -- for a non-type template-parameter of integral or
2749 // enumeration type, integral promotions (4.5) and integral
2750 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002751 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002752 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00002753 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002754 // C++ [temp.arg.nontype]p1:
2755 // A template-argument for a non-type, non-template
2756 // template-parameter shall be one of:
2757 //
2758 // -- an integral constant-expression of integral or enumeration
2759 // type; or
2760 // -- the name of a non-type template-parameter; or
2761 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002762 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00002763 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002764 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002765 diag::err_template_arg_not_integral_or_enumeral)
2766 << ArgType << Arg->getSourceRange();
2767 Diag(Param->getLocation(), diag::note_template_param_here);
2768 return true;
2769 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002770 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002771 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2772 << ArgType << Arg->getSourceRange();
2773 return true;
2774 }
2775
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002776 // From here on out, all we care about are the unqualified forms
2777 // of the parameter and argument types.
2778 ParamType = ParamType.getUnqualifiedType();
2779 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002780
2781 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002782 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002783 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002784 } else if (CTAK == CTAK_Deduced) {
2785 // C++ [temp.deduct.type]p17:
2786 // If, in the declaration of a function template with a non-type
2787 // template-parameter, the non-type template- parameter is used
2788 // in an expression in the function parameter-list and, if the
2789 // corresponding template-argument is deduced, the
2790 // template-argument type shall match the type of the
2791 // template-parameter exactly, except that a template-argument
2792 // deduced from an array bound may be of any integral type.
2793 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2794 << ArgType << ParamType;
2795 Diag(Param->getLocation(), diag::note_template_param_here);
2796 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002797 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2798 !ParamType->isEnumeralType()) {
2799 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002800 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002801 } else {
2802 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002803 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002804 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002805 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002806 Diag(Param->getLocation(), diag::note_template_param_here);
2807 return true;
2808 }
2809
Douglas Gregor52aba872009-03-14 00:20:21 +00002810 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002811 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002812 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002813
2814 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002815 llvm::APSInt OldValue = Value;
2816
2817 // Coerce the template argument's value to the value it will have
2818 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002819 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002820 if (Value.getBitWidth() != AllowedBits)
2821 Value.extOrTrunc(AllowedBits);
2822 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002823
2824 // Complain if an unsigned parameter received a negative value.
2825 if (IntegerType->isUnsignedIntegerType()
2826 && (OldValue.isSigned() && OldValue.isNegative())) {
2827 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2828 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2829 << Arg->getSourceRange();
2830 Diag(Param->getLocation(), diag::note_template_param_here);
2831 }
2832
2833 // Complain if we overflowed the template parameter's type.
2834 unsigned RequiredBits;
2835 if (IntegerType->isUnsignedIntegerType())
2836 RequiredBits = OldValue.getActiveBits();
2837 else if (OldValue.isUnsigned())
2838 RequiredBits = OldValue.getActiveBits() + 1;
2839 else
2840 RequiredBits = OldValue.getMinSignedBits();
2841 if (RequiredBits > AllowedBits) {
2842 Diag(Arg->getSourceRange().getBegin(),
2843 diag::warn_template_arg_too_large)
2844 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2845 << Arg->getSourceRange();
2846 Diag(Param->getLocation(), diag::note_template_param_here);
2847 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002848 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002849
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002850 // Add the value of this argument to the list of converted
2851 // arguments. We use the bitwidth and signedness of the template
2852 // parameter.
2853 if (Arg->isValueDependent()) {
2854 // The argument is value-dependent. Create a new
2855 // TemplateArgument with the converted expression.
2856 Converted = TemplateArgument(Arg);
2857 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002858 }
2859
John McCall0ad16662009-10-29 08:12:44 +00002860 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002861 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002862 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002863 return false;
2864 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002865
John McCall16df1e52010-03-30 21:47:33 +00002866 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2867
Douglas Gregorb242683d2010-04-01 18:32:35 +00002868 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2869 // from a template argument of type std::nullptr_t to a non-type
2870 // template parameter of type pointer to object, pointer to
2871 // function, or pointer-to-member, respectively.
2872 if (ArgType->isNullPtrType() &&
2873 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2874 Converted = TemplateArgument((NamedDecl *)0);
2875 return false;
2876 }
2877
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002878 // Handle pointer-to-function, reference-to-function, and
2879 // pointer-to-member-function all in (roughly) the same way.
2880 if (// -- For a non-type template-parameter of type pointer to
2881 // function, only the function-to-pointer conversion (4.3) is
2882 // applied. If the template-argument represents a set of
2883 // overloaded functions (or a pointer to such), the matching
2884 // function is selected from the set (13.4).
2885 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002886 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002887 // -- For a non-type template-parameter of type reference to
2888 // function, no conversions apply. If the template-argument
2889 // represents a set of overloaded functions, the matching
2890 // function is selected from the set (13.4).
2891 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002892 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002893 // -- For a non-type template-parameter of type pointer to
2894 // member function, no conversions apply. If the
2895 // template-argument represents a set of overloaded member
2896 // functions, the matching member function is selected from
2897 // the set (13.4).
2898 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002899 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002900 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002901
Douglas Gregor064fdb22010-04-14 23:11:21 +00002902 if (Arg->getType() == Context.OverloadTy) {
2903 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2904 true,
2905 FoundResult)) {
2906 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2907 return true;
2908
2909 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2910 ArgType = Arg->getType();
2911 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002912 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002913 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002914
Douglas Gregorb242683d2010-04-01 18:32:35 +00002915 if (!ParamType->isMemberPointerType())
2916 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2917 ParamType,
2918 Arg, Converted);
2919
2920 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002921 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00002922 } else if (!Context.hasSameUnqualifiedType(ArgType,
2923 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002924 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002925 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002926 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002927 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002928 Diag(Param->getLocation(), diag::note_template_param_here);
2929 return true;
2930 }
Mike Stump11289f42009-09-09 15:08:12 +00002931
Douglas Gregorb242683d2010-04-01 18:32:35 +00002932 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002933 }
2934
Chris Lattner696197c2009-02-20 21:37:53 +00002935 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002936 // -- for a non-type template-parameter of type pointer to
2937 // object, qualification conversions (4.4) and the
2938 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002939 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00002940 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002941 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002942
Douglas Gregorb242683d2010-04-01 18:32:35 +00002943 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2944 ParamType,
2945 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002946 }
Mike Stump11289f42009-09-09 15:08:12 +00002947
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002948 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002949 // -- For a non-type template-parameter of type reference to
2950 // object, no conversions apply. The type referred to by the
2951 // reference may be more cv-qualified than the (otherwise
2952 // identical) type of the template-argument. The
2953 // template-parameter is bound directly to the
2954 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00002955 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002956 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002957
Douglas Gregor064fdb22010-04-14 23:11:21 +00002958 if (Arg->getType() == Context.OverloadTy) {
2959 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2960 ParamRefType->getPointeeType(),
2961 true,
2962 FoundResult)) {
2963 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2964 return true;
2965
2966 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2967 ArgType = Arg->getType();
2968 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002969 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002970 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002971
Douglas Gregorb242683d2010-04-01 18:32:35 +00002972 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2973 ParamType,
2974 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002975 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002976
2977 // -- For a non-type template-parameter of type pointer to data
2978 // member, qualification conversions (4.4) are applied.
2979 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2980
Douglas Gregor1515f762009-02-11 18:22:40 +00002981 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002982 // Types match exactly: nothing more to do here.
2983 } else if (IsQualificationConversion(ArgType, ParamType)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002984 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00002985 } else {
2986 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002987 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002988 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002989 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002990 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002991 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002992 }
2993
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002994 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002995}
2996
2997/// \brief Check a template argument against its corresponding
2998/// template template parameter.
2999///
3000/// This routine implements the semantics of C++ [temp.arg.template].
3001/// It returns true if an error occurred, and false otherwise.
3002bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003003 const TemplateArgumentLoc &Arg) {
3004 TemplateName Name = Arg.getArgument().getAsTemplate();
3005 TemplateDecl *Template = Name.getAsTemplateDecl();
3006 if (!Template) {
3007 // Any dependent template name is fine.
3008 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3009 return false;
3010 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003011
3012 // C++ [temp.arg.template]p1:
3013 // A template-argument for a template template-parameter shall be
3014 // the name of a class template, expressed as id-expression. Only
3015 // primary class templates are considered when matching the
3016 // template template argument with the corresponding parameter;
3017 // partial specializations are not considered even if their
3018 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003019 //
3020 // Note that we also allow template template parameters here, which
3021 // will happen when we are dealing with, e.g., class template
3022 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003023 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003024 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003025 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003026 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003027 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003028 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003029 << Template;
3030 }
3031
3032 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3033 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003034 true,
3035 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003036 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003037}
3038
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003039/// \brief Given a non-type template argument that refers to a
3040/// declaration and the type of its corresponding non-type template
3041/// parameter, produce an expression that properly refers to that
3042/// declaration.
John McCalldadc5752010-08-24 06:29:42 +00003043ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003044Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3045 QualType ParamType,
3046 SourceLocation Loc) {
3047 assert(Arg.getKind() == TemplateArgument::Declaration &&
3048 "Only declaration template arguments permitted here");
3049 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3050
3051 if (VD->getDeclContext()->isRecord() &&
3052 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3053 // If the value is a class member, we might have a pointer-to-member.
3054 // Determine whether the non-type template template parameter is of
3055 // pointer-to-member type. If so, we need to build an appropriate
3056 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3057 // would refer to the member itself.
3058 if (ParamType->isMemberPointerType()) {
3059 QualType ClassType
3060 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3061 NestedNameSpecifier *Qualifier
John McCallb268a282010-08-23 23:25:46 +00003062 = NestedNameSpecifier::Create(Context, 0, false,
3063 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003064 CXXScopeSpec SS;
3065 SS.setScopeRep(Qualifier);
John McCalldadc5752010-08-24 06:29:42 +00003066 ExprResult RefExpr = BuildDeclRefExpr(VD,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003067 VD->getType().getNonReferenceType(),
3068 Loc,
3069 &SS);
3070 if (RefExpr.isInvalid())
3071 return ExprError();
3072
John McCallb268a282010-08-23 23:25:46 +00003073 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, RefExpr.get());
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003074
3075 // We might need to perform a trailing qualification conversion, since
3076 // the element type on the parameter could be more qualified than the
3077 // element type in the expression we constructed.
3078 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3079 ParamType.getUnqualifiedType())) {
3080 Expr *RefE = RefExpr.takeAs<Expr>();
3081 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3082 CastExpr::CK_NoOp);
3083 RefExpr = Owned(RefE);
3084 }
3085
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003086 assert(!RefExpr.isInvalid() &&
3087 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003088 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003089 return move(RefExpr);
3090 }
3091 }
3092
3093 QualType T = VD->getType().getNonReferenceType();
3094 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003095 // When the non-type template parameter is a pointer, take the
3096 // address of the declaration.
John McCalldadc5752010-08-24 06:29:42 +00003097 ExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003098 if (RefExpr.isInvalid())
3099 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003100
3101 if (T->isFunctionType() || T->isArrayType()) {
3102 // Decay functions and arrays.
3103 Expr *RefE = (Expr *)RefExpr.get();
3104 DefaultFunctionArrayConversion(RefE);
3105 if (RefE != RefExpr.get()) {
3106 RefExpr.release();
3107 RefExpr = Owned(RefE);
3108 }
3109
3110 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003111 }
3112
Douglas Gregorb242683d2010-04-01 18:32:35 +00003113 // Take the address of everything else
John McCallb268a282010-08-23 23:25:46 +00003114 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003115 }
3116
3117 // If the non-type template parameter has reference type, qualify the
3118 // resulting declaration reference with the extra qualifiers on the
3119 // type that the reference refers to.
3120 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3121 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3122
3123 return BuildDeclRefExpr(VD, T, Loc);
3124}
3125
3126/// \brief Construct a new expression that refers to the given
3127/// integral template argument with the given source-location
3128/// information.
3129///
3130/// This routine takes care of the mapping from an integral template
3131/// argument (which may have any integral type) to the appropriate
3132/// literal value.
John McCalldadc5752010-08-24 06:29:42 +00003133ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003134Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3135 SourceLocation Loc) {
3136 assert(Arg.getKind() == TemplateArgument::Integral &&
3137 "Operation is only value for integral template arguments");
3138 QualType T = Arg.getIntegralType();
3139 if (T->isCharType() || T->isWideCharType())
3140 return Owned(new (Context) CharacterLiteral(
3141 Arg.getAsIntegral()->getZExtValue(),
3142 T->isWideCharType(),
3143 T,
3144 Loc));
3145 if (T->isBooleanType())
3146 return Owned(new (Context) CXXBoolLiteralExpr(
3147 Arg.getAsIntegral()->getBoolValue(),
3148 T,
3149 Loc));
3150
3151 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3152}
3153
3154
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003155/// \brief Determine whether the given template parameter lists are
3156/// equivalent.
3157///
Mike Stump11289f42009-09-09 15:08:12 +00003158/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003159/// source code as part of a new template declaration.
3160///
3161/// \param Old The old template parameter list, typically found via
3162/// name lookup of the template declared with this template parameter
3163/// list.
3164///
3165/// \param Complain If true, this routine will produce a diagnostic if
3166/// the template parameter lists are not equivalent.
3167///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003168/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003169///
3170/// \param TemplateArgLoc If this source location is valid, then we
3171/// are actually checking the template parameter list of a template
3172/// argument (New) against the template parameter list of its
3173/// corresponding template template parameter (Old). We produce
3174/// slightly different diagnostics in this scenario.
3175///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003176/// \returns True if the template parameter lists are equal, false
3177/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003178bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003179Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3180 TemplateParameterList *Old,
3181 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003182 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003183 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003184 if (Old->size() != New->size()) {
3185 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003186 unsigned NextDiag = diag::err_template_param_list_different_arity;
3187 if (TemplateArgLoc.isValid()) {
3188 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3189 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003190 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003191 Diag(New->getTemplateLoc(), NextDiag)
3192 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003193 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003194 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003195 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003196 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003197 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3198 }
3199
3200 return false;
3201 }
3202
3203 for (TemplateParameterList::iterator OldParm = Old->begin(),
3204 OldParmEnd = Old->end(), NewParm = New->begin();
3205 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3206 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003207 if (Complain) {
3208 unsigned NextDiag = diag::err_template_param_different_kind;
3209 if (TemplateArgLoc.isValid()) {
3210 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3211 NextDiag = diag::note_template_param_different_kind;
3212 }
3213 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003214 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003215 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003216 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003217 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003218 return false;
3219 }
3220
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003221 if (TemplateTypeParmDecl *OldTTP
3222 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3223 // Template type parameters are equivalent if either both are template
3224 // type parameter packs or neither are (since we know we're at the same
3225 // index).
3226 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3227 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3228 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3229 // allow one to match a template parameter pack in the template
3230 // parameter list of a template template parameter to one or more
3231 // template parameters in the template parameter list of the
3232 // corresponding template template argument.
3233 if (Complain) {
3234 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3235 if (TemplateArgLoc.isValid()) {
3236 Diag(TemplateArgLoc,
3237 diag::err_template_arg_template_params_mismatch);
3238 NextDiag = diag::note_template_parameter_pack_non_pack;
3239 }
3240 Diag(NewTTP->getLocation(), NextDiag)
3241 << 0 << NewTTP->isParameterPack();
3242 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3243 << 0 << OldTTP->isParameterPack();
3244 }
3245 return false;
3246 }
Mike Stump11289f42009-09-09 15:08:12 +00003247 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003248 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3249 // The types of non-type template parameters must agree.
3250 NonTypeTemplateParmDecl *NewNTTP
3251 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003252
3253 // If we are matching a template template argument to a template
3254 // template parameter and one of the non-type template parameter types
3255 // is dependent, then we must wait until template instantiation time
3256 // to actually compare the arguments.
3257 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3258 (OldNTTP->getType()->isDependentType() ||
3259 NewNTTP->getType()->isDependentType()))
3260 continue;
3261
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003262 if (Context.getCanonicalType(OldNTTP->getType()) !=
3263 Context.getCanonicalType(NewNTTP->getType())) {
3264 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003265 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3266 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003267 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003268 diag::err_template_arg_template_params_mismatch);
3269 NextDiag = diag::note_template_nontype_parm_different_type;
3270 }
3271 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003272 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003273 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003274 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003275 diag::note_template_nontype_parm_prev_declaration)
3276 << OldNTTP->getType();
3277 }
3278 return false;
3279 }
3280 } else {
3281 // The template parameter lists of template template
3282 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003283 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003284 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003285 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003286 = cast<TemplateTemplateParmDecl>(*OldParm);
3287 TemplateTemplateParmDecl *NewTTP
3288 = cast<TemplateTemplateParmDecl>(*NewParm);
3289 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3290 OldTTP->getTemplateParameters(),
3291 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003292 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003293 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003294 return false;
3295 }
3296 }
3297
3298 return true;
3299}
3300
3301/// \brief Check whether a template can be declared within this scope.
3302///
3303/// If the template declaration is valid in this scope, returns
3304/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003305bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003306Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003307 // Find the nearest enclosing declaration scope.
3308 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3309 (S->getFlags() & Scope::TemplateParamScope) != 0)
3310 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003311
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003312 // C++ [temp]p2:
3313 // A template-declaration can appear only as a namespace scope or
3314 // class scope declaration.
3315 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003316 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3317 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003318 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003319 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003320
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003321 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003322 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003323
3324 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3325 return false;
3326
Mike Stump11289f42009-09-09 15:08:12 +00003327 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003328 diag::err_template_outside_namespace_or_class_scope)
3329 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003330}
Douglas Gregor67a65642009-02-17 23:15:12 +00003331
Douglas Gregor54888652009-10-07 00:13:32 +00003332/// \brief Determine what kind of template specialization the given declaration
3333/// is.
3334static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3335 if (!D)
3336 return TSK_Undeclared;
3337
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003338 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3339 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003340 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3341 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003342 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3343 return Var->getTemplateSpecializationKind();
3344
Douglas Gregor54888652009-10-07 00:13:32 +00003345 return TSK_Undeclared;
3346}
3347
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003348/// \brief Check whether a specialization is well-formed in the current
3349/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003350///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003351/// This routine determines whether a template specialization can be declared
3352/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003353///
3354/// \param S the semantic analysis object for which this check is being
3355/// performed.
3356///
3357/// \param Specialized the entity being specialized or instantiated, which
3358/// may be a kind of template (class template, function template, etc.) or
3359/// a member of a class template (member function, static data member,
3360/// member class).
3361///
3362/// \param PrevDecl the previous declaration of this entity, if any.
3363///
3364/// \param Loc the location of the explicit specialization or instantiation of
3365/// this entity.
3366///
3367/// \param IsPartialSpecialization whether this is a partial specialization of
3368/// a class template.
3369///
Douglas Gregor54888652009-10-07 00:13:32 +00003370/// \returns true if there was an error that we cannot recover from, false
3371/// otherwise.
3372static bool CheckTemplateSpecializationScope(Sema &S,
3373 NamedDecl *Specialized,
3374 NamedDecl *PrevDecl,
3375 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003376 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003377 // Keep these "kind" numbers in sync with the %select statements in the
3378 // various diagnostics emitted by this routine.
3379 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003380 bool isTemplateSpecialization = false;
3381 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003382 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003383 isTemplateSpecialization = true;
3384 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003385 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003386 isTemplateSpecialization = true;
3387 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003388 EntityKind = 3;
3389 else if (isa<VarDecl>(Specialized))
3390 EntityKind = 4;
3391 else if (isa<RecordDecl>(Specialized))
3392 EntityKind = 5;
3393 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003394 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3395 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003396 return true;
3397 }
3398
Douglas Gregorf47b9112009-02-25 22:02:03 +00003399 // C++ [temp.expl.spec]p2:
3400 // An explicit specialization shall be declared in the namespace
3401 // of which the template is a member, or, for member templates, in
3402 // the namespace of which the enclosing class or enclosing class
3403 // template is a member. An explicit specialization of a member
3404 // function, member class or static data member of a class
3405 // template shall be declared in the namespace of which the class
3406 // template is a member. Such a declaration may also be a
3407 // definition. If the declaration is not a definition, the
3408 // specialization may be defined later in the name- space in which
3409 // the explicit specialization was declared, or in a namespace
3410 // that encloses the one in which the explicit specialization was
3411 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003412 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3413 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003414 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003415 return true;
3416 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003417
Douglas Gregor40fb7442009-10-07 17:30:37 +00003418 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3419 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003420 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003421 return true;
3422 }
3423
Douglas Gregore4b05162009-10-07 17:21:34 +00003424 // C++ [temp.class.spec]p6:
3425 // A class template partial specialization may be declared or redeclared
3426 // in any namespace scope in which its definition may be defined (14.5.1
3427 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003428 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003429 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003430 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003431 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003432 if ((!PrevDecl ||
3433 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3434 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3435 // There is no prior declaration of this entity, so this
3436 // specialization must be in the same context as the template
3437 // itself.
3438 if (!DC->Equals(SpecializedContext)) {
3439 if (isa<TranslationUnitDecl>(SpecializedContext))
3440 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3441 << EntityKind << Specialized;
3442 else if (isa<NamespaceDecl>(SpecializedContext))
3443 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3444 << EntityKind << Specialized
3445 << cast<NamedDecl>(SpecializedContext);
3446
3447 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3448 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003449 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003450 }
Douglas Gregor54888652009-10-07 00:13:32 +00003451
3452 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003453 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003454 // Note that HandleDeclarator() performs this check for explicit
3455 // specializations of function templates, static data members, and member
3456 // functions, so we skip the check here for those kinds of entities.
3457 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003458 // Should we refactor that check, so that it occurs later?
3459 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003460 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3461 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003462 if (isa<TranslationUnitDecl>(SpecializedContext))
3463 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3464 << EntityKind << Specialized;
3465 else if (isa<NamespaceDecl>(SpecializedContext))
3466 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3467 << EntityKind << Specialized
3468 << cast<NamedDecl>(SpecializedContext);
3469
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003470 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003471 }
Douglas Gregor54888652009-10-07 00:13:32 +00003472
3473 // FIXME: check for specialization-after-instantiation errors and such.
3474
Douglas Gregorf47b9112009-02-25 22:02:03 +00003475 return false;
3476}
Douglas Gregor54888652009-10-07 00:13:32 +00003477
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003478/// \brief Check the non-type template arguments of a class template
3479/// partial specialization according to C++ [temp.class.spec]p9.
3480///
Douglas Gregor09a30232009-06-12 22:08:06 +00003481/// \param TemplateParams the template parameters of the primary class
3482/// template.
3483///
3484/// \param TemplateArg the template arguments of the class template
3485/// partial specialization.
3486///
3487/// \param MirrorsPrimaryTemplate will be set true if the class
3488/// template partial specialization arguments are identical to the
3489/// implicit template arguments of the primary template. This is not
3490/// necessarily an error (C++0x), and it is left to the caller to diagnose
3491/// this condition when it is an error.
3492///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003493/// \returns true if there was an error, false otherwise.
3494bool Sema::CheckClassTemplatePartialSpecializationArgs(
3495 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003496 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003497 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003498 // FIXME: the interface to this function will have to change to
3499 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003500 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003501
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003502 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003503
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003504 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003505 // Determine whether the template argument list of the partial
3506 // specialization is identical to the implicit argument list of
3507 // the primary template. The caller may need to diagnostic this as
3508 // an error per C++ [temp.class.spec]p9b3.
3509 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003510 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003511 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3512 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003513 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003514 MirrorsPrimaryTemplate = false;
3515 } else if (TemplateTemplateParmDecl *TTP
3516 = dyn_cast<TemplateTemplateParmDecl>(
3517 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003518 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003519 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003520 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003521 if (!ArgDecl ||
3522 ArgDecl->getIndex() != TTP->getIndex() ||
3523 ArgDecl->getDepth() != TTP->getDepth())
3524 MirrorsPrimaryTemplate = false;
3525 }
3526 }
3527
Mike Stump11289f42009-09-09 15:08:12 +00003528 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003529 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003530 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003531 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003532 }
3533
Anders Carlsson40c1d492009-06-13 18:20:51 +00003534 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003535 if (!ArgExpr) {
3536 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003537 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003538 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003539
3540 // C++ [temp.class.spec]p8:
3541 // A non-type argument is non-specialized if it is the name of a
3542 // non-type parameter. All other non-type arguments are
3543 // specialized.
3544 //
3545 // Below, we check the two conditions that only apply to
3546 // specialized non-type arguments, so skip any non-specialized
3547 // arguments.
3548 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003549 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003550 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003551 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003552 (Param->getIndex() != NTTP->getIndex() ||
3553 Param->getDepth() != NTTP->getDepth()))
3554 MirrorsPrimaryTemplate = false;
3555
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003556 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003557 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003558
3559 // C++ [temp.class.spec]p9:
3560 // Within the argument list of a class template partial
3561 // specialization, the following restrictions apply:
3562 // -- A partially specialized non-type argument expression
3563 // shall not involve a template parameter of the partial
3564 // specialization except when the argument expression is a
3565 // simple identifier.
3566 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003567 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003568 diag::err_dependent_non_type_arg_in_partial_spec)
3569 << ArgExpr->getSourceRange();
3570 return true;
3571 }
3572
3573 // -- The type of a template parameter corresponding to a
3574 // specialized non-type argument shall not be dependent on a
3575 // parameter of the specialization.
3576 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003577 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003578 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3579 << Param->getType()
3580 << ArgExpr->getSourceRange();
3581 Diag(Param->getLocation(), diag::note_template_param_here);
3582 return true;
3583 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003584
3585 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003586 }
3587
3588 return false;
3589}
3590
Douglas Gregorc854c662010-02-26 06:03:23 +00003591/// \brief Retrieve the previous declaration of the given declaration.
3592static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3593 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3594 return VD->getPreviousDeclaration();
3595 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3596 return FD->getPreviousDeclaration();
3597 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3598 return TD->getPreviousDeclaration();
3599 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3600 return TD->getPreviousDeclaration();
3601 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3602 return FTD->getPreviousDeclaration();
3603 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3604 return CTD->getPreviousDeclaration();
3605 return 0;
3606}
3607
John McCall48871652010-08-21 09:40:31 +00003608DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003609Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3610 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003611 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003612 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003613 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003614 SourceLocation TemplateNameLoc,
3615 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003616 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003617 SourceLocation RAngleLoc,
3618 AttributeList *Attr,
3619 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003620 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003621
Douglas Gregor67a65642009-02-17 23:15:12 +00003622 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003623 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003624 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003625 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3626
3627 if (!ClassTemplate) {
3628 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3629 << (Name.getAsTemplateDecl() &&
3630 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3631 return true;
3632 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003633
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003634 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003635 bool isPartialSpecialization = false;
3636
Douglas Gregorf47b9112009-02-25 22:02:03 +00003637 // Check the validity of the template headers that introduce this
3638 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003639 // FIXME: We probably shouldn't complain about these headers for
3640 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003641 bool Invalid = false;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003642 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003643 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3644 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003645 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003646 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003647 isExplicitSpecialization,
3648 Invalid);
3649 if (Invalid)
3650 return true;
3651
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003652 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3653 if (TemplateParams)
3654 --NumMatchedTemplateParamLists;
3655
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003656 if (TemplateParams && TemplateParams->size() > 0) {
3657 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003658
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003659 // C++ [temp.class.spec]p10:
3660 // The template parameter list of a specialization shall not
3661 // contain default template argument values.
3662 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3663 Decl *Param = TemplateParams->getParam(I);
3664 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3665 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003666 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003667 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003668 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003669 }
3670 } else if (NonTypeTemplateParmDecl *NTTP
3671 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3672 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003673 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003674 diag::err_default_arg_in_partial_spec)
3675 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003676 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003677 }
3678 } else {
3679 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003680 if (TTP->hasDefaultArgument()) {
3681 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003682 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003683 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003684 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003685 }
3686 }
3687 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003688 } else if (TemplateParams) {
3689 if (TUK == TUK_Friend)
3690 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003691 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003692 SourceRange(TemplateParams->getTemplateLoc(),
3693 TemplateParams->getRAngleLoc()))
3694 << SourceRange(LAngleLoc, RAngleLoc);
3695 else
3696 isExplicitSpecialization = true;
3697 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003698 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003699 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003700 isExplicitSpecialization = true;
3701 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003702
Douglas Gregor67a65642009-02-17 23:15:12 +00003703 // Check that the specialization uses the same tag kind as the
3704 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003705 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3706 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003707 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003708 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003709 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003710 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003711 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003712 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003713 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003714 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003715 diag::note_previous_use);
3716 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3717 }
3718
Douglas Gregorc40290e2009-03-09 23:48:35 +00003719 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003720 TemplateArgumentListInfo TemplateArgs;
3721 TemplateArgs.setLAngleLoc(LAngleLoc);
3722 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003723 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003724
Douglas Gregor67a65642009-02-17 23:15:12 +00003725 // Check that the template argument list is well-formed for this
3726 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003727 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3728 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003729 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3730 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003731 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003732
Mike Stump11289f42009-09-09 15:08:12 +00003733 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003734 ClassTemplate->getTemplateParameters()->size()) &&
3735 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003736
Douglas Gregor2373c592009-05-31 09:31:02 +00003737 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003738 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00003739 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003740 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003741 if (CheckClassTemplatePartialSpecializationArgs(
3742 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003743 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003744 return true;
3745
Douglas Gregor09a30232009-06-12 22:08:06 +00003746 if (MirrorsPrimaryTemplate) {
3747 // C++ [temp.class.spec]p9b3:
3748 //
Mike Stump11289f42009-09-09 15:08:12 +00003749 // -- The argument list of the specialization shall not be identical
3750 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003751 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003752 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003753 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003754 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003755 ClassTemplate->getIdentifier(),
3756 TemplateNameLoc,
3757 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003758 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003759 AS_none);
3760 }
3761
Douglas Gregor2208a292009-09-26 20:57:03 +00003762 // FIXME: Diagnose friend partial specializations
3763
Douglas Gregor92354b62010-02-09 00:37:32 +00003764 if (!Name.isDependent() &&
3765 !TemplateSpecializationType::anyDependentTemplateArguments(
3766 TemplateArgs.getArgumentArray(),
3767 TemplateArgs.size())) {
3768 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3769 << ClassTemplate->getDeclName();
3770 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00003771 }
3772 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003773
Douglas Gregor67a65642009-02-17 23:15:12 +00003774 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003775 ClassTemplateSpecializationDecl *PrevDecl = 0;
3776
3777 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003778 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00003779 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003780 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
3781 Converted.flatSize(),
3782 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003783 else
3784 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003785 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
3786 Converted.flatSize(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003787
3788 ClassTemplateSpecializationDecl *Specialization = 0;
3789
Douglas Gregorf47b9112009-02-25 22:02:03 +00003790 // Check whether we can declare a class template specialization in
3791 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003792 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003793 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003794 TemplateNameLoc,
3795 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003796 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003797
Douglas Gregor15301382009-07-30 17:40:51 +00003798 // The canonical type
3799 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003800 if (PrevDecl &&
3801 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003802 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003803 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003804 // arguments was referenced but not declared, or we're only
3805 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003806 // declaration node as our own, updating its source location to
3807 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003808 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003809 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003810 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003811 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003812 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003813 // Build the canonical type that describes the converted template
3814 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003815 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3816 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003817 Converted.getFlatArguments(),
3818 Converted.flatSize());
3819
Douglas Gregor2373c592009-05-31 09:31:02 +00003820 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003821 ClassTemplatePartialSpecializationDecl *PrevPartial
3822 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00003823 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003824 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump11289f42009-09-09 15:08:12 +00003825 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00003826 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00003827 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003828 TemplateNameLoc,
3829 TemplateParams,
3830 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003831 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003832 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003833 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00003834 PrevPartial,
3835 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00003836 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003837 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003838 Partial->setTemplateParameterListsInfo(Context,
3839 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003840 (TemplateParameterList**) TemplateParameterLists.release());
3841 }
Douglas Gregor2373c592009-05-31 09:31:02 +00003842
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003843 if (!PrevPartial)
3844 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003845 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003846
Douglas Gregor21610382009-10-29 00:04:11 +00003847 // If we are providing an explicit specialization of a member class
3848 // template specialization, make a note of that.
3849 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3850 PrevPartial->setMemberSpecialization();
3851
Douglas Gregor91772d12009-06-13 00:26:55 +00003852 // Check that all of the template parameters of the class template
3853 // partial specialization are deducible from the template
3854 // arguments. If not, this class template partial specialization
3855 // will never be used.
3856 llvm::SmallVector<bool, 8> DeducibleParams;
3857 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003858 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003859 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003860 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003861 unsigned NumNonDeducible = 0;
3862 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3863 if (!DeducibleParams[I])
3864 ++NumNonDeducible;
3865
3866 if (NumNonDeducible) {
3867 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3868 << (NumNonDeducible > 1)
3869 << SourceRange(TemplateNameLoc, RAngleLoc);
3870 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3871 if (!DeducibleParams[I]) {
3872 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3873 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003874 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003875 diag::note_partial_spec_unused_parameter)
3876 << Param->getDeclName();
3877 else
Mike Stump11289f42009-09-09 15:08:12 +00003878 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003879 diag::note_partial_spec_unused_parameter)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003880 << "<anonymous>";
Douglas Gregor91772d12009-06-13 00:26:55 +00003881 }
3882 }
3883 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003884 } else {
3885 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003886 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003887 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00003888 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00003889 ClassTemplate->getDeclContext(),
3890 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003891 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003892 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003893 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003894 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003895 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003896 Specialization->setTemplateParameterListsInfo(Context,
3897 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003898 (TemplateParameterList**) TemplateParameterLists.release());
3899 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003900
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003901 if (!PrevDecl)
3902 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00003903
3904 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003905 }
3906
Douglas Gregor06db9f52009-10-12 20:18:28 +00003907 // C++ [temp.expl.spec]p6:
3908 // If a template, a member template or the member of a class template is
3909 // explicitly specialized then that specialization shall be declared
3910 // before the first use of that specialization that would cause an implicit
3911 // instantiation to take place, in every translation unit in which such a
3912 // use occurs; no diagnostic is required.
3913 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003914 bool Okay = false;
3915 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3916 // Is there any previous explicit specialization declaration?
3917 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3918 Okay = true;
3919 break;
3920 }
3921 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003922
Douglas Gregorc854c662010-02-26 06:03:23 +00003923 if (!Okay) {
3924 SourceRange Range(TemplateNameLoc, RAngleLoc);
3925 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3926 << Context.getTypeDeclType(Specialization) << Range;
3927
3928 Diag(PrevDecl->getPointOfInstantiation(),
3929 diag::note_instantiation_required_here)
3930 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003931 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003932 return true;
3933 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003934 }
3935
Douglas Gregor2208a292009-09-26 20:57:03 +00003936 // If this is not a friend, note that this is an explicit specialization.
3937 if (TUK != TUK_Friend)
3938 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003939
3940 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003941 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003942 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003943 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003944 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003945 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003946 Diag(Def->getLocation(), diag::note_previous_definition);
3947 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003948 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003949 }
3950 }
3951
Douglas Gregord56a91e2009-02-26 22:19:44 +00003952 // Build the fully-sugared type for this class template
3953 // specialization as the user wrote in the specialization
3954 // itself. This means that we'll pretty-print the type retrieved
3955 // from the specialization's declaration the way that the user
3956 // actually wrote the specialization, rather than formatting the
3957 // name based on the "canonical" representation used to store the
3958 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003959 TypeSourceInfo *WrittenTy
3960 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3961 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00003962 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003963 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregord890b732010-07-06 18:33:12 +00003964 if (TemplateParams)
3965 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnara8075c852010-06-12 07:44:57 +00003966 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00003967 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003968
Douglas Gregor1e249f82009-02-25 22:18:32 +00003969 // C++ [temp.expl.spec]p9:
3970 // A template explicit specialization is in the scope of the
3971 // namespace in which the template was defined.
3972 //
3973 // We actually implement this paragraph where we set the semantic
3974 // context (in the creation of the ClassTemplateSpecializationDecl),
3975 // but we also maintain the lexical context where the actual
3976 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003977 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003978
Douglas Gregor67a65642009-02-17 23:15:12 +00003979 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003980 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003981 Specialization->startDefinition();
3982
Douglas Gregor2208a292009-09-26 20:57:03 +00003983 if (TUK == TUK_Friend) {
3984 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3985 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00003986 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00003987 /*FIXME:*/KWLoc);
3988 Friend->setAccess(AS_public);
3989 CurContext->addDecl(Friend);
3990 } else {
3991 // Add the specialization into its lexical context, so that it can
3992 // be seen when iterating through the list of declarations in that
3993 // context. However, specializations are not found by name lookup.
3994 CurContext->addDecl(Specialization);
3995 }
John McCall48871652010-08-21 09:40:31 +00003996 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00003997}
Douglas Gregor333489b2009-03-27 23:10:48 +00003998
John McCall48871652010-08-21 09:40:31 +00003999Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004000 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004001 Declarator &D) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004002 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4003}
4004
John McCall48871652010-08-21 09:40:31 +00004005Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004006 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004007 Declarator &D) {
Douglas Gregor17a7c122009-06-24 00:54:41 +00004008 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4009 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4010 "Not a function declarator!");
4011 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004012
Douglas Gregor17a7c122009-06-24 00:54:41 +00004013 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004014 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004015 }
Mike Stump11289f42009-09-09 15:08:12 +00004016
Douglas Gregor17a7c122009-06-24 00:54:41 +00004017 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004018
John McCall48871652010-08-21 09:40:31 +00004019 Decl *DP = HandleDeclarator(ParentScope, D,
4020 move(TemplateParameterLists),
4021 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004022 if (FunctionTemplateDecl *FunctionTemplate
John McCall48871652010-08-21 09:40:31 +00004023 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump11289f42009-09-09 15:08:12 +00004024 return ActOnStartOfFunctionDef(FnBodyScope,
John McCall48871652010-08-21 09:40:31 +00004025 FunctionTemplate->getTemplatedDecl());
4026 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4027 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4028 return 0;
Douglas Gregor17a7c122009-06-24 00:54:41 +00004029}
4030
John McCall4f7ced62010-02-11 01:33:53 +00004031/// \brief Strips various properties off an implicit instantiation
4032/// that has just been explicitly specialized.
4033static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004034 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00004035
4036 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4037 FD->setInlineSpecified(false);
4038 }
4039}
4040
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004041/// \brief Diagnose cases where we have an explicit template specialization
4042/// before/after an explicit template instantiation, producing diagnostics
4043/// for those cases where they are required and determining whether the
4044/// new specialization/instantiation will have any effect.
4045///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004046/// \param NewLoc the location of the new explicit specialization or
4047/// instantiation.
4048///
4049/// \param NewTSK the kind of the new explicit specialization or instantiation.
4050///
4051/// \param PrevDecl the previous declaration of the entity.
4052///
4053/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4054///
4055/// \param PrevPointOfInstantiation if valid, indicates where the previus
4056/// declaration was instantiated (either implicitly or explicitly).
4057///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004058/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004059/// specialization or instantiation has no effect and should be ignored.
4060///
4061/// \returns true if there was an error that should prevent the introduction of
4062/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004063bool
4064Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4065 TemplateSpecializationKind NewTSK,
4066 NamedDecl *PrevDecl,
4067 TemplateSpecializationKind PrevTSK,
4068 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004069 bool &HasNoEffect) {
4070 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004071
4072 switch (NewTSK) {
4073 case TSK_Undeclared:
4074 case TSK_ImplicitInstantiation:
4075 assert(false && "Don't check implicit instantiations here");
4076 return false;
4077
4078 case TSK_ExplicitSpecialization:
4079 switch (PrevTSK) {
4080 case TSK_Undeclared:
4081 case TSK_ExplicitSpecialization:
4082 // Okay, we're just specializing something that is either already
4083 // explicitly specialized or has merely been mentioned without any
4084 // instantiation.
4085 return false;
4086
4087 case TSK_ImplicitInstantiation:
4088 if (PrevPointOfInstantiation.isInvalid()) {
4089 // The declaration itself has not actually been instantiated, so it is
4090 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004091 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004092 return false;
4093 }
4094 // Fall through
4095
4096 case TSK_ExplicitInstantiationDeclaration:
4097 case TSK_ExplicitInstantiationDefinition:
4098 assert((PrevTSK == TSK_ImplicitInstantiation ||
4099 PrevPointOfInstantiation.isValid()) &&
4100 "Explicit instantiation without point of instantiation?");
4101
4102 // C++ [temp.expl.spec]p6:
4103 // If a template, a member template or the member of a class template
4104 // is explicitly specialized then that specialization shall be declared
4105 // before the first use of that specialization that would cause an
4106 // implicit instantiation to take place, in every translation unit in
4107 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004108 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4109 // Is there any previous explicit specialization declaration?
4110 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4111 return false;
4112 }
4113
Douglas Gregor1d957a32009-10-27 18:42:08 +00004114 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004115 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004116 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004117 << (PrevTSK != TSK_ImplicitInstantiation);
4118
4119 return true;
4120 }
4121 break;
4122
4123 case TSK_ExplicitInstantiationDeclaration:
4124 switch (PrevTSK) {
4125 case TSK_ExplicitInstantiationDeclaration:
4126 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004127 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004128 return false;
4129
4130 case TSK_Undeclared:
4131 case TSK_ImplicitInstantiation:
4132 // We're explicitly instantiating something that may have already been
4133 // implicitly instantiated; that's fine.
4134 return false;
4135
4136 case TSK_ExplicitSpecialization:
4137 // C++0x [temp.explicit]p4:
4138 // For a given set of template parameters, if an explicit instantiation
4139 // of a template appears after a declaration of an explicit
4140 // specialization for that template, the explicit instantiation has no
4141 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004142 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004143 return false;
4144
4145 case TSK_ExplicitInstantiationDefinition:
4146 // C++0x [temp.explicit]p10:
4147 // If an entity is the subject of both an explicit instantiation
4148 // declaration and an explicit instantiation definition in the same
4149 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004150 Diag(NewLoc,
4151 diag::err_explicit_instantiation_declaration_after_definition);
4152 Diag(PrevPointOfInstantiation,
4153 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004154 assert(PrevPointOfInstantiation.isValid() &&
4155 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004156 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004157 return false;
4158 }
4159 break;
4160
4161 case TSK_ExplicitInstantiationDefinition:
4162 switch (PrevTSK) {
4163 case TSK_Undeclared:
4164 case TSK_ImplicitInstantiation:
4165 // We're explicitly instantiating something that may have already been
4166 // implicitly instantiated; that's fine.
4167 return false;
4168
4169 case TSK_ExplicitSpecialization:
4170 // C++ DR 259, C++0x [temp.explicit]p4:
4171 // For a given set of template parameters, if an explicit
4172 // instantiation of a template appears after a declaration of
4173 // an explicit specialization for that template, the explicit
4174 // instantiation has no effect.
4175 //
4176 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004177 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004178 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004179 if (!getLangOptions().CPlusPlus0x) {
4180 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004181 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004182 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004183 diag::note_previous_template_specialization);
4184 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004185 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004186 return false;
4187
4188 case TSK_ExplicitInstantiationDeclaration:
4189 // We're explicity instantiating a definition for something for which we
4190 // were previously asked to suppress instantiations. That's fine.
4191 return false;
4192
4193 case TSK_ExplicitInstantiationDefinition:
4194 // C++0x [temp.spec]p5:
4195 // For a given template and a given set of template-arguments,
4196 // - an explicit instantiation definition shall appear at most once
4197 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004198 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004199 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004200 Diag(PrevPointOfInstantiation,
4201 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004202 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004203 return false;
4204 }
4205 break;
4206 }
4207
4208 assert(false && "Missing specialization/instantiation case?");
4209
4210 return false;
4211}
4212
John McCallb9c78482010-04-08 09:05:18 +00004213/// \brief Perform semantic analysis for the given dependent function
4214/// template specialization. The only possible way to get a dependent
4215/// function template specialization is with a friend declaration,
4216/// like so:
4217///
4218/// template <class T> void foo(T);
4219/// template <class T> class A {
4220/// friend void foo<>(T);
4221/// };
4222///
4223/// There really isn't any useful analysis we can do here, so we
4224/// just store the information.
4225bool
4226Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4227 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4228 LookupResult &Previous) {
4229 // Remove anything from Previous that isn't a function template in
4230 // the correct context.
4231 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4232 LookupResult::Filter F = Previous.makeFilter();
4233 while (F.hasNext()) {
4234 NamedDecl *D = F.next()->getUnderlyingDecl();
4235 if (!isa<FunctionTemplateDecl>(D) ||
4236 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4237 F.erase();
4238 }
4239 F.done();
4240
4241 // Should this be diagnosed here?
4242 if (Previous.empty()) return true;
4243
4244 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4245 ExplicitTemplateArgs);
4246 return false;
4247}
4248
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004249/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004250/// specialization.
4251///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004252/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004253/// explicit function template specialization. On successful completion,
4254/// the function declaration \p FD will become a function template
4255/// specialization.
4256///
4257/// \param FD the function declaration, which will be updated to become a
4258/// function template specialization.
4259///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004260/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4261/// if any. Note that this may be valid info even when 0 arguments are
4262/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4263/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004264///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004265/// \param PrevDecl the set of declarations that may be specialized by
4266/// this function specialization.
4267bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004268Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004269 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004270 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004271 // The set of function template specializations that could match this
4272 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004273 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004274
4275 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004276 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4277 I != E; ++I) {
4278 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4279 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004280 // Only consider templates found within the same semantic lookup scope as
4281 // FD.
4282 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4283 continue;
4284
4285 // C++ [temp.expl.spec]p11:
4286 // A trailing template-argument can be left unspecified in the
4287 // template-id naming an explicit function template specialization
4288 // provided it can be deduced from the function argument type.
4289 // Perform template argument deduction to determine whether we may be
4290 // specializing this template.
4291 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004292 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004293 FunctionDecl *Specialization = 0;
4294 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004295 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004296 FD->getType(),
4297 Specialization,
4298 Info)) {
4299 // FIXME: Template argument deduction failed; record why it failed, so
4300 // that we can provide nifty diagnostics.
4301 (void)TDK;
4302 continue;
4303 }
4304
4305 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004306 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004307 }
4308 }
4309
Douglas Gregor5de279c2009-09-26 03:41:46 +00004310 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004311 UnresolvedSetIterator Result
4312 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4313 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004314 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004315 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004316 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004317 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004318 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004319 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004320 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004321
4322 // Ignore access information; it doesn't figure into redeclaration checking.
4323 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004324 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004325
4326 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004327 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004328
4329 // If this is a friend declaration, then we're not really declaring
4330 // an explicit specialization.
4331 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004332
Douglas Gregor54888652009-10-07 00:13:32 +00004333 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004334 if (!isFriend &&
4335 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004336 Specialization->getPrimaryTemplate(),
4337 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004338 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004339 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004340
4341 // C++ [temp.expl.spec]p6:
4342 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004343 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004344 // before the first use of that specialization that would cause an implicit
4345 // instantiation to take place, in every translation unit in which such a
4346 // use occurs; no diagnostic is required.
4347 FunctionTemplateSpecializationInfo *SpecInfo
4348 = Specialization->getTemplateSpecializationInfo();
4349 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004350
Abramo Bagnara8075c852010-06-12 07:44:57 +00004351 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004352 if (!isFriend &&
4353 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004354 TSK_ExplicitSpecialization,
4355 Specialization,
4356 SpecInfo->getTemplateSpecializationKind(),
4357 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004358 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004359 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004360
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004361 // Mark the prior declaration as an explicit specialization, so that later
4362 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004363 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00004364 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004365 MarkUnusedFileScopedDecl(Specialization);
4366 }
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004367
4368 // Turn the given function declaration into a function template
4369 // specialization, with the template arguments from the previous
4370 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004371 // Take copies of (semantic and syntactic) template argument lists.
4372 const TemplateArgumentList* TemplArgs = new (Context)
4373 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4374 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4375 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004376 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004377 TemplArgs, /*InsertPos=*/0,
4378 SpecInfo->getTemplateSpecializationKind(),
4379 TemplArgsAsWritten);
4380
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004381 // The "previous declaration" for this function template specialization is
4382 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004383 Previous.clear();
4384 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004385 return false;
4386}
4387
Douglas Gregor86d142a2009-10-08 07:24:58 +00004388/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004389/// specialization.
4390///
4391/// This routine performs all of the semantic analysis required for an
4392/// explicit member function specialization. On successful completion,
4393/// the function declaration \p FD will become a member function
4394/// specialization.
4395///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004396/// \param Member the member declaration, which will be updated to become a
4397/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004398///
John McCall1f82f242009-11-18 22:49:29 +00004399/// \param Previous the set of declarations, one of which may be specialized
4400/// by this function specialization; the set will be modified to contain the
4401/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004402bool
John McCall1f82f242009-11-18 22:49:29 +00004403Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004404 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004405
Douglas Gregor86d142a2009-10-08 07:24:58 +00004406 // Try to find the member we are instantiating.
4407 NamedDecl *Instantiation = 0;
4408 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004409 MemberSpecializationInfo *MSInfo = 0;
4410
John McCall1f82f242009-11-18 22:49:29 +00004411 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004412 // Nowhere to look anyway.
4413 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004414 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4415 I != E; ++I) {
4416 NamedDecl *D = (*I)->getUnderlyingDecl();
4417 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004418 if (Context.hasSameType(Function->getType(), Method->getType())) {
4419 Instantiation = Method;
4420 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004421 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004422 break;
4423 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004424 }
4425 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004426 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004427 VarDecl *PrevVar;
4428 if (Previous.isSingleResult() &&
4429 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004430 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004431 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004432 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004433 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004434 }
4435 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004436 CXXRecordDecl *PrevRecord;
4437 if (Previous.isSingleResult() &&
4438 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4439 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004440 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004441 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004442 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004443 }
4444
4445 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004446 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004447 // specializations are always out-of-line, the caller will complain about
4448 // this mismatch later.
4449 return false;
4450 }
John McCalle820e5e2010-04-13 20:37:33 +00004451
4452 // If this is a friend, just bail out here before we start turning
4453 // things into explicit specializations.
4454 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4455 // Preserve instantiation information.
4456 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4457 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4458 cast<CXXMethodDecl>(InstantiatedFrom),
4459 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4460 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4461 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4462 cast<CXXRecordDecl>(InstantiatedFrom),
4463 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4464 }
4465
4466 Previous.clear();
4467 Previous.addDecl(Instantiation);
4468 return false;
4469 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004470
Douglas Gregor86d142a2009-10-08 07:24:58 +00004471 // Make sure that this is a specialization of a member.
4472 if (!InstantiatedFrom) {
4473 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4474 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004475 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4476 return true;
4477 }
4478
Douglas Gregor06db9f52009-10-12 20:18:28 +00004479 // C++ [temp.expl.spec]p6:
4480 // If a template, a member template or the member of a class template is
4481 // explicitly specialized then that spe- cialization shall be declared
4482 // before the first use of that specialization that would cause an implicit
4483 // instantiation to take place, in every translation unit in which such a
4484 // use occurs; no diagnostic is required.
4485 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004486
Abramo Bagnara8075c852010-06-12 07:44:57 +00004487 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004488 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4489 TSK_ExplicitSpecialization,
4490 Instantiation,
4491 MSInfo->getTemplateSpecializationKind(),
4492 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004493 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004494 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004495
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004496 // Check the scope of this explicit specialization.
4497 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004498 InstantiatedFrom,
4499 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004500 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004501 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004502
Douglas Gregor86d142a2009-10-08 07:24:58 +00004503 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004504 // the original declaration to note that it is an explicit specialization
4505 // (if it was previously an implicit instantiation). This latter step
4506 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004507 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004508 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4509 if (InstantiationFunction->getTemplateSpecializationKind() ==
4510 TSK_ImplicitInstantiation) {
4511 InstantiationFunction->setTemplateSpecializationKind(
4512 TSK_ExplicitSpecialization);
4513 InstantiationFunction->setLocation(Member->getLocation());
4514 }
4515
Douglas Gregor86d142a2009-10-08 07:24:58 +00004516 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4517 cast<CXXMethodDecl>(InstantiatedFrom),
4518 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004519 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004520 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004521 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4522 if (InstantiationVar->getTemplateSpecializationKind() ==
4523 TSK_ImplicitInstantiation) {
4524 InstantiationVar->setTemplateSpecializationKind(
4525 TSK_ExplicitSpecialization);
4526 InstantiationVar->setLocation(Member->getLocation());
4527 }
4528
Douglas Gregor86d142a2009-10-08 07:24:58 +00004529 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4530 cast<VarDecl>(InstantiatedFrom),
4531 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004532 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004533 } else {
4534 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004535 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4536 if (InstantiationClass->getTemplateSpecializationKind() ==
4537 TSK_ImplicitInstantiation) {
4538 InstantiationClass->setTemplateSpecializationKind(
4539 TSK_ExplicitSpecialization);
4540 InstantiationClass->setLocation(Member->getLocation());
4541 }
4542
Douglas Gregor86d142a2009-10-08 07:24:58 +00004543 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004544 cast<CXXRecordDecl>(InstantiatedFrom),
4545 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004546 }
4547
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004548 // Save the caller the trouble of having to figure out which declaration
4549 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004550 Previous.clear();
4551 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004552 return false;
4553}
4554
Douglas Gregore47f5a72009-10-14 23:41:34 +00004555/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004556///
4557/// \returns true if a serious error occurs, false otherwise.
4558static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004559 SourceLocation InstLoc,
4560 bool WasQualifiedName) {
4561 DeclContext *ExpectedContext
4562 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4563 DeclContext *CurContext = S.CurContext->getLookupContext();
4564
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004565 if (CurContext->isRecord()) {
4566 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4567 << D;
4568 return true;
4569 }
4570
Douglas Gregore47f5a72009-10-14 23:41:34 +00004571 // C++0x [temp.explicit]p2:
4572 // An explicit instantiation shall appear in an enclosing namespace of its
4573 // template.
4574 //
4575 // This is DR275, which we do not retroactively apply to C++98/03.
4576 if (S.getLangOptions().CPlusPlus0x &&
4577 !CurContext->Encloses(ExpectedContext)) {
4578 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004579 S.Diag(InstLoc,
4580 S.getLangOptions().CPlusPlus0x?
4581 diag::err_explicit_instantiation_out_of_scope
4582 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004583 << D << NS;
4584 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004585 S.Diag(InstLoc,
4586 S.getLangOptions().CPlusPlus0x?
4587 diag::err_explicit_instantiation_must_be_global
4588 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004589 << D;
4590 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004591 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004592 }
4593
4594 // C++0x [temp.explicit]p2:
4595 // If the name declared in the explicit instantiation is an unqualified
4596 // name, the explicit instantiation shall appear in the namespace where
4597 // its template is declared or, if that namespace is inline (7.3.1), any
4598 // namespace from its enclosing namespace set.
4599 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004600 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004601
4602 if (CurContext->Equals(ExpectedContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004603 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004604
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004605 S.Diag(InstLoc,
4606 S.getLangOptions().CPlusPlus0x?
4607 diag::err_explicit_instantiation_unqualified_wrong_namespace
4608 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004609 << D << ExpectedContext;
4610 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004611 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004612}
4613
4614/// \brief Determine whether the given scope specifier has a template-id in it.
4615static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4616 if (!SS.isSet())
4617 return false;
4618
4619 // C++0x [temp.explicit]p2:
4620 // If the explicit instantiation is for a member function, a member class
4621 // or a static data member of a class template specialization, the name of
4622 // the class template specialization in the qualified-id for the member
4623 // name shall be a simple-template-id.
4624 //
4625 // C++98 has the same restriction, just worded differently.
4626 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4627 NNS; NNS = NNS->getPrefix())
4628 if (Type *T = NNS->getAsType())
4629 if (isa<TemplateSpecializationType>(T))
4630 return true;
4631
4632 return false;
4633}
4634
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004635// Explicit instantiation of a class template specialization
Douglas Gregora1f49972009-05-13 00:25:59 +00004636Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004637Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004638 SourceLocation ExternLoc,
4639 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004640 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004641 SourceLocation KWLoc,
4642 const CXXScopeSpec &SS,
4643 TemplateTy TemplateD,
4644 SourceLocation TemplateNameLoc,
4645 SourceLocation LAngleLoc,
4646 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004647 SourceLocation RAngleLoc,
4648 AttributeList *Attr) {
4649 // Find the class template we're specializing
4650 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004651 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004652 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4653
4654 // Check that the specialization uses the same tag kind as the
4655 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004656 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4657 assert(Kind != TTK_Enum &&
4658 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004659 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004660 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004661 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004662 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004663 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004664 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004665 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004666 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004667 diag::note_previous_use);
4668 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4669 }
4670
Douglas Gregore47f5a72009-10-14 23:41:34 +00004671 // C++0x [temp.explicit]p2:
4672 // There are two forms of explicit instantiation: an explicit instantiation
4673 // definition and an explicit instantiation declaration. An explicit
4674 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004675 TemplateSpecializationKind TSK
4676 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4677 : TSK_ExplicitInstantiationDeclaration;
4678
Douglas Gregora1f49972009-05-13 00:25:59 +00004679 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004680 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004681 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004682
4683 // Check that the template argument list is well-formed for this
4684 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004685 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4686 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004687 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4688 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004689 return true;
4690
Mike Stump11289f42009-09-09 15:08:12 +00004691 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004692 ClassTemplate->getTemplateParameters()->size()) &&
4693 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004694
Douglas Gregora1f49972009-05-13 00:25:59 +00004695 // Find the class template specialization declaration that
4696 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00004697 void *InsertPos = 0;
4698 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004699 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4700 Converted.flatSize(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004701
Abramo Bagnara8075c852010-06-12 07:44:57 +00004702 TemplateSpecializationKind PrevDecl_TSK
4703 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4704
Douglas Gregor54888652009-10-07 00:13:32 +00004705 // C++0x [temp.explicit]p2:
4706 // [...] An explicit instantiation shall appear in an enclosing
4707 // namespace of its template. [...]
4708 //
4709 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004710 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4711 SS.isSet()))
4712 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004713
Douglas Gregora1f49972009-05-13 00:25:59 +00004714 ClassTemplateSpecializationDecl *Specialization = 0;
4715
Douglas Gregor0681a352009-11-25 06:01:46 +00004716 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004717 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004718 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00004719 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004720 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004721 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004722 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00004723 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00004724
Abramo Bagnara8075c852010-06-12 07:44:57 +00004725 // Even though HasNoEffect == true means that this explicit instantiation
4726 // has no effect on semantics, we go on to put its syntax in the AST.
4727
4728 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4729 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004730 // Since the only prior class template specialization with these
4731 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00004732 // declaration node as our own, updating the source location
4733 // for the template name to reflect our new declaration.
4734 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004735 Specialization = PrevDecl;
4736 Specialization->setLocation(TemplateNameLoc);
4737 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004738 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004739 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004740 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004741
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004742 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004743 // Create a new class template specialization declaration node for
4744 // this explicit specialization.
4745 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004746 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004747 ClassTemplate->getDeclContext(),
4748 TemplateNameLoc,
4749 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004750 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004751 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004752
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004753 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00004754 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004755 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004756 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004757 }
4758
4759 // Build the fully-sugared type for this explicit instantiation as
4760 // the user wrote in the explicit instantiation itself. This means
4761 // that we'll pretty-print the type retrieved from the
4762 // specialization's declaration the way that the user actually wrote
4763 // the explicit instantiation, rather than formatting the name based
4764 // on the "canonical" representation used to store the template
4765 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004766 TypeSourceInfo *WrittenTy
4767 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4768 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004769 Context.getTypeDeclType(Specialization));
4770 Specialization->setTypeAsWritten(WrittenTy);
4771 TemplateArgsIn.release();
4772
Abramo Bagnara8075c852010-06-12 07:44:57 +00004773 // Set source locations for keywords.
4774 Specialization->setExternLoc(ExternLoc);
4775 Specialization->setTemplateKeywordLoc(TemplateLoc);
4776
4777 // Add the explicit instantiation into its lexical context. However,
4778 // since explicit instantiations are never found by name lookup, we
4779 // just put it into the declaration context directly.
4780 Specialization->setLexicalDeclContext(CurContext);
4781 CurContext->addDecl(Specialization);
4782
4783 // Syntax is now OK, so return if it has no other effect on semantics.
4784 if (HasNoEffect) {
4785 // Set the template specialization kind.
4786 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00004787 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00004788 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004789
4790 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004791 // A definition of a class template or class member template
4792 // shall be in scope at the point of the explicit instantiation of
4793 // the class template or class member template.
4794 //
4795 // This check comes when we actually try to perform the
4796 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004797 ClassTemplateSpecializationDecl *Def
4798 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004799 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004800 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004801 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004802 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00004803 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004804 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4805 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004806
Douglas Gregor1d957a32009-10-27 18:42:08 +00004807 // Instantiate the members of this class template specialization.
4808 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004809 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004810 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004811 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4812
4813 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4814 // TSK_ExplicitInstantiationDefinition
4815 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4816 TSK == TSK_ExplicitInstantiationDefinition)
4817 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004818
Douglas Gregor12e49d32009-10-15 22:53:21 +00004819 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004820 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004821
Abramo Bagnara8075c852010-06-12 07:44:57 +00004822 // Set the template specialization kind.
4823 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00004824 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00004825}
4826
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004827// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00004828DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004829Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004830 SourceLocation ExternLoc,
4831 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004832 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004833 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004834 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004835 IdentifierInfo *Name,
4836 SourceLocation NameLoc,
4837 AttributeList *Attr) {
4838
Douglas Gregord6ab8742009-05-28 23:31:59 +00004839 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004840 bool IsDependent = false;
John McCall48871652010-08-21 09:40:31 +00004841 Decl *TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
4842 KWLoc, SS, Name, NameLoc, Attr, AS_none,
4843 MultiTemplateParamsArg(*this, 0, 0),
4844 Owned, IsDependent);
John McCall7f41d982009-09-11 04:59:25 +00004845 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4846
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004847 if (!TagD)
4848 return true;
4849
John McCall48871652010-08-21 09:40:31 +00004850 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004851 if (Tag->isEnum()) {
4852 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4853 << Context.getTypeDeclType(Tag);
4854 return true;
4855 }
4856
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004857 if (Tag->isInvalidDecl())
4858 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004859
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004860 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4861 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4862 if (!Pattern) {
4863 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4864 << Context.getTypeDeclType(Record);
4865 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4866 return true;
4867 }
4868
Douglas Gregore47f5a72009-10-14 23:41:34 +00004869 // C++0x [temp.explicit]p2:
4870 // If the explicit instantiation is for a class or member class, the
4871 // elaborated-type-specifier in the declaration shall include a
4872 // simple-template-id.
4873 //
4874 // C++98 has the same restriction, just worded differently.
4875 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00004876 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004877 << Record << SS.getRange();
4878
4879 // C++0x [temp.explicit]p2:
4880 // There are two forms of explicit instantiation: an explicit instantiation
4881 // definition and an explicit instantiation declaration. An explicit
4882 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004883 TemplateSpecializationKind TSK
4884 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4885 : TSK_ExplicitInstantiationDeclaration;
4886
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004887 // C++0x [temp.explicit]p2:
4888 // [...] An explicit instantiation shall appear in an enclosing
4889 // namespace of its template. [...]
4890 //
4891 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004892 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004893
4894 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004895 CXXRecordDecl *PrevDecl
4896 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004897 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004898 PrevDecl = Record;
4899 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004900 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00004901 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004902 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004903 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004904 PrevDecl,
4905 MSInfo->getTemplateSpecializationKind(),
4906 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004907 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004908 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004909 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004910 return TagD;
4911 }
4912
Douglas Gregor12e49d32009-10-15 22:53:21 +00004913 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004914 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004915 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004916 // C++ [temp.explicit]p3:
4917 // A definition of a member class of a class template shall be in scope
4918 // at the point of an explicit instantiation of the member class.
4919 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004920 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004921 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004922 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4923 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004924 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4925 << Pattern;
4926 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004927 } else {
4928 if (InstantiateClass(NameLoc, Record, Def,
4929 getTemplateInstantiationArgs(Record),
4930 TSK))
4931 return true;
4932
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004933 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004934 if (!RecordDef)
4935 return true;
4936 }
4937 }
4938
4939 // Instantiate all of the members of the class.
4940 InstantiateClassMembers(NameLoc, RecordDef,
4941 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004942
Douglas Gregor88d292c2010-05-13 16:44:06 +00004943 if (TSK == TSK_ExplicitInstantiationDefinition)
4944 MarkVTableUsed(NameLoc, RecordDef, true);
4945
Mike Stump87c57ac2009-05-16 07:39:55 +00004946 // FIXME: We don't have any representation for explicit instantiations of
4947 // member classes. Such a representation is not needed for compilation, but it
4948 // should be available for clients that want to see all of the declarations in
4949 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004950 return TagD;
4951}
4952
Douglas Gregor450f00842009-09-25 18:43:00 +00004953Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4954 SourceLocation ExternLoc,
4955 SourceLocation TemplateLoc,
4956 Declarator &D) {
4957 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004958 // TODO: check if/when DNInfo should replace Name.
4959 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4960 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00004961 if (!Name) {
4962 if (!D.isInvalidType())
4963 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4964 diag::err_explicit_instantiation_requires_name)
4965 << D.getDeclSpec().getSourceRange()
4966 << D.getSourceRange();
4967
4968 return true;
4969 }
4970
4971 // The scope passed in may not be a decl scope. Zip up the scope tree until
4972 // we find one that is.
4973 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4974 (S->getFlags() & Scope::TemplateParamScope) != 0)
4975 S = S->getParent();
4976
4977 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00004978 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
4979 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00004980 if (R.isNull())
4981 return true;
4982
4983 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4984 // Cannot explicitly instantiate a typedef.
4985 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4986 << Name;
4987 return true;
4988 }
4989
Douglas Gregor3c74d412009-10-14 20:14:33 +00004990 // C++0x [temp.explicit]p1:
4991 // [...] An explicit instantiation of a function template shall not use the
4992 // inline or constexpr specifiers.
4993 // Presumably, this also applies to member functions of class templates as
4994 // well.
4995 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4996 Diag(D.getDeclSpec().getInlineSpecLoc(),
4997 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00004998 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004999
5000 // FIXME: check for constexpr specifier.
5001
Douglas Gregore47f5a72009-10-14 23:41:34 +00005002 // C++0x [temp.explicit]p2:
5003 // There are two forms of explicit instantiation: an explicit instantiation
5004 // definition and an explicit instantiation declaration. An explicit
5005 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005006 TemplateSpecializationKind TSK
5007 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5008 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005009
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005010 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005011 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005012
5013 if (!R->isFunctionType()) {
5014 // C++ [temp.explicit]p1:
5015 // A [...] static data member of a class template can be explicitly
5016 // instantiated from the member definition associated with its class
5017 // template.
John McCall27b18f82009-11-17 02:14:36 +00005018 if (Previous.isAmbiguous())
5019 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005020
John McCall67c00872009-12-02 08:25:40 +00005021 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005022 if (!Prev || !Prev->isStaticDataMember()) {
5023 // We expect to see a data data member here.
5024 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5025 << Name;
5026 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5027 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005028 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005029 return true;
5030 }
5031
5032 if (!Prev->getInstantiatedFromStaticDataMember()) {
5033 // FIXME: Check for explicit specialization?
5034 Diag(D.getIdentifierLoc(),
5035 diag::err_explicit_instantiation_data_member_not_instantiated)
5036 << Prev;
5037 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5038 // FIXME: Can we provide a note showing where this was declared?
5039 return true;
5040 }
5041
Douglas Gregore47f5a72009-10-14 23:41:34 +00005042 // C++0x [temp.explicit]p2:
5043 // If the explicit instantiation is for a member function, a member class
5044 // or a static data member of a class template specialization, the name of
5045 // the class template specialization in the qualified-id for the member
5046 // name shall be a simple-template-id.
5047 //
5048 // C++98 has the same restriction, just worded differently.
5049 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5050 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005051 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005052 << Prev << D.getCXXScopeSpec().getRange();
5053
5054 // Check the scope of this explicit instantiation.
5055 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5056
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005057 // Verify that it is okay to explicitly instantiate here.
5058 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5059 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005060 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005061 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005062 MSInfo->getTemplateSpecializationKind(),
5063 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005064 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005065 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005066 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005067 return (Decl*) 0;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005068
Douglas Gregor450f00842009-09-25 18:43:00 +00005069 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005070 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005071 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00005072 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5073 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00005074
5075 // FIXME: Create an ExplicitInstantiation node?
John McCall48871652010-08-21 09:40:31 +00005076 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005077 }
5078
Douglas Gregor0e876e02009-09-25 23:53:26 +00005079 // If the declarator is a template-id, translate the parser's template
5080 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005081 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005082 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005083 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5084 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005085 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5086 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005087 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5088 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005089 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005090 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005091 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005092 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005093 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005094
Douglas Gregor450f00842009-09-25 18:43:00 +00005095 // C++ [temp.explicit]p1:
5096 // A [...] function [...] can be explicitly instantiated from its template.
5097 // A member function [...] of a class template can be explicitly
5098 // instantiated from the member definition associated with its class
5099 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005100 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005101 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5102 P != PEnd; ++P) {
5103 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005104 if (!HasExplicitTemplateArgs) {
5105 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5106 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5107 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005108
John McCall58cc69d2010-01-27 01:50:18 +00005109 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005110 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5111 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005112 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005113 }
5114 }
5115
5116 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5117 if (!FunTmpl)
5118 continue;
5119
John McCallbc077cf2010-02-08 23:07:23 +00005120 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005121 FunctionDecl *Specialization = 0;
5122 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005123 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005124 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005125 R, Specialization, Info)) {
5126 // FIXME: Keep track of almost-matches?
5127 (void)TDK;
5128 continue;
5129 }
5130
John McCall58cc69d2010-01-27 01:50:18 +00005131 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005132 }
5133
5134 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005135 UnresolvedSetIterator Result
5136 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005137 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005138 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5139 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5140 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005141
John McCall58cc69d2010-01-27 01:50:18 +00005142 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005143 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005144
5145 // Ignore access control bits, we don't need them for redeclaration checking.
5146 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005147
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005148 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005149 Diag(D.getIdentifierLoc(),
5150 diag::err_explicit_instantiation_member_function_not_instantiated)
5151 << Specialization
5152 << (Specialization->getTemplateSpecializationKind() ==
5153 TSK_ExplicitSpecialization);
5154 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5155 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005156 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005157
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005158 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005159 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5160 PrevDecl = Specialization;
5161
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005162 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005163 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005164 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005165 PrevDecl,
5166 PrevDecl->getTemplateSpecializationKind(),
5167 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005168 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005169 return true;
5170
5171 // FIXME: We may still want to build some representation of this
5172 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005173 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005174 return (Decl*) 0;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005175 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005176
5177 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005178
5179 if (TSK == TSK_ExplicitInstantiationDefinition)
5180 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5181 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005182
Douglas Gregore47f5a72009-10-14 23:41:34 +00005183 // C++0x [temp.explicit]p2:
5184 // If the explicit instantiation is for a member function, a member class
5185 // or a static data member of a class template specialization, the name of
5186 // the class template specialization in the qualified-id for the member
5187 // name shall be a simple-template-id.
5188 //
5189 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005190 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005191 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005192 D.getCXXScopeSpec().isSet() &&
5193 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5194 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005195 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005196 << Specialization << D.getCXXScopeSpec().getRange();
5197
5198 CheckExplicitInstantiationScope(*this,
5199 FunTmpl? (NamedDecl *)FunTmpl
5200 : Specialization->getInstantiatedFromMemberFunction(),
5201 D.getIdentifierLoc(),
5202 D.getCXXScopeSpec().isSet());
5203
Douglas Gregor450f00842009-09-25 18:43:00 +00005204 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCall48871652010-08-21 09:40:31 +00005205 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005206}
5207
Douglas Gregor333489b2009-03-27 23:10:48 +00005208Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005209Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5210 const CXXScopeSpec &SS, IdentifierInfo *Name,
5211 SourceLocation TagLoc, SourceLocation NameLoc) {
5212 // This has to hold, because SS is expected to be defined.
5213 assert(Name && "Expected a name in a dependent tag");
5214
5215 NestedNameSpecifier *NNS
5216 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5217 if (!NNS)
5218 return true;
5219
Abramo Bagnara6150c882010-05-11 21:36:43 +00005220 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005221
Douglas Gregorba41d012010-04-24 16:38:41 +00005222 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5223 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005224 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005225 return true;
5226 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005227
5228 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallba7bf592010-08-24 05:47:05 +00005229 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCall7f41d982009-09-11 04:59:25 +00005230}
5231
5232Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005233Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5234 const CXXScopeSpec &SS, const IdentifierInfo &II,
5235 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005236 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005237 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5238 if (!NNS)
5239 return true;
5240
Douglas Gregorf7d77712010-06-16 22:31:08 +00005241 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5242 !getLangOptions().CPlusPlus0x)
5243 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5244 << FixItHint::CreateRemoval(TypenameLoc);
5245
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005246 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005247 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005248 if (T.isNull())
5249 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005250
5251 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5252 if (isa<DependentNameType>(T)) {
5253 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005254 TL.setKeywordLoc(TypenameLoc);
5255 TL.setQualifierRange(SS.getRange());
5256 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005257 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005258 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005259 TL.setKeywordLoc(TypenameLoc);
5260 TL.setQualifierRange(SS.getRange());
5261 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005262 }
5263
John McCallba7bf592010-08-24 05:47:05 +00005264 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00005265}
5266
Douglas Gregordce2b622009-04-01 00:28:59 +00005267Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005268Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5269 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallba7bf592010-08-24 05:47:05 +00005270 ParsedType Ty) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00005271 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5272 !getLangOptions().CPlusPlus0x)
5273 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5274 << FixItHint::CreateRemoval(TypenameLoc);
5275
John McCallf7bcc812010-05-28 23:32:21 +00005276 TypeSourceInfo *InnerTSI = 0;
5277 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCallf7bcc812010-05-28 23:32:21 +00005278
5279 assert(isa<TemplateSpecializationType>(T) &&
5280 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005281
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005282 if (computeDeclContext(SS, false)) {
5283 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005284 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005285 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005286
5287 // Push the inner type, preserving its source locations if possible.
5288 TypeLocBuilder Builder;
5289 if (InnerTSI)
5290 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5291 else
5292 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5293
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005294 /* Note: NNS already embedded in template specialization type T. */
5295 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCallf7bcc812010-05-28 23:32:21 +00005296 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5297 TL.setKeywordLoc(TypenameLoc);
5298 TL.setQualifierRange(SS.getRange());
5299
5300 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallba7bf592010-08-24 05:47:05 +00005301 return CreateParsedType(T, TSI);
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005302 }
Mike Stump11289f42009-09-09 15:08:12 +00005303
John McCallc392f372010-06-11 00:33:02 +00005304 // TODO: it's really silly that we make a template specialization
5305 // type earlier only to drop it again here.
5306 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5307 DependentTemplateName *DTN =
5308 TST->getTemplateName().getAsDependentTemplateName();
5309 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005310 assert(DTN->getQualifier()
5311 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5312 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5313 DTN->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00005314 DTN->getIdentifier(),
5315 TST->getNumArgs(),
5316 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005317 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005318 DependentTemplateSpecializationTypeLoc TL =
5319 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5320 if (InnerTSI) {
5321 TemplateSpecializationTypeLoc TSTL =
5322 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5323 TL.setLAngleLoc(TSTL.getLAngleLoc());
5324 TL.setRAngleLoc(TSTL.getRAngleLoc());
5325 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5326 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5327 } else {
5328 TL.initializeLocal(SourceLocation());
5329 }
John McCallf7bcc812010-05-28 23:32:21 +00005330 TL.setKeywordLoc(TypenameLoc);
5331 TL.setQualifierRange(SS.getRange());
John McCallba7bf592010-08-24 05:47:05 +00005332 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00005333}
5334
Douglas Gregor333489b2009-03-27 23:10:48 +00005335/// \brief Build the type that describes a C++ typename specifier,
5336/// e.g., "typename T::type".
5337QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005338Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5339 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005340 SourceLocation KeywordLoc, SourceRange NNSRange,
5341 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005342 CXXScopeSpec SS;
5343 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005344 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005345
John McCall0b66eb32010-05-01 00:40:08 +00005346 DeclContext *Ctx = computeDeclContext(SS);
5347 if (!Ctx) {
5348 // If the nested-name-specifier is dependent and couldn't be
5349 // resolved to a type, build a typename type.
5350 assert(NNS->isDependent());
5351 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005352 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005353
John McCall0b66eb32010-05-01 00:40:08 +00005354 // If the nested-name-specifier refers to the current instantiation,
5355 // the "typename" keyword itself is superfluous. In C++03, the
5356 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5357 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005358 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005359
John McCall0b66eb32010-05-01 00:40:08 +00005360 if (RequireCompleteDeclContext(SS, Ctx))
5361 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005362
5363 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005364 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005365 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005366 unsigned DiagID = 0;
5367 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005368 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005369 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005370 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005371 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005372
5373 case LookupResult::NotFoundInCurrentInstantiation:
5374 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005375 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005376
5377 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005378 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005379 // We found a type. Build an ElaboratedType, since the
5380 // typename-specifier was just sugar.
5381 return Context.getElaboratedType(ETK_Typename, NNS,
5382 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005383 }
5384
5385 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005386 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005387 break;
5388
John McCalle61f2ba2009-11-18 02:36:19 +00005389 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005390 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005391 return QualType();
5392
Douglas Gregor333489b2009-03-27 23:10:48 +00005393 case LookupResult::FoundOverloaded:
5394 DiagID = diag::err_typename_nested_not_type;
5395 Referenced = *Result.begin();
5396 break;
5397
John McCall6538c932009-10-10 05:48:19 +00005398 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005399 return QualType();
5400 }
5401
5402 // If we get here, it's because name lookup did not find a
5403 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005404 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5405 IILoc);
5406 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005407 if (Referenced)
5408 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5409 << Name;
5410 return QualType();
5411}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005412
5413namespace {
5414 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005415 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005416 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005417 SourceLocation Loc;
5418 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005419
Douglas Gregor15acfb92009-08-06 16:20:37 +00005420 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005421 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5422
Mike Stump11289f42009-09-09 15:08:12 +00005423 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005424 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005425 DeclarationName Entity)
5426 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005427 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005428
5429 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005430 /// transformed.
5431 ///
5432 /// For the purposes of type reconstruction, a type has already been
5433 /// transformed if it is NULL or if it is not dependent.
5434 bool AlreadyTransformed(QualType T) {
5435 return T.isNull() || !T->isDependentType();
5436 }
Mike Stump11289f42009-09-09 15:08:12 +00005437
5438 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005439 /// rebuilt.
5440 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005441
Douglas Gregor15acfb92009-08-06 16:20:37 +00005442 /// \brief Returns the name of the entity whose type is being rebuilt.
5443 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005444
Douglas Gregoref6ab412009-10-27 06:26:26 +00005445 /// \brief Sets the "base" location and entity when that
5446 /// information is known based on another transformation.
5447 void setBase(SourceLocation Loc, DeclarationName Entity) {
5448 this->Loc = Loc;
5449 this->Entity = Entity;
5450 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005451 };
5452}
5453
Douglas Gregor15acfb92009-08-06 16:20:37 +00005454/// \brief Rebuilds a type within the context of the current instantiation.
5455///
Mike Stump11289f42009-09-09 15:08:12 +00005456/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005457/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005458/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005459/// partial specialization thereof). This routine will rebuild that type now
5460/// that we have entered the declarator's scope, which may produce different
5461/// canonical types, e.g.,
5462///
5463/// \code
5464/// template<typename T>
5465/// struct X {
5466/// typedef T* pointer;
5467/// pointer data();
5468/// };
5469///
5470/// template<typename T>
5471/// typename X<T>::pointer X<T>::data() { ... }
5472/// \endcode
5473///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005474/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005475/// since we do not know that we can look into X<T> when we parsed the type.
5476/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005477/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005478/// as the canonical type of T*, allowing the return types of the out-of-line
5479/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005480TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5481 SourceLocation Loc,
5482 DeclarationName Name) {
5483 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005484 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005485
Douglas Gregor15acfb92009-08-06 16:20:37 +00005486 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5487 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005488}
Douglas Gregorbe999392009-09-15 16:23:51 +00005489
John McCalldadc5752010-08-24 06:29:42 +00005490ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00005491 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5492 DeclarationName());
5493 return Rebuilder.TransformExpr(E);
5494}
5495
John McCall99b2fe52010-04-29 23:50:39 +00005496bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5497 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005498
5499 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5500 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5501 DeclarationName());
5502 NestedNameSpecifier *Rebuilt =
5503 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005504 if (!Rebuilt) return true;
5505
5506 SS.setScopeRep(Rebuilt);
5507 return false;
John McCall2408e322010-04-27 00:57:59 +00005508}
5509
Douglas Gregorbe999392009-09-15 16:23:51 +00005510/// \brief Produces a formatted string that describes the binding of
5511/// template parameters to template arguments.
5512std::string
5513Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5514 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005515 // FIXME: For variadic templates, we'll need to get the structured list.
5516 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5517 Args.flat_size());
5518}
5519
5520std::string
5521Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5522 const TemplateArgument *Args,
5523 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005524 std::string Result;
5525
Douglas Gregore62e6a02009-11-11 19:13:48 +00005526 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005527 return Result;
5528
5529 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005530 if (I >= NumArgs)
5531 break;
5532
Douglas Gregorbe999392009-09-15 16:23:51 +00005533 if (I == 0)
5534 Result += "[with ";
5535 else
5536 Result += ", ";
5537
5538 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5539 Result += Id->getName();
5540 } else {
5541 Result += '$';
5542 Result += llvm::utostr(I);
5543 }
5544
5545 Result += " = ";
5546
5547 switch (Args[I].getKind()) {
5548 case TemplateArgument::Null:
5549 Result += "<no value>";
5550 break;
5551
5552 case TemplateArgument::Type: {
5553 std::string TypeStr;
5554 Args[I].getAsType().getAsStringInternal(TypeStr,
5555 Context.PrintingPolicy);
5556 Result += TypeStr;
5557 break;
5558 }
5559
5560 case TemplateArgument::Declaration: {
5561 bool Unnamed = true;
5562 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5563 if (ND->getDeclName()) {
5564 Unnamed = false;
5565 Result += ND->getNameAsString();
5566 }
5567 }
5568
5569 if (Unnamed) {
5570 Result += "<anonymous>";
5571 }
5572 break;
5573 }
5574
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005575 case TemplateArgument::Template: {
5576 std::string Str;
5577 llvm::raw_string_ostream OS(Str);
5578 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5579 Result += OS.str();
5580 break;
5581 }
5582
Douglas Gregorbe999392009-09-15 16:23:51 +00005583 case TemplateArgument::Integral: {
5584 Result += Args[I].getAsIntegral()->toString(10);
5585 break;
5586 }
5587
5588 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005589 // FIXME: This is non-optimal, since we're regurgitating the
5590 // expression we were given.
5591 std::string Str;
5592 {
5593 llvm::raw_string_ostream OS(Str);
5594 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5595 Context.PrintingPolicy);
5596 }
5597 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005598 break;
5599 }
5600
5601 case TemplateArgument::Pack:
5602 // FIXME: Format template argument packs
5603 Result += "<template argument pack>";
5604 break;
5605 }
5606 }
5607
5608 Result += ']';
5609 return Result;
5610}