blob: ba697fb398555239ac46ebc5d4f0af411ebf7e01 [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"
Douglas Gregor15acfb92009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000020#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000021#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregorb7bfe792009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000030static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
31 NamedDecl *Orig) {
32 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
John McCalle9cccd82010-06-16 08:42:20 +000035 return Orig;
Mike Stump11289f42009-09-09 15:08:12 +000036
Douglas Gregorb7bfe792009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregorb7bfe792009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 return 0;
63}
64
John McCalle66edc12009-11-24 19:00:30 +000065static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor41f90302010-04-12 20:54:26 +000066 // The set of class templates we've already seen.
67 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000068 LookupResult::Filter filter = R.makeFilter();
69 while (filter.hasNext()) {
70 NamedDecl *Orig = filter.next();
John McCalle9cccd82010-06-16 08:42:20 +000071 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCalle66edc12009-11-24 19:00:30 +000072 if (!Repl)
73 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000074 else if (Repl != Orig) {
75
76 // C++ [temp.local]p3:
77 // A lookup that finds an injected-class-name (10.2) can result in an
78 // ambiguity in certain cases (for example, if it is found in more than
79 // one base class). If all of the injected-class-names that are found
80 // refer to specializations of the same class template, and if the name
81 // is followed by a template-argument-list, the reference refers to the
82 // class template itself and not a specialization thereof, and is not
83 // ambiguous.
84 //
85 // FIXME: Will we eventually have to do the same for alias templates?
86 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
87 if (!ClassTemplates.insert(ClassTmpl)) {
88 filter.erase();
89 continue;
90 }
91
John McCalle66edc12009-11-24 19:00:30 +000092 filter.replace(Repl);
Douglas Gregor41f90302010-04-12 20:54:26 +000093 }
John McCalle66edc12009-11-24 19:00:30 +000094 }
95 filter.done();
96}
97
Douglas Gregorb7bfe792009-09-02 22:59:36 +000098TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000099 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000100 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000101 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000102 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000103 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000104 TemplateTy &TemplateResult,
105 bool &MemberOfUnknownSpecialization) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000106 assert(getLangOptions().CPlusPlus && "No template names in C!");
107
Douglas Gregor3cf81312009-11-03 23:16:33 +0000108 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000109 MemberOfUnknownSpecialization = false;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000110
111 switch (Name.getKind()) {
112 case UnqualifiedId::IK_Identifier:
113 TName = DeclarationName(Name.Identifier);
114 break;
115
116 case UnqualifiedId::IK_OperatorFunctionId:
117 TName = Context.DeclarationNames.getCXXOperatorName(
118 Name.OperatorFunctionId.Operator);
119 break;
120
Alexis Hunted0530f2009-11-28 08:58:14 +0000121 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000122 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
123 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000124
Douglas Gregor3cf81312009-11-03 23:16:33 +0000125 default:
126 return TNK_Non_template;
127 }
Mike Stump11289f42009-09-09 15:08:12 +0000128
John McCalle66edc12009-11-24 19:00:30 +0000129 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000130
Douglas Gregorff18cc12009-12-31 08:11:17 +0000131 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
132 LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000133 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
134 MemberOfUnknownSpecialization);
John McCalldcc71402010-08-13 02:23:42 +0000135 if (R.empty() || R.isAmbiguous()) {
136 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000137 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000138 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000139
John McCalld28ae272009-12-02 08:04:21 +0000140 TemplateName Template;
141 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000142
John McCalld28ae272009-12-02 08:04:21 +0000143 unsigned ResultCount = R.end() - R.begin();
144 if (ResultCount > 1) {
145 // We assume that we'll preserve the qualifier from a function
146 // template name in other ways.
147 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
148 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000149
150 // We'll do this lookup again later.
151 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000152 } else {
John McCalld28ae272009-12-02 08:04:21 +0000153 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
154
155 if (SS.isSet() && !SS.isInvalid()) {
156 NestedNameSpecifier *Qualifier
157 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000158 Template = Context.getQualifiedTemplateName(Qualifier,
159 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000160 } else {
161 Template = TemplateName(TD);
162 }
163
John McCalldcc71402010-08-13 02:23:42 +0000164 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000165 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000166
167 // We'll do this lookup again later.
168 R.suppressDiagnostics();
169 } else {
John McCalld28ae272009-12-02 08:04:21 +0000170 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
171 TemplateKind = TNK_Type_template;
172 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000173 }
Mike Stump11289f42009-09-09 15:08:12 +0000174
John McCalld28ae272009-12-02 08:04:21 +0000175 TemplateResult = TemplateTy::make(Template);
176 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000177}
178
Douglas Gregor18473f32010-01-12 21:28:44 +0000179bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
180 SourceLocation IILoc,
181 Scope *S,
182 const CXXScopeSpec *SS,
183 TemplateTy &SuggestedTemplate,
184 TemplateNameKind &SuggestedKind) {
185 // We can't recover unless there's a dependent scope specifier preceding the
186 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000187 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000188 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
189 computeDeclContext(*SS))
190 return false;
191
192 // The code is missing a 'template' keyword prior to the dependent template
193 // name.
194 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
195 Diag(IILoc, diag::err_template_kw_missing)
196 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000197 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000198 SuggestedTemplate
199 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
200 SuggestedKind = TNK_Dependent_template_name;
201 return true;
202}
203
John McCalle66edc12009-11-24 19:00:30 +0000204void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000205 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000206 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000207 bool EnteringContext,
208 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000209 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000210 MemberOfUnknownSpecialization = false;
John McCalle66edc12009-11-24 19:00:30 +0000211 DeclContext *LookupCtx = 0;
212 bool isDependent = false;
213 if (!ObjectType.isNull()) {
214 // This nested-name-specifier occurs in a member access expression, e.g.,
215 // x->B::f, and we are looking into the type of the object.
216 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
217 LookupCtx = computeDeclContext(ObjectType);
218 isDependent = ObjectType->isDependentType();
219 assert((isDependent || !ObjectType->isIncompleteType()) &&
220 "Caller should have completed object type");
221 } else if (SS.isSet()) {
222 // This nested-name-specifier occurs after another nested-name-specifier,
223 // so long into the context associated with the prior nested-name-specifier.
224 LookupCtx = computeDeclContext(SS, EnteringContext);
225 isDependent = isDependentScopeSpecifier(SS);
226
227 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000228 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000229 return;
230 }
231
232 bool ObjectTypeSearchedInScope = false;
233 if (LookupCtx) {
234 // Perform "qualified" name lookup into the declaration context we
235 // computed, which is either the type of the base of a member access
236 // expression or the declaration context associated with a prior
237 // nested-name-specifier.
238 LookupQualifiedName(Found, LookupCtx);
239
240 if (!ObjectType.isNull() && Found.empty()) {
241 // C++ [basic.lookup.classref]p1:
242 // In a class member access expression (5.2.5), if the . or -> token is
243 // immediately followed by an identifier followed by a <, the
244 // identifier must be looked up to determine whether the < is the
245 // beginning of a template argument list (14.2) or a less-than operator.
246 // The identifier is first looked up in the class of the object
247 // expression. If the identifier is not found, it is then looked up in
248 // the context of the entire postfix-expression and shall name a class
249 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000250 if (S) LookupName(Found, S);
251 ObjectTypeSearchedInScope = true;
252 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000253 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000254 // We cannot look into a dependent object type or nested nme
255 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000256 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000257 return;
258 } else {
259 // Perform unqualified name lookup in the current scope.
260 LookupName(Found, S);
261 }
262
Douglas Gregorc119dd52010-01-12 17:06:20 +0000263 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000264 // If we did not find any names, attempt to correct any typos.
265 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000266 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregorc048c522010-06-29 19:27:42 +0000267 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000268 FilterAcceptableTemplateNames(Context, Found);
John McCalle9cccd82010-06-16 08:42:20 +0000269 if (!Found.empty()) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000270 if (LookupCtx)
271 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
272 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000273 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000274 Found.getLookupName().getAsString());
275 else
276 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
277 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000278 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000279 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000280 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
281 Diag(Template->getLocation(), diag::note_previous_decl)
282 << Template->getDeclName();
John McCalle9cccd82010-06-16 08:42:20 +0000283 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000284 } else {
285 Found.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +0000286 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000287 }
288 }
289
John McCalle66edc12009-11-24 19:00:30 +0000290 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000291 if (Found.empty()) {
292 if (isDependent)
293 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000294 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000295 }
John McCalle66edc12009-11-24 19:00:30 +0000296
297 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
298 // C++ [basic.lookup.classref]p1:
299 // [...] If the lookup in the class of the object expression finds a
300 // template, the name is also looked up in the context of the entire
301 // postfix-expression and [...]
302 //
303 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
304 LookupOrdinaryName);
305 LookupName(FoundOuter, S);
306 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000307
John McCalle66edc12009-11-24 19:00:30 +0000308 if (FoundOuter.empty()) {
309 // - if the name is not found, the name found in the class of the
310 // object expression is used, otherwise
311 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
312 // - if the name is found in the context of the entire
313 // postfix-expression and does not name a class template, the name
314 // found in the class of the object expression is used, otherwise
John McCalle9cccd82010-06-16 08:42:20 +0000315 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000316 // - if the name found is a class template, it must refer to the same
317 // entity as the one found in the class of the object expression,
318 // otherwise the program is ill-formed.
319 if (!Found.isSingleResult() ||
320 Found.getFoundDecl()->getCanonicalDecl()
321 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
322 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000323 diag::ext_nested_name_member_ref_lookup_ambiguous)
324 << Found.getLookupName()
325 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000326 Diag(Found.getRepresentativeDecl()->getLocation(),
327 diag::note_ambig_member_ref_object_type)
328 << ObjectType;
329 Diag(FoundOuter.getFoundDecl()->getLocation(),
330 diag::note_ambig_member_ref_scope);
331
332 // Recover by taking the template that we found in the object
333 // expression's type.
334 }
335 }
336 }
337}
338
John McCallcd4b4772009-12-02 03:53:29 +0000339/// ActOnDependentIdExpression - Handle a dependent id-expression that
340/// was just parsed. This is only possible with an explicit scope
341/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000342Sema::OwningExprResult
343Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000344 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000345 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000346 const TemplateArgumentListInfo *TemplateArgs) {
347 NestedNameSpecifier *Qualifier
348 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall87fe5d52010-05-20 01:18:31 +0000349
350 DeclContext *DC = getFunctionLevelDeclContext();
John McCalle66edc12009-11-24 19:00:30 +0000351
John McCallcd4b4772009-12-02 03:53:29 +0000352 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000353 isa<CXXMethodDecl>(DC) &&
354 cast<CXXMethodDecl>(DC)->isInstance()) {
355 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallcd4b4772009-12-02 03:53:29 +0000356
John McCalle66edc12009-11-24 19:00:30 +0000357 // Since the 'this' expression is synthesized, we don't need to
358 // perform the double-lookup check.
359 NamedDecl *FirstQualifierInScope = 0;
360
John McCall2d74de92009-12-01 22:10:20 +0000361 return Owned(CXXDependentScopeMemberExpr::Create(Context,
362 /*This*/ 0, ThisType,
363 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000364 /*Op*/ SourceLocation(),
365 Qualifier, SS.getRange(),
366 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000367 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000368 TemplateArgs));
369 }
370
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000371 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000372}
373
374Sema::OwningExprResult
375Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000376 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000377 const TemplateArgumentListInfo *TemplateArgs) {
378 return Owned(DependentScopeDeclRefExpr::Create(Context,
379 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
380 SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000381 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000382 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000383}
384
Douglas Gregor5101c242008-12-05 18:15:24 +0000385/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
386/// that the template parameter 'PrevDecl' is being shadowed by a new
387/// declaration at location Loc. Returns true to indicate that this is
388/// an error, and false otherwise.
389bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000390 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000391
392 // Microsoft Visual C++ permits template parameters to be shadowed.
393 if (getLangOptions().Microsoft)
394 return false;
395
396 // C++ [temp.local]p4:
397 // A template-parameter shall not be redeclared within its
398 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000399 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000400 << cast<NamedDecl>(PrevDecl)->getDeclName();
401 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
402 return true;
403}
404
Douglas Gregor463421d2009-03-03 04:44:36 +0000405/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000406/// the parameter D to reference the templated declaration and return a pointer
407/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000408TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000409 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000410 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000411 return Temp;
412 }
413 return 0;
414}
415
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000416static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
417 const ParsedTemplateArgument &Arg) {
418
419 switch (Arg.getKind()) {
420 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000421 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000422 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
423 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000424 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000425 return TemplateArgumentLoc(TemplateArgument(T), DI);
426 }
427
428 case ParsedTemplateArgument::NonType: {
429 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
430 return TemplateArgumentLoc(TemplateArgument(E), E);
431 }
432
433 case ParsedTemplateArgument::Template: {
434 TemplateName Template
435 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
436 return TemplateArgumentLoc(TemplateArgument(Template),
437 Arg.getScopeSpec().getRange(),
438 Arg.getLocation());
439 }
440 }
441
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000442 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000443 return TemplateArgumentLoc();
444}
445
446/// \brief Translates template arguments as provided by the parser
447/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000448void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
449 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000450 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000451 TemplateArgs.addArgument(translateTemplateArgument(*this,
452 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000453}
454
Douglas Gregor5101c242008-12-05 18:15:24 +0000455/// ActOnTypeParameter - Called when a C++ template type parameter
456/// (e.g., "typename T") has been parsed. Typename specifies whether
457/// the keyword "typename" was used to declare the type parameter
458/// (otherwise, "class" was used), and KeyLoc is the location of the
459/// "class" or "typename" keyword. ParamName is the name of the
460/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregor2ebcae12010-06-16 15:23:05 +0000461/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000462/// If the type parameter has a default argument, it will be added
463/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000464Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000465 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000466 SourceLocation KeyLoc,
467 IdentifierInfo *ParamName,
468 SourceLocation ParamNameLoc,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000469 unsigned Depth, unsigned Position,
470 SourceLocation EqualLoc,
471 TypeTy *DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000472 assert(S->isTemplateParamScope() &&
473 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000474 bool Invalid = false;
475
476 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000477 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000478 LookupOrdinaryName,
479 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000480 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000481 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000482 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000483 }
484
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000485 SourceLocation Loc = ParamNameLoc;
486 if (!ParamName)
487 Loc = KeyLoc;
488
Douglas Gregor5101c242008-12-05 18:15:24 +0000489 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000490 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
491 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000492 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000493 if (Invalid)
494 Param->setInvalidDecl();
495
496 if (ParamName) {
497 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000498 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000499 IdResolver.AddDecl(Param);
500 }
501
Douglas Gregordc13ded2010-07-01 00:00:45 +0000502 // Handle the default argument, if provided.
503 if (DefaultArg) {
504 TypeSourceInfo *DefaultTInfo;
505 GetTypeFromParser(DefaultArg, &DefaultTInfo);
506
507 assert(DefaultTInfo && "expected source information for type");
508
509 // C++0x [temp.param]p9:
510 // A default template-argument may be specified for any kind of
511 // template-parameter that is not a template parameter pack.
512 if (Ellipsis) {
513 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
514 return DeclPtrTy::make(Param);
515 }
516
517 // Check the template argument itself.
518 if (CheckTemplateArgument(Param, DefaultTInfo)) {
519 Param->setInvalidDecl();
520 return DeclPtrTy::make(Param);;
521 }
522
523 Param->setDefaultArgument(DefaultTInfo, false);
524 }
525
Chris Lattner83f095c2009-03-28 19:18:32 +0000526 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000527}
528
Douglas Gregor463421d2009-03-03 04:44:36 +0000529/// \brief Check that the type of a non-type template parameter is
530/// well-formed.
531///
532/// \returns the (possibly-promoted) parameter type if valid;
533/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000534QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000535Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000536 // We don't allow variably-modified types as the type of non-type template
537 // parameters.
538 if (T->isVariablyModifiedType()) {
539 Diag(Loc, diag::err_variably_modified_nontype_template_param)
540 << T;
541 return QualType();
542 }
543
Douglas Gregor463421d2009-03-03 04:44:36 +0000544 // C++ [temp.param]p4:
545 //
546 // A non-type template-parameter shall have one of the following
547 // (optionally cv-qualified) types:
548 //
549 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000550 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000551 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000552 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000553 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000554 T->isReferenceType() ||
555 // -- pointer to member.
556 T->isMemberPointerType() ||
557 // If T is a dependent type, we can't do the check now, so we
558 // assume that it is well-formed.
559 T->isDependentType())
560 return T;
561 // C++ [temp.param]p8:
562 //
563 // A non-type template-parameter of type "array of T" or
564 // "function returning T" is adjusted to be of type "pointer to
565 // T" or "pointer to function returning T", respectively.
566 else if (T->isArrayType())
567 // FIXME: Keep the type prior to promotion?
568 return Context.getArrayDecayedType(T);
569 else if (T->isFunctionType())
570 // FIXME: Keep the type prior to promotion?
571 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000572
Douglas Gregor463421d2009-03-03 04:44:36 +0000573 Diag(Loc, diag::err_template_nontype_parm_bad_type)
574 << T;
575
576 return QualType();
577}
578
Chris Lattner83f095c2009-03-28 19:18:32 +0000579Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000580 unsigned Depth,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000581 unsigned Position,
582 SourceLocation EqualLoc,
583 ExprArg DefaultArg) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000584 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
585 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000586
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000587 assert(S->isTemplateParamScope() &&
588 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000589 bool Invalid = false;
590
591 IdentifierInfo *ParamName = D.getIdentifier();
592 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000593 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000594 LookupOrdinaryName,
595 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000596 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000597 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000598 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000599 }
600
Douglas Gregor463421d2009-03-03 04:44:36 +0000601 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000602 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000603 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000604 Invalid = true;
605 }
Douglas Gregor81338792009-02-10 17:43:50 +0000606
Douglas Gregor5101c242008-12-05 18:15:24 +0000607 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000608 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
609 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000610 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000611 if (Invalid)
612 Param->setInvalidDecl();
613
614 if (D.getIdentifier()) {
615 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000616 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000617 IdResolver.AddDecl(Param);
618 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000619
620 // Check the well-formedness of the default template argument, if provided.
621 if (Expr *Default = static_cast<Expr *>(DefaultArg.get())) {
622 TemplateArgument Converted;
623 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
624 Param->setInvalidDecl();
625 return DeclPtrTy::make(Param);;
626 }
627
628 Param->setDefaultArgument(DefaultArg.takeAs<Expr>(), false);
629 }
630
Chris Lattner83f095c2009-03-28 19:18:32 +0000631 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000632}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000633
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000634/// ActOnTemplateTemplateParameter - Called when a C++ template template
635/// parameter (e.g. T in template <template <typename> class T> class array)
636/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000637Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
638 SourceLocation TmpLoc,
639 TemplateParamsTy *Params,
640 IdentifierInfo *Name,
641 SourceLocation NameLoc,
642 unsigned Depth,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000643 unsigned Position,
644 SourceLocation EqualLoc,
645 const ParsedTemplateArgument &Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000646 assert(S->isTemplateParamScope() &&
647 "Template template parameter not in template parameter scope!");
648
649 // Construct the parameter object.
650 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000651 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
652 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000653 (TemplateParameterList*)Params);
654
Douglas Gregordc13ded2010-07-01 00:00:45 +0000655 // If the template template parameter has a name, then link the identifier
656 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000657 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000658 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000659 IdResolver.AddDecl(Param);
660 }
661
Douglas Gregordc13ded2010-07-01 00:00:45 +0000662 if (!Default.isInvalid()) {
663 // Check only that we have a template template argument. We don't want to
664 // try to check well-formedness now, because our template template parameter
665 // might have dependent types in its template parameters, which we wouldn't
666 // be able to match now.
667 //
668 // If none of the template template parameter's template arguments mention
669 // other template parameters, we could actually perform more checking here.
670 // However, it isn't worth doing.
671 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
672 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
673 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
674 << DefaultArg.getSourceRange();
675 return DeclPtrTy::make(Param);
676 }
677
678 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000679 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000680
Douglas Gregordc13ded2010-07-01 00:00:45 +0000681 return DeclPtrTy::make(Param);
Douglas Gregordba32632009-02-10 19:49:53 +0000682}
683
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000684/// ActOnTemplateParameterList - Builds a TemplateParameterList that
685/// contains the template parameters in Params/NumParams.
686Sema::TemplateParamsTy *
687Sema::ActOnTemplateParameterList(unsigned Depth,
688 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000689 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000690 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000691 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000692 SourceLocation RAngleLoc) {
693 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000694 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000695
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000696 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000697 (NamedDecl**)Params, NumParams,
698 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000699}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000700
John McCall3e11ebe2010-03-15 10:12:16 +0000701static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
702 if (SS.isSet())
703 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
704 SS.getRange());
705}
706
Douglas Gregorc08f4892009-03-25 00:13:59 +0000707Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000708Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000709 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000710 IdentifierInfo *Name, SourceLocation NameLoc,
711 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000712 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000713 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000714 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000715 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000716 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000717 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000718
719 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000720 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000721 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000722
Abramo Bagnara6150c882010-05-11 21:36:43 +0000723 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
724 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000725
726 // There is no such thing as an unnamed class template.
727 if (!Name) {
728 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000729 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000730 }
731
732 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000733 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000734 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000735 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000736 if (SS.isNotEmpty() && !SS.isInvalid()) {
737 SemanticContext = computeDeclContext(SS, true);
738 if (!SemanticContext) {
739 // FIXME: Produce a reasonable diagnostic here
740 return true;
741 }
Mike Stump11289f42009-09-09 15:08:12 +0000742
John McCall0b66eb32010-05-01 00:40:08 +0000743 if (RequireCompleteDeclContext(SS, SemanticContext))
744 return true;
745
John McCall27b18f82009-11-17 02:14:36 +0000746 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000747 } else {
748 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000749 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000750 }
Mike Stump11289f42009-09-09 15:08:12 +0000751
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000752 if (Previous.isAmbiguous())
753 return true;
754
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000755 NamedDecl *PrevDecl = 0;
756 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000757 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000758
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000759 // If there is a previous declaration with the same name, check
760 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000761 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000762 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000763
764 // We may have found the injected-class-name of a class template,
765 // class template partial specialization, or class template specialization.
766 // In these cases, grab the template that is being defined or specialized.
767 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
768 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
769 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
770 PrevClassTemplate
771 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
772 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
773 PrevClassTemplate
774 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
775 ->getSpecializedTemplate();
776 }
777 }
778
John McCalld43784f2009-12-18 11:25:59 +0000779 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000780 // C++ [namespace.memdef]p3:
781 // [...] When looking for a prior declaration of a class or a function
782 // declared as a friend, and when the name of the friend class or
783 // function is neither a qualified name nor a template-id, scopes outside
784 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000785 if (!SS.isSet()) {
786 DeclContext *OutermostContext = CurContext;
787 while (!OutermostContext->isFileContext())
788 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000789
Douglas Gregorb74b1032010-04-18 17:37:40 +0000790 if (PrevDecl &&
791 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
792 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
793 SemanticContext = PrevDecl->getDeclContext();
794 } else {
795 // Declarations in outer scopes don't matter. However, the outermost
796 // context we computed is the semantic context for our new
797 // declaration.
798 PrevDecl = PrevClassTemplate = 0;
799 SemanticContext = OutermostContext;
800 }
John McCall90d3bb92009-12-17 23:21:11 +0000801 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000802
John McCall90d3bb92009-12-17 23:21:11 +0000803 if (CurContext->isDependentContext()) {
804 // If this is a dependent context, we don't want to link the friend
805 // class template to the template in scope, because that would perform
806 // checking of the template parameter lists that can't be performed
807 // until the outer context is instantiated.
808 PrevDecl = PrevClassTemplate = 0;
809 }
810 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
811 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000812
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000813 if (PrevClassTemplate) {
814 // Ensure that the template parameter lists are compatible.
815 if (!TemplateParameterListsAreEqual(TemplateParams,
816 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000817 /*Complain=*/true,
818 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000819 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000820
821 // C++ [temp.class]p4:
822 // In a redeclaration, partial specialization, explicit
823 // specialization or explicit instantiation of a class template,
824 // the class-key shall agree in kind with the original class
825 // template declaration (7.1.5.3).
826 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000827 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000828 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000829 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000830 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000831 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000832 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000833 }
834
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000835 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000836 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000837 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000838 Diag(NameLoc, diag::err_redefinition) << Name;
839 Diag(Def->getLocation(), diag::note_previous_definition);
840 // FIXME: Would it make sense to try to "forget" the previous
841 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000842 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000843 }
844 }
845 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
846 // Maybe we will complain about the shadowed template parameter.
847 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
848 // Just pretend that we didn't see the previous declaration.
849 PrevDecl = 0;
850 } else if (PrevDecl) {
851 // C++ [temp]p5:
852 // A class template shall not have the same name as any other
853 // template, class, function, object, enumeration, enumerator,
854 // namespace, or type in the same scope (3.3), except as specified
855 // in (14.5.4).
856 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
857 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000858 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000859 }
860
Douglas Gregordba32632009-02-10 19:49:53 +0000861 // Check the template parameter list of this declaration, possibly
862 // merging in the template parameter list from the previous class
863 // template declaration.
864 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000865 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
866 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000867 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000868
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000869 if (SS.isSet()) {
870 // If the name of the template was qualified, we must be defining the
871 // template out-of-line.
872 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
873 !(TUK == TUK_Friend && CurContext->isDependentContext()))
874 Diag(NameLoc, diag::err_member_def_does_not_match)
875 << Name << SemanticContext << SS.getRange();
876 }
877
Mike Stump11289f42009-09-09 15:08:12 +0000878 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000879 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000880 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000881 PrevClassTemplate->getTemplatedDecl() : 0,
882 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000883 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000884
885 ClassTemplateDecl *NewTemplate
886 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
887 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000888 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000889 NewClass->setDescribedClassTemplate(NewTemplate);
890
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000891 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000892 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +0000893 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000894 assert(T->isDependentType() && "Class template type is not dependent?");
895 (void)T;
896
Douglas Gregorcf915552009-10-13 16:30:37 +0000897 // If we are providing an explicit specialization of a member that is a
898 // class template, make a note of that.
899 if (PrevClassTemplate &&
900 PrevClassTemplate->getInstantiatedFromMemberTemplate())
901 PrevClassTemplate->setMemberSpecialization();
902
Anders Carlsson137108d2009-03-26 01:24:28 +0000903 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000904 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000905 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000906
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000907 // Set the lexical context of these templates
908 NewClass->setLexicalDeclContext(CurContext);
909 NewTemplate->setLexicalDeclContext(CurContext);
910
John McCall9bb74a52009-07-31 02:45:11 +0000911 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000912 NewClass->startDefinition();
913
914 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000915 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000916
John McCall27b5c252009-09-14 21:59:20 +0000917 if (TUK != TUK_Friend)
918 PushOnScopeChains(NewTemplate, S);
919 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000920 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000921 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000922 NewClass->setAccess(PrevClassTemplate->getAccess());
923 }
John McCall27b5c252009-09-14 21:59:20 +0000924
Douglas Gregor3dad8422009-09-26 06:47:28 +0000925 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
926 PrevClassTemplate != NULL);
927
John McCall27b5c252009-09-14 21:59:20 +0000928 // Friend templates are visible in fairly strange ways.
929 if (!CurContext->isDependentContext()) {
930 DeclContext *DC = SemanticContext->getLookupContext();
931 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
932 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
933 PushOnScopeChains(NewTemplate, EnclosingScope,
934 /* AddToContext = */ false);
935 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000936
937 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
938 NewClass->getLocation(),
939 NewTemplate,
940 /*FIXME:*/NewClass->getLocation());
941 Friend->setAccess(AS_public);
942 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000943 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000944
Douglas Gregordba32632009-02-10 19:49:53 +0000945 if (Invalid) {
946 NewTemplate->setInvalidDecl();
947 NewClass->setInvalidDecl();
948 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000949 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000950}
951
Douglas Gregored5731f2009-11-25 17:50:39 +0000952/// \brief Diagnose the presence of a default template argument on a
953/// template parameter, which is ill-formed in certain contexts.
954///
955/// \returns true if the default template argument should be dropped.
956static bool DiagnoseDefaultTemplateArgument(Sema &S,
957 Sema::TemplateParamListContext TPC,
958 SourceLocation ParamLoc,
959 SourceRange DefArgRange) {
960 switch (TPC) {
961 case Sema::TPC_ClassTemplate:
962 return false;
963
964 case Sema::TPC_FunctionTemplate:
965 // C++ [temp.param]p9:
966 // A default template-argument shall not be specified in a
967 // function template declaration or a function template
968 // definition [...]
969 // (This sentence is not in C++0x, per DR226).
970 if (!S.getLangOptions().CPlusPlus0x)
971 S.Diag(ParamLoc,
972 diag::err_template_parameter_default_in_function_template)
973 << DefArgRange;
974 return false;
975
976 case Sema::TPC_ClassTemplateMember:
977 // C++0x [temp.param]p9:
978 // A default template-argument shall not be specified in the
979 // template-parameter-lists of the definition of a member of a
980 // class template that appears outside of the member's class.
981 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
982 << DefArgRange;
983 return true;
984
985 case Sema::TPC_FriendFunctionTemplate:
986 // C++ [temp.param]p9:
987 // A default template-argument shall not be specified in a
988 // friend template declaration.
989 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
990 << DefArgRange;
991 return true;
992
993 // FIXME: C++0x [temp.param]p9 allows default template-arguments
994 // for friend function templates if there is only a single
995 // declaration (and it is a definition). Strange!
996 }
997
998 return false;
999}
1000
Douglas Gregordba32632009-02-10 19:49:53 +00001001/// \brief Checks the validity of a template parameter list, possibly
1002/// considering the template parameter list from a previous
1003/// declaration.
1004///
1005/// If an "old" template parameter list is provided, it must be
1006/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1007/// template parameter list.
1008///
1009/// \param NewParams Template parameter list for a new template
1010/// declaration. This template parameter list will be updated with any
1011/// default arguments that are carried through from the previous
1012/// template parameter list.
1013///
1014/// \param OldParams If provided, template parameter list from a
1015/// previous declaration of the same template. Default template
1016/// arguments will be merged from the old template parameter list to
1017/// the new template parameter list.
1018///
Douglas Gregored5731f2009-11-25 17:50:39 +00001019/// \param TPC Describes the context in which we are checking the given
1020/// template parameter list.
1021///
Douglas Gregordba32632009-02-10 19:49:53 +00001022/// \returns true if an error occurred, false otherwise.
1023bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001024 TemplateParameterList *OldParams,
1025 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001026 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001027
Douglas Gregordba32632009-02-10 19:49:53 +00001028 // C++ [temp.param]p10:
1029 // The set of default template-arguments available for use with a
1030 // template declaration or definition is obtained by merging the
1031 // default arguments from the definition (if in scope) and all
1032 // declarations in scope in the same way default function
1033 // arguments are (8.3.6).
1034 bool SawDefaultArgument = false;
1035 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001036
Anders Carlsson327865d2009-06-12 23:20:15 +00001037 bool SawParameterPack = false;
1038 SourceLocation ParameterPackLoc;
1039
Mike Stumpc89c8e32009-02-11 23:03:27 +00001040 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001041 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001042 if (OldParams)
1043 OldParam = OldParams->begin();
1044
1045 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1046 NewParamEnd = NewParams->end();
1047 NewParam != NewParamEnd; ++NewParam) {
1048 // Variables used to diagnose redundant default arguments
1049 bool RedundantDefaultArg = false;
1050 SourceLocation OldDefaultLoc;
1051 SourceLocation NewDefaultLoc;
1052
1053 // Variables used to diagnose missing default arguments
1054 bool MissingDefaultArg = false;
1055
Anders Carlsson327865d2009-06-12 23:20:15 +00001056 // C++0x [temp.param]p11:
1057 // If a template parameter of a class template is a template parameter pack,
1058 // it must be the last template parameter.
1059 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001060 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001061 diag::err_template_param_pack_must_be_last_template_parameter);
1062 Invalid = true;
1063 }
1064
Douglas Gregordba32632009-02-10 19:49:53 +00001065 if (TemplateTypeParmDecl *NewTypeParm
1066 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001067 // Check the presence of a default argument here.
1068 if (NewTypeParm->hasDefaultArgument() &&
1069 DiagnoseDefaultTemplateArgument(*this, TPC,
1070 NewTypeParm->getLocation(),
1071 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001072 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001073 NewTypeParm->removeDefaultArgument();
1074
1075 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001076 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001077 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001078
Anders Carlsson327865d2009-06-12 23:20:15 +00001079 if (NewTypeParm->isParameterPack()) {
1080 assert(!NewTypeParm->hasDefaultArgument() &&
1081 "Parameter packs can't have a default argument!");
1082 SawParameterPack = true;
1083 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001084 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001085 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001086 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1087 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1088 SawDefaultArgument = true;
1089 RedundantDefaultArg = true;
1090 PreviousDefaultArgLoc = NewDefaultLoc;
1091 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1092 // Merge the default argument from the old declaration to the
1093 // new declaration.
1094 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001095 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001096 true);
1097 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1098 } else if (NewTypeParm->hasDefaultArgument()) {
1099 SawDefaultArgument = true;
1100 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1101 } else if (SawDefaultArgument)
1102 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001103 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001104 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001105 // Check the presence of a default argument here.
1106 if (NewNonTypeParm->hasDefaultArgument() &&
1107 DiagnoseDefaultTemplateArgument(*this, TPC,
1108 NewNonTypeParm->getLocation(),
1109 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001110 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001111 }
1112
Mike Stump12b8ce12009-08-04 21:02:39 +00001113 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001114 NonTypeTemplateParmDecl *OldNonTypeParm
1115 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001116 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001117 NewNonTypeParm->hasDefaultArgument()) {
1118 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1119 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1120 SawDefaultArgument = true;
1121 RedundantDefaultArg = true;
1122 PreviousDefaultArgLoc = NewDefaultLoc;
1123 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1124 // Merge the default argument from the old declaration to the
1125 // new declaration.
1126 SawDefaultArgument = true;
1127 // FIXME: We need to create a new kind of "default argument"
1128 // expression that points to a previous template template
1129 // parameter.
1130 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001131 OldNonTypeParm->getDefaultArgument(),
1132 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001133 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1134 } else if (NewNonTypeParm->hasDefaultArgument()) {
1135 SawDefaultArgument = true;
1136 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1137 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001138 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001139 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001140 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001141 TemplateTemplateParmDecl *NewTemplateParm
1142 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001143 if (NewTemplateParm->hasDefaultArgument() &&
1144 DiagnoseDefaultTemplateArgument(*this, TPC,
1145 NewTemplateParm->getLocation(),
1146 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001147 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001148
1149 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001150 TemplateTemplateParmDecl *OldTemplateParm
1151 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001152 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001153 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001154 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1155 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001156 SawDefaultArgument = true;
1157 RedundantDefaultArg = true;
1158 PreviousDefaultArgLoc = NewDefaultLoc;
1159 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1160 // Merge the default argument from the old declaration to the
1161 // new declaration.
1162 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001163 // FIXME: We need to create a new kind of "default argument" expression
1164 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001165 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001166 OldTemplateParm->getDefaultArgument(),
1167 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001168 PreviousDefaultArgLoc
1169 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001170 } else if (NewTemplateParm->hasDefaultArgument()) {
1171 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001172 PreviousDefaultArgLoc
1173 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001174 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001175 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001176 }
1177
1178 if (RedundantDefaultArg) {
1179 // C++ [temp.param]p12:
1180 // A template-parameter shall not be given default arguments
1181 // by two different declarations in the same scope.
1182 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1183 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1184 Invalid = true;
1185 } else if (MissingDefaultArg) {
1186 // C++ [temp.param]p11:
1187 // If a template-parameter has a default template-argument,
1188 // all subsequent template-parameters shall have a default
1189 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001190 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001191 diag::err_template_param_default_arg_missing);
1192 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1193 Invalid = true;
1194 }
1195
1196 // If we have an old template parameter list that we're merging
1197 // in, move on to the next parameter.
1198 if (OldParams)
1199 ++OldParam;
1200 }
1201
1202 return Invalid;
1203}
Douglas Gregord32e0282009-02-09 23:23:08 +00001204
Mike Stump11289f42009-09-09 15:08:12 +00001205/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001206/// specifier, returning the template parameter list that applies to the
1207/// name.
1208///
1209/// \param DeclStartLoc the start of the declaration that has a scope
1210/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001211///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001212/// \param SS the scope specifier that will be matched to the given template
1213/// parameter lists. This scope specifier precedes a qualified name that is
1214/// being declared.
1215///
1216/// \param ParamLists the template parameter lists, from the outermost to the
1217/// innermost template parameter lists.
1218///
1219/// \param NumParamLists the number of template parameter lists in ParamLists.
1220///
John McCalle820e5e2010-04-13 20:37:33 +00001221/// \param IsFriend Whether to apply the slightly different rules for
1222/// matching template parameters to scope specifiers in friend
1223/// declarations.
1224///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001225/// \param IsExplicitSpecialization will be set true if the entity being
1226/// declared is an explicit specialization, false otherwise.
1227///
Mike Stump11289f42009-09-09 15:08:12 +00001228/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001229/// name that is preceded by the scope specifier @p SS. This template
1230/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001231/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001232/// template specialization), or may be NULL (if we were's declaring isn't
1233/// itself a template).
1234TemplateParameterList *
1235Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1236 const CXXScopeSpec &SS,
1237 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001238 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001239 bool IsFriend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001240 bool &IsExplicitSpecialization,
1241 bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001242 IsExplicitSpecialization = false;
1243
Douglas Gregord8d297c2009-07-21 23:53:31 +00001244 // Find the template-ids that occur within the nested-name-specifier. These
1245 // template-ids will match up with the template parameter lists.
1246 llvm::SmallVector<const TemplateSpecializationType *, 4>
1247 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001248 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1249 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001250 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1251 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001252 const Type *T = NNS->getAsType();
1253 if (!T) break;
1254
1255 // C++0x [temp.expl.spec]p17:
1256 // A member or a member template may be nested within many
1257 // enclosing class templates. In an explicit specialization for
1258 // such a member, the member declaration shall be preceded by a
1259 // template<> for each enclosing class template that is
1260 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001261 //
1262 // Following the existing practice of GNU and EDG, we allow a typedef of a
1263 // template specialization type.
1264 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1265 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001266
Mike Stump11289f42009-09-09 15:08:12 +00001267 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001268 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001269 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1270 if (!Template)
1271 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001272
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001273 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001274 ClassTemplateSpecializationDecl *SpecDecl
1275 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1276 // If the nested name specifier refers to an explicit specialization,
1277 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001278 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1279 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001280 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001281 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001282 }
Mike Stump11289f42009-09-09 15:08:12 +00001283
Douglas Gregord8d297c2009-07-21 23:53:31 +00001284 TemplateIdsInSpecifier.push_back(SpecType);
1285 }
1286 }
Mike Stump11289f42009-09-09 15:08:12 +00001287
Douglas Gregord8d297c2009-07-21 23:53:31 +00001288 // Reverse the list of template-ids in the scope specifier, so that we can
1289 // more easily match up the template-ids and the template parameter lists.
1290 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001291
Douglas Gregord8d297c2009-07-21 23:53:31 +00001292 SourceLocation FirstTemplateLoc = DeclStartLoc;
1293 if (NumParamLists)
1294 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001295
Douglas Gregord8d297c2009-07-21 23:53:31 +00001296 // Match the template-ids found in the specifier to the template parameter
1297 // lists.
1298 unsigned Idx = 0;
1299 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1300 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001301 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1302 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001303 if (Idx >= NumParamLists) {
1304 // We have a template-id without a corresponding template parameter
1305 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001306
1307 // ...which is fine if this is a friend declaration.
1308 if (IsFriend) {
1309 IsExplicitSpecialization = true;
1310 break;
1311 }
1312
Douglas Gregord8d297c2009-07-21 23:53:31 +00001313 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001314 // FIXME: the location information here isn't great.
1315 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001316 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001317 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001318 << SS.getRange();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001319 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001320 } else {
1321 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1322 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001323 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001324 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001325 }
1326 return 0;
1327 }
Mike Stump11289f42009-09-09 15:08:12 +00001328
Douglas Gregord8d297c2009-07-21 23:53:31 +00001329 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001330 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001331 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001332
John McCall2408e322010-04-27 00:57:59 +00001333 // Are there cases in (e.g.) friends where this won't match?
1334 if (const InjectedClassNameType *Injected
1335 = TemplateId->getAs<InjectedClassNameType>()) {
1336 CXXRecordDecl *Record = Injected->getDecl();
1337 if (ClassTemplatePartialSpecializationDecl *Partial =
1338 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1339 ExpectedTemplateParams = Partial->getTemplateParameters();
1340 else
1341 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1342 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001343 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001344
John McCall2408e322010-04-27 00:57:59 +00001345 if (ExpectedTemplateParams)
1346 TemplateParameterListsAreEqual(ParamLists[Idx],
1347 ExpectedTemplateParams,
1348 true, TPL_TemplateMatch);
1349
Douglas Gregored5731f2009-11-25 17:50:39 +00001350 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001351 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001352 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001353 diag::err_template_param_list_matches_nontemplate)
1354 << TemplateId
1355 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001356 else
1357 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001358 }
Mike Stump11289f42009-09-09 15:08:12 +00001359
Douglas Gregord8d297c2009-07-21 23:53:31 +00001360 // If there were at least as many template-ids as there were template
1361 // parameter lists, then there are no template parameter lists remaining for
1362 // the declaration itself.
1363 if (Idx >= NumParamLists)
1364 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001365
Douglas Gregord8d297c2009-07-21 23:53:31 +00001366 // If there were too many template parameter lists, complain about that now.
1367 if (Idx != NumParamLists - 1) {
1368 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001369 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001370 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001371 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1372 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001373 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1374 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001375
1376 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1377 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1378 diag::note_explicit_template_spec_does_not_need_header)
1379 << ExplicitSpecializationsInSpecifier.back();
1380 ExplicitSpecializationsInSpecifier.pop_back();
1381 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001382
1383 // We have a template parameter list with no corresponding scope, which
1384 // means that the resulting template declaration can't be instantiated
1385 // properly (we'll end up with dependent nodes when we shouldn't).
1386 if (!isExplicitSpecHeader)
1387 Invalid = true;
1388
Douglas Gregord8d297c2009-07-21 23:53:31 +00001389 ++Idx;
1390 }
1391 }
Mike Stump11289f42009-09-09 15:08:12 +00001392
Douglas Gregord8d297c2009-07-21 23:53:31 +00001393 // Return the last template parameter list, which corresponds to the
1394 // entity being declared.
1395 return ParamLists[NumParamLists - 1];
1396}
1397
Douglas Gregordc572a32009-03-30 22:58:21 +00001398QualType Sema::CheckTemplateIdType(TemplateName Name,
1399 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001400 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001401 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001402 if (!Template) {
1403 // The template name does not resolve to a template, so we just
1404 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001405 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001406 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001407
Douglas Gregorc40290e2009-03-09 23:48:35 +00001408 // Check that the template argument list is well-formed for this
1409 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001410 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001411 TemplateArgs.size());
1412 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001413 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001414 return QualType();
1415
Mike Stump11289f42009-09-09 15:08:12 +00001416 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001417 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001418 "Converted template argument list is too short!");
1419
1420 QualType CanonType;
1421
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001422 if (Name.isDependent() ||
1423 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001424 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001425 // This class template specialization is a dependent
1426 // type. Therefore, its canonical type is another class template
1427 // specialization type that contains all of the converted
1428 // arguments in canonical form. This ensures that, e.g., A<T> and
1429 // A<T, T> have identical types when A is declared as:
1430 //
1431 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001432 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001433 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001434 Converted.getFlatArguments(),
1435 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001436
Douglas Gregora8e02e72009-07-28 23:00:59 +00001437 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001438 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001439 // In the future, we need to teach getTemplateSpecializationType to only
1440 // build the canonical type and return that to us.
1441 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001442
1443 // This might work out to be a current instantiation, in which
1444 // case the canonical type needs to be the InjectedClassNameType.
1445 //
1446 // TODO: in theory this could be a simple hashtable lookup; most
1447 // changes to CurContext don't change the set of current
1448 // instantiations.
1449 if (isa<ClassTemplateDecl>(Template)) {
1450 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1451 // If we get out to a namespace, we're done.
1452 if (Ctx->isFileContext()) break;
1453
1454 // If this isn't a record, keep looking.
1455 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1456 if (!Record) continue;
1457
1458 // Look for one of the two cases with InjectedClassNameTypes
1459 // and check whether it's the same template.
1460 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1461 !Record->getDescribedClassTemplate())
1462 continue;
1463
1464 // Fetch the injected class name type and check whether its
1465 // injected type is equal to the type we just built.
1466 QualType ICNT = Context.getTypeDeclType(Record);
1467 QualType Injected = cast<InjectedClassNameType>(ICNT)
1468 ->getInjectedSpecializationType();
1469
1470 if (CanonType != Injected->getCanonicalTypeInternal())
1471 continue;
1472
1473 // If so, the canonical type of this TST is the injected
1474 // class name type of the record we just found.
1475 assert(ICNT.isCanonical());
1476 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001477 break;
1478 }
1479 }
Mike Stump11289f42009-09-09 15:08:12 +00001480 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001481 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001482 // Find the class template specialization declaration that
1483 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001484 void *InsertPos = 0;
1485 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001486 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1487 Converted.flatSize(), InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001488 if (!Decl) {
1489 // This is the first time we have referenced this class template
1490 // specialization. Create the canonical declaration and add it to
1491 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001492 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001493 ClassTemplate->getTemplatedDecl()->getTagKind(),
1494 ClassTemplate->getDeclContext(),
1495 ClassTemplate->getLocation(),
1496 ClassTemplate,
1497 Converted, 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001498 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001499 Decl->setLexicalDeclContext(CurContext);
1500 }
1501
1502 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001503 assert(isa<RecordType>(CanonType) &&
1504 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001505 }
Mike Stump11289f42009-09-09 15:08:12 +00001506
Douglas Gregorc40290e2009-03-09 23:48:35 +00001507 // Build the fully-sugared type for this class template
1508 // specialization, which refers back to the class template
1509 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001510 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001511}
1512
Douglas Gregor67a65642009-02-17 23:15:12 +00001513Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001514Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001515 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001516 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001517 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001518 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001519
Douglas Gregorc40290e2009-03-09 23:48:35 +00001520 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001521 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001522 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001523
John McCall6b51f282009-11-23 01:53:49 +00001524 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001525 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001526
1527 if (Result.isNull())
1528 return true;
1529
John McCallbcd03502009-12-07 02:54:59 +00001530 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001531 TemplateSpecializationTypeLoc TL
1532 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1533 TL.setTemplateNameLoc(TemplateLoc);
1534 TL.setLAngleLoc(LAngleLoc);
1535 TL.setRAngleLoc(RAngleLoc);
1536 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1537 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1538
1539 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001540}
John McCall06f6fe8d2009-09-04 01:14:41 +00001541
John McCalld8fe9af2009-09-08 17:47:29 +00001542Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1543 TagUseKind TUK,
1544 DeclSpec::TST TagSpec,
1545 SourceLocation TagLoc) {
1546 if (TypeResult.isInvalid())
1547 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001548
John McCall0ad16662009-10-29 08:12:44 +00001549 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001550 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001551 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001552
John McCalld8fe9af2009-09-08 17:47:29 +00001553 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001554 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001555
John McCalld8fe9af2009-09-08 17:47:29 +00001556 if (const RecordType *RT = Type->getAs<RecordType>()) {
1557 RecordDecl *D = RT->getDecl();
1558
1559 IdentifierInfo *Id = D->getIdentifier();
1560 assert(Id && "templated class must have an identifier");
1561
1562 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1563 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001564 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001565 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001566 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001567 }
1568 }
1569
Abramo Bagnara6150c882010-05-11 21:36:43 +00001570 ElaboratedTypeKeyword Keyword
1571 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1572 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001573
1574 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001575}
1576
John McCalle66edc12009-11-24 19:00:30 +00001577Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1578 LookupResult &R,
1579 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001580 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001581 // FIXME: Can we do any checking at this point? I guess we could check the
1582 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001583 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001584 // though.
John McCalle66edc12009-11-24 19:00:30 +00001585
1586 // These should be filtered out by our callers.
1587 assert(!R.empty() && "empty lookup results when building templateid");
1588 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1589
1590 NestedNameSpecifier *Qualifier = 0;
1591 SourceRange QualifierRange;
1592 if (SS.isSet()) {
1593 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1594 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001595 }
John McCall58cc69d2010-01-27 01:50:18 +00001596
1597 // We don't want lookup warnings at this point.
1598 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001599
John McCalle66edc12009-11-24 19:00:30 +00001600 bool Dependent
1601 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1602 &TemplateArgs);
1603 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001604 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001605 Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001606 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001607 RequiresADL, TemplateArgs,
1608 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001609
1610 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001611}
1612
John McCalle66edc12009-11-24 19:00:30 +00001613// We actually only call this from template instantiation.
1614Sema::OwningExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001615Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001616 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +00001617 const TemplateArgumentListInfo &TemplateArgs) {
1618 DeclContext *DC;
1619 if (!(DC = computeDeclContext(SS, false)) ||
1620 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001621 RequireCompleteDeclContext(SS, DC))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001622 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001623
Douglas Gregor786123d2010-05-21 23:18:07 +00001624 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001625 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001626 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1627 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001628
John McCalle66edc12009-11-24 19:00:30 +00001629 if (R.isAmbiguous())
1630 return ExprError();
1631
1632 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001633 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1634 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001635 return ExprError();
1636 }
1637
1638 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001639 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1640 << (NestedNameSpecifier*) SS.getScopeRep()
1641 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001642 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1643 return ExprError();
1644 }
1645
1646 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001647}
1648
Douglas Gregorb67535d2009-03-31 00:43:58 +00001649/// \brief Form a dependent template name.
1650///
1651/// This action forms a dependent template name given the template
1652/// name and its (presumably dependent) scope specifier. For
1653/// example, given "MetaFun::template apply", the scope specifier \p
1654/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1655/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregorbb119652010-06-16 23:00:59 +00001656TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1657 SourceLocation TemplateKWLoc,
1658 CXXScopeSpec &SS,
1659 UnqualifiedId &Name,
1660 TypeTy *ObjectType,
1661 bool EnteringContext,
1662 TemplateTy &Result) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001663 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1664 !getLangOptions().CPlusPlus0x)
1665 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1666 << FixItHint::CreateRemoval(TemplateKWLoc);
1667
Douglas Gregor9abe2372010-01-19 16:01:07 +00001668 DeclContext *LookupCtx = 0;
1669 if (SS.isSet())
1670 LookupCtx = computeDeclContext(SS, EnteringContext);
1671 if (!LookupCtx && ObjectType)
1672 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1673 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001674 // C++0x [temp.names]p5:
1675 // If a name prefixed by the keyword template is not the name of
1676 // a template, the program is ill-formed. [Note: the keyword
1677 // template may not be applied to non-template members of class
1678 // templates. -end note ] [ Note: as is the case with the
1679 // typename prefix, the template prefix is allowed in cases
1680 // where it is not strictly necessary; i.e., when the
1681 // nested-name-specifier or the expression on the left of the ->
1682 // or . is not dependent on a template-parameter, or the use
1683 // does not appear in the scope of a template. -end note]
1684 //
1685 // Note: C++03 was more strict here, because it banned the use of
1686 // the "template" keyword prior to a template-name that was not a
1687 // dependent name. C++ DR468 relaxed this requirement (the
1688 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001689 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00001690 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001691 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1692 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00001693 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001694 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1695 isa<CXXRecordDecl>(LookupCtx) &&
1696 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregorbb119652010-06-16 23:00:59 +00001697 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00001698 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001699 Diag(Name.getSourceRange().getBegin(),
1700 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001701 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001702 << Name.getSourceRange()
1703 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001704 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00001705 } else {
1706 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00001707 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001708 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001709 }
1710
Mike Stump11289f42009-09-09 15:08:12 +00001711 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001712 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001713
1714 switch (Name.getKind()) {
1715 case UnqualifiedId::IK_Identifier:
Douglas Gregorbb119652010-06-16 23:00:59 +00001716 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1717 Name.Identifier));
1718 return TNK_Dependent_template_name;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001719
Douglas Gregor71395fa2009-11-04 00:56:37 +00001720 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00001721 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001722 Name.OperatorFunctionId.Operator));
Douglas Gregorbb119652010-06-16 23:00:59 +00001723 return TNK_Dependent_template_name;
Alexis Hunted0530f2009-11-28 08:58:14 +00001724
1725 case UnqualifiedId::IK_LiteralOperatorId:
1726 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1727
Douglas Gregor3cf81312009-11-03 23:16:33 +00001728 default:
1729 break;
1730 }
1731
1732 Diag(Name.getSourceRange().getBegin(),
1733 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001734 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001735 << Name.getSourceRange()
1736 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001737 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001738}
1739
Mike Stump11289f42009-09-09 15:08:12 +00001740bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001741 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001742 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001743 const TemplateArgument &Arg = AL.getArgument();
1744
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001745 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001746 switch(Arg.getKind()) {
1747 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001748 // C++ [temp.arg.type]p1:
1749 // A template-argument for a template-parameter which is a
1750 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001751 break;
1752 case TemplateArgument::Template: {
1753 // We have a template type parameter but the template argument
1754 // is a template without any arguments.
1755 SourceRange SR = AL.getSourceRange();
1756 TemplateName Name = Arg.getAsTemplate();
1757 Diag(SR.getBegin(), diag::err_template_missing_args)
1758 << Name << SR;
1759 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1760 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001761
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001762 return true;
1763 }
1764 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001765 // We have a template type parameter but the template argument
1766 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001767 SourceRange SR = AL.getSourceRange();
1768 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001769 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001770
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001771 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001772 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001773 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001774
John McCallbcd03502009-12-07 02:54:59 +00001775 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001776 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001777
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001778 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001779 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001780 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001781 return false;
1782}
1783
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001784/// \brief Substitute template arguments into the default template argument for
1785/// the given template type parameter.
1786///
1787/// \param SemaRef the semantic analysis object for which we are performing
1788/// the substitution.
1789///
1790/// \param Template the template that we are synthesizing template arguments
1791/// for.
1792///
1793/// \param TemplateLoc the location of the template name that started the
1794/// template-id we are checking.
1795///
1796/// \param RAngleLoc the location of the right angle bracket ('>') that
1797/// terminates the template-id.
1798///
1799/// \param Param the template template parameter whose default we are
1800/// substituting into.
1801///
1802/// \param Converted the list of template arguments provided for template
1803/// parameters that precede \p Param in the template parameter list.
1804///
1805/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001806static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001807SubstDefaultTemplateArgument(Sema &SemaRef,
1808 TemplateDecl *Template,
1809 SourceLocation TemplateLoc,
1810 SourceLocation RAngleLoc,
1811 TemplateTypeParmDecl *Param,
1812 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001813 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001814
1815 // If the argument type is dependent, instantiate it now based
1816 // on the previously-computed template arguments.
1817 if (ArgType->getType()->isDependentType()) {
1818 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1819 /*TakeArgs=*/false);
1820
1821 MultiLevelTemplateArgumentList AllTemplateArgs
1822 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1823
1824 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1825 Template, Converted.getFlatArguments(),
1826 Converted.flatSize(),
1827 SourceRange(TemplateLoc, RAngleLoc));
1828
1829 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1830 Param->getDefaultArgumentLoc(),
1831 Param->getDeclName());
1832 }
1833
1834 return ArgType;
1835}
1836
1837/// \brief Substitute template arguments into the default template argument for
1838/// the given non-type template parameter.
1839///
1840/// \param SemaRef the semantic analysis object for which we are performing
1841/// the substitution.
1842///
1843/// \param Template the template that we are synthesizing template arguments
1844/// for.
1845///
1846/// \param TemplateLoc the location of the template name that started the
1847/// template-id we are checking.
1848///
1849/// \param RAngleLoc the location of the right angle bracket ('>') that
1850/// terminates the template-id.
1851///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001852/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001853/// substituting into.
1854///
1855/// \param Converted the list of template arguments provided for template
1856/// parameters that precede \p Param in the template parameter list.
1857///
1858/// \returns the substituted template argument, or NULL if an error occurred.
1859static Sema::OwningExprResult
1860SubstDefaultTemplateArgument(Sema &SemaRef,
1861 TemplateDecl *Template,
1862 SourceLocation TemplateLoc,
1863 SourceLocation RAngleLoc,
1864 NonTypeTemplateParmDecl *Param,
1865 TemplateArgumentListBuilder &Converted) {
1866 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1867 /*TakeArgs=*/false);
1868
1869 MultiLevelTemplateArgumentList AllTemplateArgs
1870 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1871
1872 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1873 Template, Converted.getFlatArguments(),
1874 Converted.flatSize(),
1875 SourceRange(TemplateLoc, RAngleLoc));
1876
1877 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1878}
1879
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001880/// \brief Substitute template arguments into the default template argument for
1881/// the given template template parameter.
1882///
1883/// \param SemaRef the semantic analysis object for which we are performing
1884/// the substitution.
1885///
1886/// \param Template the template that we are synthesizing template arguments
1887/// for.
1888///
1889/// \param TemplateLoc the location of the template name that started the
1890/// template-id we are checking.
1891///
1892/// \param RAngleLoc the location of the right angle bracket ('>') that
1893/// terminates the template-id.
1894///
1895/// \param Param the template template parameter whose default we are
1896/// substituting into.
1897///
1898/// \param Converted the list of template arguments provided for template
1899/// parameters that precede \p Param in the template parameter list.
1900///
1901/// \returns the substituted template argument, or NULL if an error occurred.
1902static TemplateName
1903SubstDefaultTemplateArgument(Sema &SemaRef,
1904 TemplateDecl *Template,
1905 SourceLocation TemplateLoc,
1906 SourceLocation RAngleLoc,
1907 TemplateTemplateParmDecl *Param,
1908 TemplateArgumentListBuilder &Converted) {
1909 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1910 /*TakeArgs=*/false);
1911
1912 MultiLevelTemplateArgumentList AllTemplateArgs
1913 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1914
1915 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1916 Template, Converted.getFlatArguments(),
1917 Converted.flatSize(),
1918 SourceRange(TemplateLoc, RAngleLoc));
1919
1920 return SemaRef.SubstTemplateName(
1921 Param->getDefaultArgument().getArgument().getAsTemplate(),
1922 Param->getDefaultArgument().getTemplateNameLoc(),
1923 AllTemplateArgs);
1924}
1925
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001926/// \brief If the given template parameter has a default template
1927/// argument, substitute into that default template argument and
1928/// return the corresponding template argument.
1929TemplateArgumentLoc
1930Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1931 SourceLocation TemplateLoc,
1932 SourceLocation RAngleLoc,
1933 Decl *Param,
1934 TemplateArgumentListBuilder &Converted) {
1935 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1936 if (!TypeParm->hasDefaultArgument())
1937 return TemplateArgumentLoc();
1938
John McCallbcd03502009-12-07 02:54:59 +00001939 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001940 TemplateLoc,
1941 RAngleLoc,
1942 TypeParm,
1943 Converted);
1944 if (DI)
1945 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1946
1947 return TemplateArgumentLoc();
1948 }
1949
1950 if (NonTypeTemplateParmDecl *NonTypeParm
1951 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1952 if (!NonTypeParm->hasDefaultArgument())
1953 return TemplateArgumentLoc();
1954
1955 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1956 TemplateLoc,
1957 RAngleLoc,
1958 NonTypeParm,
1959 Converted);
1960 if (Arg.isInvalid())
1961 return TemplateArgumentLoc();
1962
1963 Expr *ArgE = Arg.takeAs<Expr>();
1964 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1965 }
1966
1967 TemplateTemplateParmDecl *TempTempParm
1968 = cast<TemplateTemplateParmDecl>(Param);
1969 if (!TempTempParm->hasDefaultArgument())
1970 return TemplateArgumentLoc();
1971
1972 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1973 TemplateLoc,
1974 RAngleLoc,
1975 TempTempParm,
1976 Converted);
1977 if (TName.isNull())
1978 return TemplateArgumentLoc();
1979
1980 return TemplateArgumentLoc(TemplateArgument(TName),
1981 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1982 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1983}
1984
Douglas Gregorda0fb532009-11-11 19:31:23 +00001985/// \brief Check that the given template argument corresponds to the given
1986/// template parameter.
1987bool Sema::CheckTemplateArgument(NamedDecl *Param,
1988 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001989 TemplateDecl *Template,
1990 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001991 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001992 TemplateArgumentListBuilder &Converted,
1993 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001994 // Check template type parameters.
1995 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001996 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001997
Douglas Gregoreebed722009-11-11 19:41:09 +00001998 // Check non-type template parameters.
1999 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002000 // Do substitution on the type of the non-type template parameter
2001 // with the template arguments we've seen thus far.
2002 QualType NTTPType = NTTP->getType();
2003 if (NTTPType->isDependentType()) {
2004 // Do substitution on the type of the non-type template parameter.
2005 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2006 NTTP, Converted.getFlatArguments(),
2007 Converted.flatSize(),
2008 SourceRange(TemplateLoc, RAngleLoc));
2009
2010 TemplateArgumentList TemplateArgs(Context, Converted,
2011 /*TakeArgs=*/false);
2012 NTTPType = SubstType(NTTPType,
2013 MultiLevelTemplateArgumentList(TemplateArgs),
2014 NTTP->getLocation(),
2015 NTTP->getDeclName());
2016 // If that worked, check the non-type template parameter type
2017 // for validity.
2018 if (!NTTPType.isNull())
2019 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2020 NTTP->getLocation());
2021 if (NTTPType.isNull())
2022 return true;
2023 }
2024
2025 switch (Arg.getArgument().getKind()) {
2026 case TemplateArgument::Null:
2027 assert(false && "Should never see a NULL template argument here");
2028 return true;
2029
2030 case TemplateArgument::Expression: {
2031 Expr *E = Arg.getArgument().getAsExpr();
2032 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002033 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002034 return true;
2035
2036 Converted.Append(Result);
2037 break;
2038 }
2039
2040 case TemplateArgument::Declaration:
2041 case TemplateArgument::Integral:
2042 // We've already checked this template argument, so just copy
2043 // it to the list of converted arguments.
2044 Converted.Append(Arg.getArgument());
2045 break;
2046
2047 case TemplateArgument::Template:
2048 // We were given a template template argument. It may not be ill-formed;
2049 // see below.
2050 if (DependentTemplateName *DTN
2051 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2052 // We have a template argument such as \c T::template X, which we
2053 // parsed as a template template argument. However, since we now
2054 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002055 // template name into an expression.
2056
2057 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2058 Arg.getTemplateNameLoc());
2059
John McCalle66edc12009-11-24 19:00:30 +00002060 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2061 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002062 Arg.getTemplateQualifierRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002063 NameInfo);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002064
2065 TemplateArgument Result;
2066 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2067 return true;
2068
2069 Converted.Append(Result);
2070 break;
2071 }
2072
2073 // We have a template argument that actually does refer to a class
2074 // template, template alias, or template template parameter, and
2075 // therefore cannot be a non-type template argument.
2076 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2077 << Arg.getSourceRange();
2078
2079 Diag(Param->getLocation(), diag::note_template_param_here);
2080 return true;
2081
2082 case TemplateArgument::Type: {
2083 // We have a non-type template parameter but the template
2084 // argument is a type.
2085
2086 // C++ [temp.arg]p2:
2087 // In a template-argument, an ambiguity between a type-id and
2088 // an expression is resolved to a type-id, regardless of the
2089 // form of the corresponding template-parameter.
2090 //
2091 // We warn specifically about this case, since it can be rather
2092 // confusing for users.
2093 QualType T = Arg.getArgument().getAsType();
2094 SourceRange SR = Arg.getSourceRange();
2095 if (T->isFunctionType())
2096 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2097 else
2098 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2099 Diag(Param->getLocation(), diag::note_template_param_here);
2100 return true;
2101 }
2102
2103 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002104 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002105 break;
2106 }
2107
2108 return false;
2109 }
2110
2111
2112 // Check template template parameters.
2113 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2114
2115 // Substitute into the template parameter list of the template
2116 // template parameter, since previously-supplied template arguments
2117 // may appear within the template template parameter.
2118 {
2119 // Set up a template instantiation context.
2120 LocalInstantiationScope Scope(*this);
2121 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2122 TempParm, Converted.getFlatArguments(),
2123 Converted.flatSize(),
2124 SourceRange(TemplateLoc, RAngleLoc));
2125
2126 TemplateArgumentList TemplateArgs(Context, Converted,
2127 /*TakeArgs=*/false);
2128 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2129 SubstDecl(TempParm, CurContext,
2130 MultiLevelTemplateArgumentList(TemplateArgs)));
2131 if (!TempParm)
2132 return true;
2133
2134 // FIXME: TempParam is leaked.
2135 }
2136
2137 switch (Arg.getArgument().getKind()) {
2138 case TemplateArgument::Null:
2139 assert(false && "Should never see a NULL template argument here");
2140 return true;
2141
2142 case TemplateArgument::Template:
2143 if (CheckTemplateArgument(TempParm, Arg))
2144 return true;
2145
2146 Converted.Append(Arg.getArgument());
2147 break;
2148
2149 case TemplateArgument::Expression:
2150 case TemplateArgument::Type:
2151 // We have a template template parameter but the template
2152 // argument does not refer to a template.
2153 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2154 return true;
2155
2156 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002157 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002158 "Declaration argument with template template parameter");
2159 break;
2160 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002161 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002162 "Integral argument with template template parameter");
2163 break;
2164
2165 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002166 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002167 break;
2168 }
2169
2170 return false;
2171}
2172
Douglas Gregord32e0282009-02-09 23:23:08 +00002173/// \brief Check that the given template argument list is well-formed
2174/// for specializing the given template.
2175bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2176 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002177 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002178 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002179 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002180 TemplateParameterList *Params = Template->getTemplateParameters();
2181 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002182 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002183 bool Invalid = false;
2184
John McCall6b51f282009-11-23 01:53:49 +00002185 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2186
Mike Stump11289f42009-09-09 15:08:12 +00002187 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002188 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002189
Anders Carlsson15201f12009-06-13 02:08:00 +00002190 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002191 (NumArgs < Params->getMinRequiredArguments() &&
2192 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002193 // FIXME: point at either the first arg beyond what we can handle,
2194 // or the '>', depending on whether we have too many or too few
2195 // arguments.
2196 SourceRange Range;
2197 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002198 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002199 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2200 << (NumArgs > NumParams)
2201 << (isa<ClassTemplateDecl>(Template)? 0 :
2202 isa<FunctionTemplateDecl>(Template)? 1 :
2203 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2204 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002205 Diag(Template->getLocation(), diag::note_template_decl_here)
2206 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002207 Invalid = true;
2208 }
Mike Stump11289f42009-09-09 15:08:12 +00002209
2210 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002211 // [...] The type and form of each template-argument specified in
2212 // a template-id shall match the type and form specified for the
2213 // corresponding parameter declared by the template in its
2214 // template-parameter-list.
2215 unsigned ArgIdx = 0;
2216 for (TemplateParameterList::iterator Param = Params->begin(),
2217 ParamEnd = Params->end();
2218 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002219 if (ArgIdx > NumArgs && PartialTemplateArgs)
2220 break;
Mike Stump11289f42009-09-09 15:08:12 +00002221
Douglas Gregoreebed722009-11-11 19:41:09 +00002222 // If we have a template parameter pack, check every remaining template
2223 // argument against that template parameter pack.
2224 if ((*Param)->isTemplateParameterPack()) {
2225 Converted.BeginPack();
2226 for (; ArgIdx < NumArgs; ++ArgIdx) {
2227 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2228 TemplateLoc, RAngleLoc, Converted)) {
2229 Invalid = true;
2230 break;
2231 }
2232 }
2233 Converted.EndPack();
2234 continue;
2235 }
2236
Douglas Gregor84d49a22009-11-11 21:54:23 +00002237 if (ArgIdx < NumArgs) {
2238 // Check the template argument we were given.
2239 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2240 TemplateLoc, RAngleLoc, Converted))
2241 return true;
2242
2243 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002244 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002245
Douglas Gregor84d49a22009-11-11 21:54:23 +00002246 // We have a default template argument that we will use.
2247 TemplateArgumentLoc Arg;
2248
2249 // Retrieve the default template argument from the template
2250 // parameter. For each kind of template parameter, we substitute the
2251 // template arguments provided thus far and any "outer" template arguments
2252 // (when the template parameter was part of a nested template) into
2253 // the default argument.
2254 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2255 if (!TTP->hasDefaultArgument()) {
2256 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2257 break;
2258 }
2259
John McCallbcd03502009-12-07 02:54:59 +00002260 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002261 Template,
2262 TemplateLoc,
2263 RAngleLoc,
2264 TTP,
2265 Converted);
2266 if (!ArgType)
2267 return true;
2268
2269 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2270 ArgType);
2271 } else if (NonTypeTemplateParmDecl *NTTP
2272 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2273 if (!NTTP->hasDefaultArgument()) {
2274 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2275 break;
2276 }
2277
2278 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2279 TemplateLoc,
2280 RAngleLoc,
2281 NTTP,
2282 Converted);
2283 if (E.isInvalid())
2284 return true;
2285
2286 Expr *Ex = E.takeAs<Expr>();
2287 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2288 } else {
2289 TemplateTemplateParmDecl *TempParm
2290 = cast<TemplateTemplateParmDecl>(*Param);
2291
2292 if (!TempParm->hasDefaultArgument()) {
2293 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2294 break;
2295 }
2296
2297 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2298 TemplateLoc,
2299 RAngleLoc,
2300 TempParm,
2301 Converted);
2302 if (Name.isNull())
2303 return true;
2304
2305 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2306 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2307 TempParm->getDefaultArgument().getTemplateNameLoc());
2308 }
2309
2310 // Introduce an instantiation record that describes where we are using
2311 // the default template argument.
2312 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2313 Converted.getFlatArguments(),
2314 Converted.flatSize(),
2315 SourceRange(TemplateLoc, RAngleLoc));
2316
2317 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002318 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002319 RAngleLoc, Converted))
2320 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002321 }
2322
2323 return Invalid;
2324}
2325
2326/// \brief Check a template argument against its corresponding
2327/// template type parameter.
2328///
2329/// This routine implements the semantics of C++ [temp.arg.type]. It
2330/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002331bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002332 TypeSourceInfo *ArgInfo) {
2333 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002334 QualType Arg = ArgInfo->getType();
2335
Douglas Gregord32e0282009-02-09 23:23:08 +00002336 // C++ [temp.arg.type]p2:
2337 // A local type, a type with no linkage, an unnamed type or a type
2338 // compounded from any of these types shall not be used as a
2339 // template-argument for a template type-parameter.
2340 //
Douglas Gregor959d5a02010-05-22 16:17:30 +00002341 // FIXME: Perform the unnamed type check.
2342 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002343 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002344 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002345 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002346 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002347 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002348 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002349 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00002350 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2351 << QualType(Tag, 0) << SR;
2352 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002353 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002354 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002355 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2356 return true;
Douglas Gregor959d5a02010-05-22 16:17:30 +00002357 } else if (Arg->isVariablyModifiedType()) {
2358 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2359 << Arg;
2360 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002361 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002362 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002363 }
2364
2365 return false;
2366}
2367
Douglas Gregorccb07762009-02-11 19:52:55 +00002368/// \brief Checks whether the given template argument is the address
2369/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002370static bool
2371CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2372 NonTypeTemplateParmDecl *Param,
2373 QualType ParamType,
2374 Expr *ArgIn,
2375 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002376 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002377 Expr *Arg = ArgIn;
2378 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002379
2380 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002381 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002382 Arg = Cast->getSubExpr();
2383
2384 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002385 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002386 // A template-argument for a non-type, non-template
2387 // template-parameter shall be one of: [...]
2388 //
2389 // -- the address of an object or function with external
2390 // linkage, including function templates and function
2391 // template-ids but excluding non-static class members,
2392 // expressed as & id-expression where the & is optional if
2393 // the name refers to a function or array, or if the
2394 // corresponding template-parameter is a reference; or
2395 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002396
Douglas Gregorccb07762009-02-11 19:52:55 +00002397 // Ignore (and complain about) any excess parentheses.
2398 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2399 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002400 S.Diag(Arg->getSourceRange().getBegin(),
2401 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002402 << Arg->getSourceRange();
2403 Invalid = true;
2404 }
2405
2406 Arg = Parens->getSubExpr();
2407 }
2408
Douglas Gregorb242683d2010-04-01 18:32:35 +00002409 bool AddressTaken = false;
2410 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002411 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002412 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002413 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002414 AddressTaken = true;
2415 AddrOpLoc = UnOp->getOperatorLoc();
2416 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002417 } else
2418 DRE = dyn_cast<DeclRefExpr>(Arg);
2419
Douglas Gregorb242683d2010-04-01 18:32:35 +00002420 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002421 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2422 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002423 S.Diag(Param->getLocation(), diag::note_template_param_here);
2424 return true;
2425 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002426
2427 // Stop checking the precise nature of the argument if it is value dependent,
2428 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002429 if (Arg->isValueDependent()) {
2430 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002431 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002432 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002433
Douglas Gregorb242683d2010-04-01 18:32:35 +00002434 if (!isa<ValueDecl>(DRE->getDecl())) {
2435 S.Diag(Arg->getSourceRange().getBegin(),
2436 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002437 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002438 S.Diag(Param->getLocation(), diag::note_template_param_here);
2439 return true;
2440 }
2441
2442 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002443
2444 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002445 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2446 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002447 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002448 S.Diag(Param->getLocation(), diag::note_template_param_here);
2449 return true;
2450 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002451
2452 // Cannot refer to non-static member functions
2453 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002454 if (!Method->isStatic()) {
2455 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002456 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002457 S.Diag(Param->getLocation(), diag::note_template_param_here);
2458 return true;
2459 }
Mike Stump11289f42009-09-09 15:08:12 +00002460
Douglas Gregorccb07762009-02-11 19:52:55 +00002461 // Functions must have external linkage.
2462 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002463 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002464 S.Diag(Arg->getSourceRange().getBegin(),
2465 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002466 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002467 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002468 << true;
2469 return true;
2470 }
2471
2472 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002473 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002474
Douglas Gregorb242683d2010-04-01 18:32:35 +00002475 // If the template parameter has pointer type, the function decays.
2476 if (ParamType->isPointerType() && !AddressTaken)
2477 ArgType = S.Context.getPointerType(Func->getType());
2478 else if (AddressTaken && ParamType->isReferenceType()) {
2479 // If we originally had an address-of operator, but the
2480 // parameter has reference type, complain and (if things look
2481 // like they will work) drop the address-of operator.
2482 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2483 ParamType.getNonReferenceType())) {
2484 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2485 << ParamType;
2486 S.Diag(Param->getLocation(), diag::note_template_param_here);
2487 return true;
2488 }
2489
2490 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2491 << ParamType
2492 << FixItHint::CreateRemoval(AddrOpLoc);
2493 S.Diag(Param->getLocation(), diag::note_template_param_here);
2494
2495 ArgType = Func->getType();
2496 }
2497 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002498 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002499 S.Diag(Arg->getSourceRange().getBegin(),
2500 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002501 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002502 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002503 << true;
2504 return true;
2505 }
2506
Douglas Gregorb242683d2010-04-01 18:32:35 +00002507 // A value of reference type is not an object.
2508 if (Var->getType()->isReferenceType()) {
2509 S.Diag(Arg->getSourceRange().getBegin(),
2510 diag::err_template_arg_reference_var)
2511 << Var->getType() << Arg->getSourceRange();
2512 S.Diag(Param->getLocation(), diag::note_template_param_here);
2513 return true;
2514 }
2515
Douglas Gregorccb07762009-02-11 19:52:55 +00002516 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002517 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002518
2519 // If the template parameter has pointer type, we must have taken
2520 // the address of this object.
2521 if (ParamType->isReferenceType()) {
2522 if (AddressTaken) {
2523 // If we originally had an address-of operator, but the
2524 // parameter has reference type, complain and (if things look
2525 // like they will work) drop the address-of operator.
2526 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2527 ParamType.getNonReferenceType())) {
2528 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2529 << ParamType;
2530 S.Diag(Param->getLocation(), diag::note_template_param_here);
2531 return true;
2532 }
2533
2534 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2535 << ParamType
2536 << FixItHint::CreateRemoval(AddrOpLoc);
2537 S.Diag(Param->getLocation(), diag::note_template_param_here);
2538
2539 ArgType = Var->getType();
2540 }
2541 } else if (!AddressTaken && ParamType->isPointerType()) {
2542 if (Var->getType()->isArrayType()) {
2543 // Array-to-pointer decay.
2544 ArgType = S.Context.getArrayDecayedType(Var->getType());
2545 } else {
2546 // If the template parameter has pointer type but the address of
2547 // this object was not taken, complain and (possibly) recover by
2548 // taking the address of the entity.
2549 ArgType = S.Context.getPointerType(Var->getType());
2550 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2551 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2552 << ParamType;
2553 S.Diag(Param->getLocation(), diag::note_template_param_here);
2554 return true;
2555 }
2556
2557 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2558 << ParamType
2559 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2560
2561 S.Diag(Param->getLocation(), diag::note_template_param_here);
2562 }
2563 }
2564 } else {
2565 // We found something else, but we don't know specifically what it is.
2566 S.Diag(Arg->getSourceRange().getBegin(),
2567 diag::err_template_arg_not_object_or_func)
2568 << Arg->getSourceRange();
2569 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2570 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002571 }
Mike Stump11289f42009-09-09 15:08:12 +00002572
Douglas Gregorb242683d2010-04-01 18:32:35 +00002573 if (ParamType->isPointerType() &&
2574 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2575 S.IsQualificationConversion(ArgType, ParamType)) {
2576 // For pointer-to-object types, qualification conversions are
2577 // permitted.
2578 } else {
2579 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2580 if (!ParamRef->getPointeeType()->isFunctionType()) {
2581 // C++ [temp.arg.nontype]p5b3:
2582 // For a non-type template-parameter of type reference to
2583 // object, no conversions apply. The type referred to by the
2584 // reference may be more cv-qualified than the (otherwise
2585 // identical) type of the template- argument. The
2586 // template-parameter is bound directly to the
2587 // template-argument, which shall be an lvalue.
2588
2589 // FIXME: Other qualifiers?
2590 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2591 unsigned ArgQuals = ArgType.getCVRQualifiers();
2592
2593 if ((ParamQuals | ArgQuals) != ParamQuals) {
2594 S.Diag(Arg->getSourceRange().getBegin(),
2595 diag::err_template_arg_ref_bind_ignores_quals)
2596 << ParamType << Arg->getType()
2597 << Arg->getSourceRange();
2598 S.Diag(Param->getLocation(), diag::note_template_param_here);
2599 return true;
2600 }
2601 }
2602 }
2603
2604 // At this point, the template argument refers to an object or
2605 // function with external linkage. We now need to check whether the
2606 // argument and parameter types are compatible.
2607 if (!S.Context.hasSameUnqualifiedType(ArgType,
2608 ParamType.getNonReferenceType())) {
2609 // We can't perform this conversion or binding.
2610 if (ParamType->isReferenceType())
2611 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2612 << ParamType << Arg->getType() << Arg->getSourceRange();
2613 else
2614 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2615 << Arg->getType() << ParamType << Arg->getSourceRange();
2616 S.Diag(Param->getLocation(), diag::note_template_param_here);
2617 return true;
2618 }
2619 }
2620
2621 // Create the template argument.
2622 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002623 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002624 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002625}
2626
2627/// \brief Checks whether the given template argument is a pointer to
2628/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002629bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2630 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002631 bool Invalid = false;
2632
2633 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002634 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002635 Arg = Cast->getSubExpr();
2636
2637 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002638 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002639 // A template-argument for a non-type, non-template
2640 // template-parameter shall be one of: [...]
2641 //
2642 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002643 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002644
2645 // Ignore (and complain about) any excess parentheses.
2646 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2647 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002648 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002649 diag::err_template_arg_extra_parens)
2650 << Arg->getSourceRange();
2651 Invalid = true;
2652 }
2653
2654 Arg = Parens->getSubExpr();
2655 }
2656
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002657 // A pointer-to-member constant written &Class::member.
2658 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002659 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2660 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2661 if (DRE && !DRE->getQualifier())
2662 DRE = 0;
2663 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002664 }
2665 // A constant of pointer-to-member type.
2666 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2667 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2668 if (VD->getType()->isMemberPointerType()) {
2669 if (isa<NonTypeTemplateParmDecl>(VD) ||
2670 (isa<VarDecl>(VD) &&
2671 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2672 if (Arg->isTypeDependent() || Arg->isValueDependent())
2673 Converted = TemplateArgument(Arg->Retain());
2674 else
2675 Converted = TemplateArgument(VD->getCanonicalDecl());
2676 return Invalid;
2677 }
2678 }
2679 }
2680
2681 DRE = 0;
2682 }
2683
Douglas Gregorccb07762009-02-11 19:52:55 +00002684 if (!DRE)
2685 return Diag(Arg->getSourceRange().getBegin(),
2686 diag::err_template_arg_not_pointer_to_member_form)
2687 << Arg->getSourceRange();
2688
2689 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2690 assert((isa<FieldDecl>(DRE->getDecl()) ||
2691 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2692 "Only non-static member pointers can make it here");
2693
2694 // Okay: this is the address of a non-static member, and therefore
2695 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002696 if (Arg->isTypeDependent() || Arg->isValueDependent())
2697 Converted = TemplateArgument(Arg->Retain());
2698 else
2699 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002700 return Invalid;
2701 }
2702
2703 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002704 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002705 diag::err_template_arg_not_pointer_to_member_form)
2706 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002707 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002708 diag::note_template_arg_refers_here);
2709 return true;
2710}
2711
Douglas Gregord32e0282009-02-09 23:23:08 +00002712/// \brief Check a template argument against its corresponding
2713/// non-type template parameter.
2714///
Douglas Gregor463421d2009-03-03 04:44:36 +00002715/// This routine implements the semantics of C++ [temp.arg.nontype].
2716/// It returns true if an error occurred, and false otherwise. \p
2717/// InstantiatedParamType is the type of the non-type template
2718/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002719///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002720/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002721bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002722 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002723 TemplateArgument &Converted,
2724 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002725 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2726
Douglas Gregor86560402009-02-10 23:36:10 +00002727 // If either the parameter has a dependent type or the argument is
2728 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002729 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2730 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002731 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002732 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002733 }
Douglas Gregor86560402009-02-10 23:36:10 +00002734
2735 // C++ [temp.arg.nontype]p5:
2736 // The following conversions are performed on each expression used
2737 // as a non-type template-argument. If a non-type
2738 // template-argument cannot be converted to the type of the
2739 // corresponding template-parameter then the program is
2740 // ill-formed.
2741 //
2742 // -- for a non-type template-parameter of integral or
2743 // enumeration type, integral promotions (4.5) and integral
2744 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002745 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002746 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00002747 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002748 // C++ [temp.arg.nontype]p1:
2749 // A template-argument for a non-type, non-template
2750 // template-parameter shall be one of:
2751 //
2752 // -- an integral constant-expression of integral or enumeration
2753 // type; or
2754 // -- the name of a non-type template-parameter; or
2755 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002756 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00002757 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002758 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002759 diag::err_template_arg_not_integral_or_enumeral)
2760 << ArgType << Arg->getSourceRange();
2761 Diag(Param->getLocation(), diag::note_template_param_here);
2762 return true;
2763 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002764 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002765 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2766 << ArgType << Arg->getSourceRange();
2767 return true;
2768 }
2769
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002770 // From here on out, all we care about are the unqualified forms
2771 // of the parameter and argument types.
2772 ParamType = ParamType.getUnqualifiedType();
2773 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002774
2775 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002776 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002777 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002778 } else if (CTAK == CTAK_Deduced) {
2779 // C++ [temp.deduct.type]p17:
2780 // If, in the declaration of a function template with a non-type
2781 // template-parameter, the non-type template- parameter is used
2782 // in an expression in the function parameter-list and, if the
2783 // corresponding template-argument is deduced, the
2784 // template-argument type shall match the type of the
2785 // template-parameter exactly, except that a template-argument
2786 // deduced from an array bound may be of any integral type.
2787 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2788 << ArgType << ParamType;
2789 Diag(Param->getLocation(), diag::note_template_param_here);
2790 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002791 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2792 !ParamType->isEnumeralType()) {
2793 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002794 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002795 } else {
2796 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002797 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002798 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002799 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002800 Diag(Param->getLocation(), diag::note_template_param_here);
2801 return true;
2802 }
2803
Douglas Gregor52aba872009-03-14 00:20:21 +00002804 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002805 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002806 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002807
2808 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002809 llvm::APSInt OldValue = Value;
2810
2811 // Coerce the template argument's value to the value it will have
2812 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002813 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002814 if (Value.getBitWidth() != AllowedBits)
2815 Value.extOrTrunc(AllowedBits);
2816 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002817
2818 // Complain if an unsigned parameter received a negative value.
2819 if (IntegerType->isUnsignedIntegerType()
2820 && (OldValue.isSigned() && OldValue.isNegative())) {
2821 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2822 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2823 << Arg->getSourceRange();
2824 Diag(Param->getLocation(), diag::note_template_param_here);
2825 }
2826
2827 // Complain if we overflowed the template parameter's type.
2828 unsigned RequiredBits;
2829 if (IntegerType->isUnsignedIntegerType())
2830 RequiredBits = OldValue.getActiveBits();
2831 else if (OldValue.isUnsigned())
2832 RequiredBits = OldValue.getActiveBits() + 1;
2833 else
2834 RequiredBits = OldValue.getMinSignedBits();
2835 if (RequiredBits > AllowedBits) {
2836 Diag(Arg->getSourceRange().getBegin(),
2837 diag::warn_template_arg_too_large)
2838 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2839 << Arg->getSourceRange();
2840 Diag(Param->getLocation(), diag::note_template_param_here);
2841 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002842 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002843
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002844 // Add the value of this argument to the list of converted
2845 // arguments. We use the bitwidth and signedness of the template
2846 // parameter.
2847 if (Arg->isValueDependent()) {
2848 // The argument is value-dependent. Create a new
2849 // TemplateArgument with the converted expression.
2850 Converted = TemplateArgument(Arg);
2851 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002852 }
2853
John McCall0ad16662009-10-29 08:12:44 +00002854 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002855 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002856 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002857 return false;
2858 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002859
John McCall16df1e52010-03-30 21:47:33 +00002860 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2861
Douglas Gregorb242683d2010-04-01 18:32:35 +00002862 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2863 // from a template argument of type std::nullptr_t to a non-type
2864 // template parameter of type pointer to object, pointer to
2865 // function, or pointer-to-member, respectively.
2866 if (ArgType->isNullPtrType() &&
2867 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2868 Converted = TemplateArgument((NamedDecl *)0);
2869 return false;
2870 }
2871
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002872 // Handle pointer-to-function, reference-to-function, and
2873 // pointer-to-member-function all in (roughly) the same way.
2874 if (// -- For a non-type template-parameter of type pointer to
2875 // function, only the function-to-pointer conversion (4.3) is
2876 // applied. If the template-argument represents a set of
2877 // overloaded functions (or a pointer to such), the matching
2878 // function is selected from the set (13.4).
2879 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002880 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002881 // -- For a non-type template-parameter of type reference to
2882 // function, no conversions apply. If the template-argument
2883 // represents a set of overloaded functions, the matching
2884 // function is selected from the set (13.4).
2885 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002886 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002887 // -- For a non-type template-parameter of type pointer to
2888 // member function, no conversions apply. If the
2889 // template-argument represents a set of overloaded member
2890 // functions, the matching member function is selected from
2891 // the set (13.4).
2892 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002893 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002894 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002895
Douglas Gregor064fdb22010-04-14 23:11:21 +00002896 if (Arg->getType() == Context.OverloadTy) {
2897 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2898 true,
2899 FoundResult)) {
2900 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2901 return true;
2902
2903 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2904 ArgType = Arg->getType();
2905 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002906 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002907 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002908
Douglas Gregorb242683d2010-04-01 18:32:35 +00002909 if (!ParamType->isMemberPointerType())
2910 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2911 ParamType,
2912 Arg, Converted);
2913
2914 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002915 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00002916 } else if (!Context.hasSameUnqualifiedType(ArgType,
2917 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002918 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002919 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002920 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002921 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002922 Diag(Param->getLocation(), diag::note_template_param_here);
2923 return true;
2924 }
Mike Stump11289f42009-09-09 15:08:12 +00002925
Douglas Gregorb242683d2010-04-01 18:32:35 +00002926 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002927 }
2928
Chris Lattner696197c2009-02-20 21:37:53 +00002929 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002930 // -- for a non-type template-parameter of type pointer to
2931 // object, qualification conversions (4.4) and the
2932 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002933 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00002934 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002935 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002936
Douglas Gregorb242683d2010-04-01 18:32:35 +00002937 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2938 ParamType,
2939 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002940 }
Mike Stump11289f42009-09-09 15:08:12 +00002941
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002942 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002943 // -- For a non-type template-parameter of type reference to
2944 // object, no conversions apply. The type referred to by the
2945 // reference may be more cv-qualified than the (otherwise
2946 // identical) type of the template-argument. The
2947 // template-parameter is bound directly to the
2948 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00002949 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002950 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002951
Douglas Gregor064fdb22010-04-14 23:11:21 +00002952 if (Arg->getType() == Context.OverloadTy) {
2953 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2954 ParamRefType->getPointeeType(),
2955 true,
2956 FoundResult)) {
2957 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2958 return true;
2959
2960 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2961 ArgType = Arg->getType();
2962 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002963 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002964 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002965
Douglas Gregorb242683d2010-04-01 18:32:35 +00002966 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2967 ParamType,
2968 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002969 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002970
2971 // -- For a non-type template-parameter of type pointer to data
2972 // member, qualification conversions (4.4) are applied.
2973 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2974
Douglas Gregor1515f762009-02-11 18:22:40 +00002975 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002976 // Types match exactly: nothing more to do here.
2977 } else if (IsQualificationConversion(ArgType, ParamType)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002978 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00002979 } else {
2980 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002981 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002982 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002983 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002984 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002985 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002986 }
2987
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002988 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002989}
2990
2991/// \brief Check a template argument against its corresponding
2992/// template template parameter.
2993///
2994/// This routine implements the semantics of C++ [temp.arg.template].
2995/// It returns true if an error occurred, and false otherwise.
2996bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002997 const TemplateArgumentLoc &Arg) {
2998 TemplateName Name = Arg.getArgument().getAsTemplate();
2999 TemplateDecl *Template = Name.getAsTemplateDecl();
3000 if (!Template) {
3001 // Any dependent template name is fine.
3002 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3003 return false;
3004 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003005
3006 // C++ [temp.arg.template]p1:
3007 // A template-argument for a template template-parameter shall be
3008 // the name of a class template, expressed as id-expression. Only
3009 // primary class templates are considered when matching the
3010 // template template argument with the corresponding parameter;
3011 // partial specializations are not considered even if their
3012 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003013 //
3014 // Note that we also allow template template parameters here, which
3015 // will happen when we are dealing with, e.g., class template
3016 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003017 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003018 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003019 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003020 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003021 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003022 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003023 << Template;
3024 }
3025
3026 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3027 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003028 true,
3029 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003030 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003031}
3032
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003033/// \brief Given a non-type template argument that refers to a
3034/// declaration and the type of its corresponding non-type template
3035/// parameter, produce an expression that properly refers to that
3036/// declaration.
3037Sema::OwningExprResult
3038Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3039 QualType ParamType,
3040 SourceLocation Loc) {
3041 assert(Arg.getKind() == TemplateArgument::Declaration &&
3042 "Only declaration template arguments permitted here");
3043 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3044
3045 if (VD->getDeclContext()->isRecord() &&
3046 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3047 // If the value is a class member, we might have a pointer-to-member.
3048 // Determine whether the non-type template template parameter is of
3049 // pointer-to-member type. If so, we need to build an appropriate
3050 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3051 // would refer to the member itself.
3052 if (ParamType->isMemberPointerType()) {
3053 QualType ClassType
3054 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3055 NestedNameSpecifier *Qualifier
3056 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3057 CXXScopeSpec SS;
3058 SS.setScopeRep(Qualifier);
3059 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3060 VD->getType().getNonReferenceType(),
3061 Loc,
3062 &SS);
3063 if (RefExpr.isInvalid())
3064 return ExprError();
3065
3066 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003067
3068 // We might need to perform a trailing qualification conversion, since
3069 // the element type on the parameter could be more qualified than the
3070 // element type in the expression we constructed.
3071 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3072 ParamType.getUnqualifiedType())) {
3073 Expr *RefE = RefExpr.takeAs<Expr>();
3074 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3075 CastExpr::CK_NoOp);
3076 RefExpr = Owned(RefE);
3077 }
3078
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003079 assert(!RefExpr.isInvalid() &&
3080 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003081 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003082 return move(RefExpr);
3083 }
3084 }
3085
3086 QualType T = VD->getType().getNonReferenceType();
3087 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003088 // When the non-type template parameter is a pointer, take the
3089 // address of the declaration.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003090 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3091 if (RefExpr.isInvalid())
3092 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003093
3094 if (T->isFunctionType() || T->isArrayType()) {
3095 // Decay functions and arrays.
3096 Expr *RefE = (Expr *)RefExpr.get();
3097 DefaultFunctionArrayConversion(RefE);
3098 if (RefE != RefExpr.get()) {
3099 RefExpr.release();
3100 RefExpr = Owned(RefE);
3101 }
3102
3103 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003104 }
3105
Douglas Gregorb242683d2010-04-01 18:32:35 +00003106 // Take the address of everything else
3107 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003108 }
3109
3110 // If the non-type template parameter has reference type, qualify the
3111 // resulting declaration reference with the extra qualifiers on the
3112 // type that the reference refers to.
3113 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3114 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3115
3116 return BuildDeclRefExpr(VD, T, Loc);
3117}
3118
3119/// \brief Construct a new expression that refers to the given
3120/// integral template argument with the given source-location
3121/// information.
3122///
3123/// This routine takes care of the mapping from an integral template
3124/// argument (which may have any integral type) to the appropriate
3125/// literal value.
3126Sema::OwningExprResult
3127Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3128 SourceLocation Loc) {
3129 assert(Arg.getKind() == TemplateArgument::Integral &&
3130 "Operation is only value for integral template arguments");
3131 QualType T = Arg.getIntegralType();
3132 if (T->isCharType() || T->isWideCharType())
3133 return Owned(new (Context) CharacterLiteral(
3134 Arg.getAsIntegral()->getZExtValue(),
3135 T->isWideCharType(),
3136 T,
3137 Loc));
3138 if (T->isBooleanType())
3139 return Owned(new (Context) CXXBoolLiteralExpr(
3140 Arg.getAsIntegral()->getBoolValue(),
3141 T,
3142 Loc));
3143
3144 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3145}
3146
3147
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003148/// \brief Determine whether the given template parameter lists are
3149/// equivalent.
3150///
Mike Stump11289f42009-09-09 15:08:12 +00003151/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003152/// source code as part of a new template declaration.
3153///
3154/// \param Old The old template parameter list, typically found via
3155/// name lookup of the template declared with this template parameter
3156/// list.
3157///
3158/// \param Complain If true, this routine will produce a diagnostic if
3159/// the template parameter lists are not equivalent.
3160///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003161/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003162///
3163/// \param TemplateArgLoc If this source location is valid, then we
3164/// are actually checking the template parameter list of a template
3165/// argument (New) against the template parameter list of its
3166/// corresponding template template parameter (Old). We produce
3167/// slightly different diagnostics in this scenario.
3168///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003169/// \returns True if the template parameter lists are equal, false
3170/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003171bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003172Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3173 TemplateParameterList *Old,
3174 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003175 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003176 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003177 if (Old->size() != New->size()) {
3178 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003179 unsigned NextDiag = diag::err_template_param_list_different_arity;
3180 if (TemplateArgLoc.isValid()) {
3181 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3182 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003183 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003184 Diag(New->getTemplateLoc(), NextDiag)
3185 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003186 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003187 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003188 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003189 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003190 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3191 }
3192
3193 return false;
3194 }
3195
3196 for (TemplateParameterList::iterator OldParm = Old->begin(),
3197 OldParmEnd = Old->end(), NewParm = New->begin();
3198 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3199 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003200 if (Complain) {
3201 unsigned NextDiag = diag::err_template_param_different_kind;
3202 if (TemplateArgLoc.isValid()) {
3203 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3204 NextDiag = diag::note_template_param_different_kind;
3205 }
3206 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003207 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003208 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003209 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003210 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003211 return false;
3212 }
3213
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003214 if (TemplateTypeParmDecl *OldTTP
3215 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3216 // Template type parameters are equivalent if either both are template
3217 // type parameter packs or neither are (since we know we're at the same
3218 // index).
3219 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3220 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3221 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3222 // allow one to match a template parameter pack in the template
3223 // parameter list of a template template parameter to one or more
3224 // template parameters in the template parameter list of the
3225 // corresponding template template argument.
3226 if (Complain) {
3227 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3228 if (TemplateArgLoc.isValid()) {
3229 Diag(TemplateArgLoc,
3230 diag::err_template_arg_template_params_mismatch);
3231 NextDiag = diag::note_template_parameter_pack_non_pack;
3232 }
3233 Diag(NewTTP->getLocation(), NextDiag)
3234 << 0 << NewTTP->isParameterPack();
3235 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3236 << 0 << OldTTP->isParameterPack();
3237 }
3238 return false;
3239 }
Mike Stump11289f42009-09-09 15:08:12 +00003240 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003241 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3242 // The types of non-type template parameters must agree.
3243 NonTypeTemplateParmDecl *NewNTTP
3244 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003245
3246 // If we are matching a template template argument to a template
3247 // template parameter and one of the non-type template parameter types
3248 // is dependent, then we must wait until template instantiation time
3249 // to actually compare the arguments.
3250 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3251 (OldNTTP->getType()->isDependentType() ||
3252 NewNTTP->getType()->isDependentType()))
3253 continue;
3254
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003255 if (Context.getCanonicalType(OldNTTP->getType()) !=
3256 Context.getCanonicalType(NewNTTP->getType())) {
3257 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003258 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3259 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003260 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003261 diag::err_template_arg_template_params_mismatch);
3262 NextDiag = diag::note_template_nontype_parm_different_type;
3263 }
3264 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003265 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003266 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003267 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003268 diag::note_template_nontype_parm_prev_declaration)
3269 << OldNTTP->getType();
3270 }
3271 return false;
3272 }
3273 } else {
3274 // The template parameter lists of template template
3275 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003276 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003277 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003278 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003279 = cast<TemplateTemplateParmDecl>(*OldParm);
3280 TemplateTemplateParmDecl *NewTTP
3281 = cast<TemplateTemplateParmDecl>(*NewParm);
3282 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3283 OldTTP->getTemplateParameters(),
3284 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003285 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003286 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003287 return false;
3288 }
3289 }
3290
3291 return true;
3292}
3293
3294/// \brief Check whether a template can be declared within this scope.
3295///
3296/// If the template declaration is valid in this scope, returns
3297/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003298bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003299Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003300 // Find the nearest enclosing declaration scope.
3301 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3302 (S->getFlags() & Scope::TemplateParamScope) != 0)
3303 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003304
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003305 // C++ [temp]p2:
3306 // A template-declaration can appear only as a namespace scope or
3307 // class scope declaration.
3308 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003309 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3310 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003311 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003312 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003313
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003314 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003315 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003316
3317 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3318 return false;
3319
Mike Stump11289f42009-09-09 15:08:12 +00003320 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003321 diag::err_template_outside_namespace_or_class_scope)
3322 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003323}
Douglas Gregor67a65642009-02-17 23:15:12 +00003324
Douglas Gregor54888652009-10-07 00:13:32 +00003325/// \brief Determine what kind of template specialization the given declaration
3326/// is.
3327static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3328 if (!D)
3329 return TSK_Undeclared;
3330
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003331 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3332 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003333 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3334 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003335 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3336 return Var->getTemplateSpecializationKind();
3337
Douglas Gregor54888652009-10-07 00:13:32 +00003338 return TSK_Undeclared;
3339}
3340
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003341/// \brief Check whether a specialization is well-formed in the current
3342/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003343///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003344/// This routine determines whether a template specialization can be declared
3345/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003346///
3347/// \param S the semantic analysis object for which this check is being
3348/// performed.
3349///
3350/// \param Specialized the entity being specialized or instantiated, which
3351/// may be a kind of template (class template, function template, etc.) or
3352/// a member of a class template (member function, static data member,
3353/// member class).
3354///
3355/// \param PrevDecl the previous declaration of this entity, if any.
3356///
3357/// \param Loc the location of the explicit specialization or instantiation of
3358/// this entity.
3359///
3360/// \param IsPartialSpecialization whether this is a partial specialization of
3361/// a class template.
3362///
Douglas Gregor54888652009-10-07 00:13:32 +00003363/// \returns true if there was an error that we cannot recover from, false
3364/// otherwise.
3365static bool CheckTemplateSpecializationScope(Sema &S,
3366 NamedDecl *Specialized,
3367 NamedDecl *PrevDecl,
3368 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003369 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003370 // Keep these "kind" numbers in sync with the %select statements in the
3371 // various diagnostics emitted by this routine.
3372 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003373 bool isTemplateSpecialization = false;
3374 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003375 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003376 isTemplateSpecialization = true;
3377 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003378 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003379 isTemplateSpecialization = true;
3380 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003381 EntityKind = 3;
3382 else if (isa<VarDecl>(Specialized))
3383 EntityKind = 4;
3384 else if (isa<RecordDecl>(Specialized))
3385 EntityKind = 5;
3386 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003387 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3388 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003389 return true;
3390 }
3391
Douglas Gregorf47b9112009-02-25 22:02:03 +00003392 // C++ [temp.expl.spec]p2:
3393 // An explicit specialization shall be declared in the namespace
3394 // of which the template is a member, or, for member templates, in
3395 // the namespace of which the enclosing class or enclosing class
3396 // template is a member. An explicit specialization of a member
3397 // function, member class or static data member of a class
3398 // template shall be declared in the namespace of which the class
3399 // template is a member. Such a declaration may also be a
3400 // definition. If the declaration is not a definition, the
3401 // specialization may be defined later in the name- space in which
3402 // the explicit specialization was declared, or in a namespace
3403 // that encloses the one in which the explicit specialization was
3404 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003405 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3406 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003407 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003408 return true;
3409 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003410
Douglas Gregor40fb7442009-10-07 17:30:37 +00003411 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3412 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003413 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003414 return true;
3415 }
3416
Douglas Gregore4b05162009-10-07 17:21:34 +00003417 // C++ [temp.class.spec]p6:
3418 // A class template partial specialization may be declared or redeclared
3419 // in any namespace scope in which its definition may be defined (14.5.1
3420 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003421 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003422 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003423 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003424 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003425 if ((!PrevDecl ||
3426 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3427 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3428 // There is no prior declaration of this entity, so this
3429 // specialization must be in the same context as the template
3430 // itself.
3431 if (!DC->Equals(SpecializedContext)) {
3432 if (isa<TranslationUnitDecl>(SpecializedContext))
3433 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3434 << EntityKind << Specialized;
3435 else if (isa<NamespaceDecl>(SpecializedContext))
3436 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3437 << EntityKind << Specialized
3438 << cast<NamedDecl>(SpecializedContext);
3439
3440 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3441 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003442 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003443 }
Douglas Gregor54888652009-10-07 00:13:32 +00003444
3445 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003446 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003447 // Note that HandleDeclarator() performs this check for explicit
3448 // specializations of function templates, static data members, and member
3449 // functions, so we skip the check here for those kinds of entities.
3450 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003451 // Should we refactor that check, so that it occurs later?
3452 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003453 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3454 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003455 if (isa<TranslationUnitDecl>(SpecializedContext))
3456 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3457 << EntityKind << Specialized;
3458 else if (isa<NamespaceDecl>(SpecializedContext))
3459 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3460 << EntityKind << Specialized
3461 << cast<NamedDecl>(SpecializedContext);
3462
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003463 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003464 }
Douglas Gregor54888652009-10-07 00:13:32 +00003465
3466 // FIXME: check for specialization-after-instantiation errors and such.
3467
Douglas Gregorf47b9112009-02-25 22:02:03 +00003468 return false;
3469}
Douglas Gregor54888652009-10-07 00:13:32 +00003470
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003471/// \brief Check the non-type template arguments of a class template
3472/// partial specialization according to C++ [temp.class.spec]p9.
3473///
Douglas Gregor09a30232009-06-12 22:08:06 +00003474/// \param TemplateParams the template parameters of the primary class
3475/// template.
3476///
3477/// \param TemplateArg the template arguments of the class template
3478/// partial specialization.
3479///
3480/// \param MirrorsPrimaryTemplate will be set true if the class
3481/// template partial specialization arguments are identical to the
3482/// implicit template arguments of the primary template. This is not
3483/// necessarily an error (C++0x), and it is left to the caller to diagnose
3484/// this condition when it is an error.
3485///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003486/// \returns true if there was an error, false otherwise.
3487bool Sema::CheckClassTemplatePartialSpecializationArgs(
3488 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003489 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003490 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003491 // FIXME: the interface to this function will have to change to
3492 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003493 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003494
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003495 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003496
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003497 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003498 // Determine whether the template argument list of the partial
3499 // specialization is identical to the implicit argument list of
3500 // the primary template. The caller may need to diagnostic this as
3501 // an error per C++ [temp.class.spec]p9b3.
3502 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003503 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003504 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3505 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003506 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003507 MirrorsPrimaryTemplate = false;
3508 } else if (TemplateTemplateParmDecl *TTP
3509 = dyn_cast<TemplateTemplateParmDecl>(
3510 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003511 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003512 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003513 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003514 if (!ArgDecl ||
3515 ArgDecl->getIndex() != TTP->getIndex() ||
3516 ArgDecl->getDepth() != TTP->getDepth())
3517 MirrorsPrimaryTemplate = false;
3518 }
3519 }
3520
Mike Stump11289f42009-09-09 15:08:12 +00003521 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003522 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003523 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003524 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003525 }
3526
Anders Carlsson40c1d492009-06-13 18:20:51 +00003527 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003528 if (!ArgExpr) {
3529 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003530 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003531 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003532
3533 // C++ [temp.class.spec]p8:
3534 // A non-type argument is non-specialized if it is the name of a
3535 // non-type parameter. All other non-type arguments are
3536 // specialized.
3537 //
3538 // Below, we check the two conditions that only apply to
3539 // specialized non-type arguments, so skip any non-specialized
3540 // arguments.
3541 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003542 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003543 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003544 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003545 (Param->getIndex() != NTTP->getIndex() ||
3546 Param->getDepth() != NTTP->getDepth()))
3547 MirrorsPrimaryTemplate = false;
3548
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003549 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003550 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003551
3552 // C++ [temp.class.spec]p9:
3553 // Within the argument list of a class template partial
3554 // specialization, the following restrictions apply:
3555 // -- A partially specialized non-type argument expression
3556 // shall not involve a template parameter of the partial
3557 // specialization except when the argument expression is a
3558 // simple identifier.
3559 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003560 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003561 diag::err_dependent_non_type_arg_in_partial_spec)
3562 << ArgExpr->getSourceRange();
3563 return true;
3564 }
3565
3566 // -- The type of a template parameter corresponding to a
3567 // specialized non-type argument shall not be dependent on a
3568 // parameter of the specialization.
3569 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003570 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003571 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3572 << Param->getType()
3573 << ArgExpr->getSourceRange();
3574 Diag(Param->getLocation(), diag::note_template_param_here);
3575 return true;
3576 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003577
3578 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003579 }
3580
3581 return false;
3582}
3583
Douglas Gregorc854c662010-02-26 06:03:23 +00003584/// \brief Retrieve the previous declaration of the given declaration.
3585static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3586 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3587 return VD->getPreviousDeclaration();
3588 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3589 return FD->getPreviousDeclaration();
3590 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3591 return TD->getPreviousDeclaration();
3592 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3593 return TD->getPreviousDeclaration();
3594 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3595 return FTD->getPreviousDeclaration();
3596 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3597 return CTD->getPreviousDeclaration();
3598 return 0;
3599}
3600
Douglas Gregorc08f4892009-03-25 00:13:59 +00003601Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003602Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3603 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003604 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003605 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003606 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003607 SourceLocation TemplateNameLoc,
3608 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003609 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003610 SourceLocation RAngleLoc,
3611 AttributeList *Attr,
3612 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003613 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003614
Douglas Gregor67a65642009-02-17 23:15:12 +00003615 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003616 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003617 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003618 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3619
3620 if (!ClassTemplate) {
3621 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3622 << (Name.getAsTemplateDecl() &&
3623 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3624 return true;
3625 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003626
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003627 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003628 bool isPartialSpecialization = false;
3629
Douglas Gregorf47b9112009-02-25 22:02:03 +00003630 // Check the validity of the template headers that introduce this
3631 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003632 // FIXME: We probably shouldn't complain about these headers for
3633 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003634 bool Invalid = false;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003635 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003636 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3637 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003638 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003639 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003640 isExplicitSpecialization,
3641 Invalid);
3642 if (Invalid)
3643 return true;
3644
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003645 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3646 if (TemplateParams)
3647 --NumMatchedTemplateParamLists;
3648
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003649 if (TemplateParams && TemplateParams->size() > 0) {
3650 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003651
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003652 // C++ [temp.class.spec]p10:
3653 // The template parameter list of a specialization shall not
3654 // contain default template argument values.
3655 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3656 Decl *Param = TemplateParams->getParam(I);
3657 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3658 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003659 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003660 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003661 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003662 }
3663 } else if (NonTypeTemplateParmDecl *NTTP
3664 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3665 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003666 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003667 diag::err_default_arg_in_partial_spec)
3668 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003669 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003670 }
3671 } else {
3672 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003673 if (TTP->hasDefaultArgument()) {
3674 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003675 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003676 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003677 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003678 }
3679 }
3680 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003681 } else if (TemplateParams) {
3682 if (TUK == TUK_Friend)
3683 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003684 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003685 SourceRange(TemplateParams->getTemplateLoc(),
3686 TemplateParams->getRAngleLoc()))
3687 << SourceRange(LAngleLoc, RAngleLoc);
3688 else
3689 isExplicitSpecialization = true;
3690 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003691 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003692 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003693 isExplicitSpecialization = true;
3694 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003695
Douglas Gregor67a65642009-02-17 23:15:12 +00003696 // Check that the specialization uses the same tag kind as the
3697 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003698 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3699 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003700 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003701 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003702 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003703 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003704 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003705 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003706 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003707 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003708 diag::note_previous_use);
3709 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3710 }
3711
Douglas Gregorc40290e2009-03-09 23:48:35 +00003712 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003713 TemplateArgumentListInfo TemplateArgs;
3714 TemplateArgs.setLAngleLoc(LAngleLoc);
3715 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003716 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003717
Douglas Gregor67a65642009-02-17 23:15:12 +00003718 // Check that the template argument list is well-formed for this
3719 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003720 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3721 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003722 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3723 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003724 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003725
Mike Stump11289f42009-09-09 15:08:12 +00003726 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003727 ClassTemplate->getTemplateParameters()->size()) &&
3728 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003729
Douglas Gregor2373c592009-05-31 09:31:02 +00003730 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003731 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00003732 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003733 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003734 if (CheckClassTemplatePartialSpecializationArgs(
3735 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003736 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003737 return true;
3738
Douglas Gregor09a30232009-06-12 22:08:06 +00003739 if (MirrorsPrimaryTemplate) {
3740 // C++ [temp.class.spec]p9b3:
3741 //
Mike Stump11289f42009-09-09 15:08:12 +00003742 // -- The argument list of the specialization shall not be identical
3743 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003744 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003745 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003746 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003747 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003748 ClassTemplate->getIdentifier(),
3749 TemplateNameLoc,
3750 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003751 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003752 AS_none);
3753 }
3754
Douglas Gregor2208a292009-09-26 20:57:03 +00003755 // FIXME: Diagnose friend partial specializations
3756
Douglas Gregor92354b62010-02-09 00:37:32 +00003757 if (!Name.isDependent() &&
3758 !TemplateSpecializationType::anyDependentTemplateArguments(
3759 TemplateArgs.getArgumentArray(),
3760 TemplateArgs.size())) {
3761 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3762 << ClassTemplate->getDeclName();
3763 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00003764 }
3765 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003766
Douglas Gregor67a65642009-02-17 23:15:12 +00003767 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003768 ClassTemplateSpecializationDecl *PrevDecl = 0;
3769
3770 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003771 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00003772 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003773 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
3774 Converted.flatSize(),
3775 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003776 else
3777 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003778 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
3779 Converted.flatSize(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003780
3781 ClassTemplateSpecializationDecl *Specialization = 0;
3782
Douglas Gregorf47b9112009-02-25 22:02:03 +00003783 // Check whether we can declare a class template specialization in
3784 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003785 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003786 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003787 TemplateNameLoc,
3788 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003789 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003790
Douglas Gregor15301382009-07-30 17:40:51 +00003791 // The canonical type
3792 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003793 if (PrevDecl &&
3794 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003795 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003796 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003797 // arguments was referenced but not declared, or we're only
3798 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003799 // declaration node as our own, updating its source location to
3800 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003801 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003802 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003803 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003804 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003805 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003806 // Build the canonical type that describes the converted template
3807 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003808 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3809 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003810 Converted.getFlatArguments(),
3811 Converted.flatSize());
3812
Douglas Gregor2373c592009-05-31 09:31:02 +00003813 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003814 ClassTemplatePartialSpecializationDecl *PrevPartial
3815 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00003816 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003817 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump11289f42009-09-09 15:08:12 +00003818 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00003819 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00003820 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003821 TemplateNameLoc,
3822 TemplateParams,
3823 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003824 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003825 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003826 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00003827 PrevPartial,
3828 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00003829 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003830 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003831 Partial->setTemplateParameterListsInfo(Context,
3832 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003833 (TemplateParameterList**) TemplateParameterLists.release());
3834 }
Douglas Gregor2373c592009-05-31 09:31:02 +00003835
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003836 if (!PrevPartial)
3837 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003838 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003839
Douglas Gregor21610382009-10-29 00:04:11 +00003840 // If we are providing an explicit specialization of a member class
3841 // template specialization, make a note of that.
3842 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3843 PrevPartial->setMemberSpecialization();
3844
Douglas Gregor91772d12009-06-13 00:26:55 +00003845 // Check that all of the template parameters of the class template
3846 // partial specialization are deducible from the template
3847 // arguments. If not, this class template partial specialization
3848 // will never be used.
3849 llvm::SmallVector<bool, 8> DeducibleParams;
3850 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003851 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003852 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003853 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003854 unsigned NumNonDeducible = 0;
3855 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3856 if (!DeducibleParams[I])
3857 ++NumNonDeducible;
3858
3859 if (NumNonDeducible) {
3860 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3861 << (NumNonDeducible > 1)
3862 << SourceRange(TemplateNameLoc, RAngleLoc);
3863 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3864 if (!DeducibleParams[I]) {
3865 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3866 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003867 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003868 diag::note_partial_spec_unused_parameter)
3869 << Param->getDeclName();
3870 else
Mike Stump11289f42009-09-09 15:08:12 +00003871 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003872 diag::note_partial_spec_unused_parameter)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003873 << "<anonymous>";
Douglas Gregor91772d12009-06-13 00:26:55 +00003874 }
3875 }
3876 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003877 } else {
3878 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003879 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003880 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00003881 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00003882 ClassTemplate->getDeclContext(),
3883 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003884 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003885 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003886 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003887 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003888 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003889 Specialization->setTemplateParameterListsInfo(Context,
3890 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003891 (TemplateParameterList**) TemplateParameterLists.release());
3892 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003893
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003894 if (!PrevDecl)
3895 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00003896
3897 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003898 }
3899
Douglas Gregor06db9f52009-10-12 20:18:28 +00003900 // C++ [temp.expl.spec]p6:
3901 // If a template, a member template or the member of a class template is
3902 // explicitly specialized then that specialization shall be declared
3903 // before the first use of that specialization that would cause an implicit
3904 // instantiation to take place, in every translation unit in which such a
3905 // use occurs; no diagnostic is required.
3906 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003907 bool Okay = false;
3908 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3909 // Is there any previous explicit specialization declaration?
3910 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3911 Okay = true;
3912 break;
3913 }
3914 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003915
Douglas Gregorc854c662010-02-26 06:03:23 +00003916 if (!Okay) {
3917 SourceRange Range(TemplateNameLoc, RAngleLoc);
3918 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3919 << Context.getTypeDeclType(Specialization) << Range;
3920
3921 Diag(PrevDecl->getPointOfInstantiation(),
3922 diag::note_instantiation_required_here)
3923 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003924 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003925 return true;
3926 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003927 }
3928
Douglas Gregor2208a292009-09-26 20:57:03 +00003929 // If this is not a friend, note that this is an explicit specialization.
3930 if (TUK != TUK_Friend)
3931 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003932
3933 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003934 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003935 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003936 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003937 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003938 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003939 Diag(Def->getLocation(), diag::note_previous_definition);
3940 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003941 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003942 }
3943 }
3944
Douglas Gregord56a91e2009-02-26 22:19:44 +00003945 // Build the fully-sugared type for this class template
3946 // specialization as the user wrote in the specialization
3947 // itself. This means that we'll pretty-print the type retrieved
3948 // from the specialization's declaration the way that the user
3949 // actually wrote the specialization, rather than formatting the
3950 // name based on the "canonical" representation used to store the
3951 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003952 TypeSourceInfo *WrittenTy
3953 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3954 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00003955 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003956 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregord890b732010-07-06 18:33:12 +00003957 if (TemplateParams)
3958 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnara8075c852010-06-12 07:44:57 +00003959 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00003960 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003961
Douglas Gregor1e249f82009-02-25 22:18:32 +00003962 // C++ [temp.expl.spec]p9:
3963 // A template explicit specialization is in the scope of the
3964 // namespace in which the template was defined.
3965 //
3966 // We actually implement this paragraph where we set the semantic
3967 // context (in the creation of the ClassTemplateSpecializationDecl),
3968 // but we also maintain the lexical context where the actual
3969 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003970 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003971
Douglas Gregor67a65642009-02-17 23:15:12 +00003972 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003973 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003974 Specialization->startDefinition();
3975
Douglas Gregor2208a292009-09-26 20:57:03 +00003976 if (TUK == TUK_Friend) {
3977 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3978 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00003979 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00003980 /*FIXME:*/KWLoc);
3981 Friend->setAccess(AS_public);
3982 CurContext->addDecl(Friend);
3983 } else {
3984 // Add the specialization into its lexical context, so that it can
3985 // be seen when iterating through the list of declarations in that
3986 // context. However, specializations are not found by name lookup.
3987 CurContext->addDecl(Specialization);
3988 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003989 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003990}
Douglas Gregor333489b2009-03-27 23:10:48 +00003991
Mike Stump11289f42009-09-09 15:08:12 +00003992Sema::DeclPtrTy
3993Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003994 MultiTemplateParamsArg TemplateParameterLists,
3995 Declarator &D) {
3996 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3997}
3998
Mike Stump11289f42009-09-09 15:08:12 +00003999Sema::DeclPtrTy
4000Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004001 MultiTemplateParamsArg TemplateParameterLists,
4002 Declarator &D) {
4003 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4004 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4005 "Not a function declarator!");
4006 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004007
Douglas Gregor17a7c122009-06-24 00:54:41 +00004008 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004009 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004010 }
Mike Stump11289f42009-09-09 15:08:12 +00004011
Douglas Gregor17a7c122009-06-24 00:54:41 +00004012 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004013
4014 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004015 move(TemplateParameterLists),
4016 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004017 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00004018 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00004019 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004020 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00004021 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
4022 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004023 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00004024}
4025
John McCall4f7ced62010-02-11 01:33:53 +00004026/// \brief Strips various properties off an implicit instantiation
4027/// that has just been explicitly specialized.
4028static void StripImplicitInstantiation(NamedDecl *D) {
4029 D->invalidateAttrs();
4030
4031 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4032 FD->setInlineSpecified(false);
4033 }
4034}
4035
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004036/// \brief Diagnose cases where we have an explicit template specialization
4037/// before/after an explicit template instantiation, producing diagnostics
4038/// for those cases where they are required and determining whether the
4039/// new specialization/instantiation will have any effect.
4040///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004041/// \param NewLoc the location of the new explicit specialization or
4042/// instantiation.
4043///
4044/// \param NewTSK the kind of the new explicit specialization or instantiation.
4045///
4046/// \param PrevDecl the previous declaration of the entity.
4047///
4048/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4049///
4050/// \param PrevPointOfInstantiation if valid, indicates where the previus
4051/// declaration was instantiated (either implicitly or explicitly).
4052///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004053/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004054/// specialization or instantiation has no effect and should be ignored.
4055///
4056/// \returns true if there was an error that should prevent the introduction of
4057/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004058bool
4059Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4060 TemplateSpecializationKind NewTSK,
4061 NamedDecl *PrevDecl,
4062 TemplateSpecializationKind PrevTSK,
4063 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004064 bool &HasNoEffect) {
4065 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004066
4067 switch (NewTSK) {
4068 case TSK_Undeclared:
4069 case TSK_ImplicitInstantiation:
4070 assert(false && "Don't check implicit instantiations here");
4071 return false;
4072
4073 case TSK_ExplicitSpecialization:
4074 switch (PrevTSK) {
4075 case TSK_Undeclared:
4076 case TSK_ExplicitSpecialization:
4077 // Okay, we're just specializing something that is either already
4078 // explicitly specialized or has merely been mentioned without any
4079 // instantiation.
4080 return false;
4081
4082 case TSK_ImplicitInstantiation:
4083 if (PrevPointOfInstantiation.isInvalid()) {
4084 // The declaration itself has not actually been instantiated, so it is
4085 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004086 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004087 return false;
4088 }
4089 // Fall through
4090
4091 case TSK_ExplicitInstantiationDeclaration:
4092 case TSK_ExplicitInstantiationDefinition:
4093 assert((PrevTSK == TSK_ImplicitInstantiation ||
4094 PrevPointOfInstantiation.isValid()) &&
4095 "Explicit instantiation without point of instantiation?");
4096
4097 // C++ [temp.expl.spec]p6:
4098 // If a template, a member template or the member of a class template
4099 // is explicitly specialized then that specialization shall be declared
4100 // before the first use of that specialization that would cause an
4101 // implicit instantiation to take place, in every translation unit in
4102 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004103 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4104 // Is there any previous explicit specialization declaration?
4105 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4106 return false;
4107 }
4108
Douglas Gregor1d957a32009-10-27 18:42:08 +00004109 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004110 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004111 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004112 << (PrevTSK != TSK_ImplicitInstantiation);
4113
4114 return true;
4115 }
4116 break;
4117
4118 case TSK_ExplicitInstantiationDeclaration:
4119 switch (PrevTSK) {
4120 case TSK_ExplicitInstantiationDeclaration:
4121 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004122 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004123 return false;
4124
4125 case TSK_Undeclared:
4126 case TSK_ImplicitInstantiation:
4127 // We're explicitly instantiating something that may have already been
4128 // implicitly instantiated; that's fine.
4129 return false;
4130
4131 case TSK_ExplicitSpecialization:
4132 // C++0x [temp.explicit]p4:
4133 // For a given set of template parameters, if an explicit instantiation
4134 // of a template appears after a declaration of an explicit
4135 // specialization for that template, the explicit instantiation has no
4136 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004137 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004138 return false;
4139
4140 case TSK_ExplicitInstantiationDefinition:
4141 // C++0x [temp.explicit]p10:
4142 // If an entity is the subject of both an explicit instantiation
4143 // declaration and an explicit instantiation definition in the same
4144 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004145 Diag(NewLoc,
4146 diag::err_explicit_instantiation_declaration_after_definition);
4147 Diag(PrevPointOfInstantiation,
4148 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004149 assert(PrevPointOfInstantiation.isValid() &&
4150 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004151 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004152 return false;
4153 }
4154 break;
4155
4156 case TSK_ExplicitInstantiationDefinition:
4157 switch (PrevTSK) {
4158 case TSK_Undeclared:
4159 case TSK_ImplicitInstantiation:
4160 // We're explicitly instantiating something that may have already been
4161 // implicitly instantiated; that's fine.
4162 return false;
4163
4164 case TSK_ExplicitSpecialization:
4165 // C++ DR 259, C++0x [temp.explicit]p4:
4166 // For a given set of template parameters, if an explicit
4167 // instantiation of a template appears after a declaration of
4168 // an explicit specialization for that template, the explicit
4169 // instantiation has no effect.
4170 //
4171 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004172 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004173 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004174 if (!getLangOptions().CPlusPlus0x) {
4175 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004176 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004177 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004178 diag::note_previous_template_specialization);
4179 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004180 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004181 return false;
4182
4183 case TSK_ExplicitInstantiationDeclaration:
4184 // We're explicity instantiating a definition for something for which we
4185 // were previously asked to suppress instantiations. That's fine.
4186 return false;
4187
4188 case TSK_ExplicitInstantiationDefinition:
4189 // C++0x [temp.spec]p5:
4190 // For a given template and a given set of template-arguments,
4191 // - an explicit instantiation definition shall appear at most once
4192 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004193 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004194 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004195 Diag(PrevPointOfInstantiation,
4196 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004197 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004198 return false;
4199 }
4200 break;
4201 }
4202
4203 assert(false && "Missing specialization/instantiation case?");
4204
4205 return false;
4206}
4207
John McCallb9c78482010-04-08 09:05:18 +00004208/// \brief Perform semantic analysis for the given dependent function
4209/// template specialization. The only possible way to get a dependent
4210/// function template specialization is with a friend declaration,
4211/// like so:
4212///
4213/// template <class T> void foo(T);
4214/// template <class T> class A {
4215/// friend void foo<>(T);
4216/// };
4217///
4218/// There really isn't any useful analysis we can do here, so we
4219/// just store the information.
4220bool
4221Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4222 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4223 LookupResult &Previous) {
4224 // Remove anything from Previous that isn't a function template in
4225 // the correct context.
4226 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4227 LookupResult::Filter F = Previous.makeFilter();
4228 while (F.hasNext()) {
4229 NamedDecl *D = F.next()->getUnderlyingDecl();
4230 if (!isa<FunctionTemplateDecl>(D) ||
4231 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4232 F.erase();
4233 }
4234 F.done();
4235
4236 // Should this be diagnosed here?
4237 if (Previous.empty()) return true;
4238
4239 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4240 ExplicitTemplateArgs);
4241 return false;
4242}
4243
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004244/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004245/// specialization.
4246///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004247/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004248/// explicit function template specialization. On successful completion,
4249/// the function declaration \p FD will become a function template
4250/// specialization.
4251///
4252/// \param FD the function declaration, which will be updated to become a
4253/// function template specialization.
4254///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004255/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4256/// if any. Note that this may be valid info even when 0 arguments are
4257/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4258/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004259///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004260/// \param PrevDecl the set of declarations that may be specialized by
4261/// this function specialization.
4262bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004263Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004264 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004265 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004266 // The set of function template specializations that could match this
4267 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004268 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004269
4270 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004271 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4272 I != E; ++I) {
4273 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4274 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004275 // Only consider templates found within the same semantic lookup scope as
4276 // FD.
4277 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4278 continue;
4279
4280 // C++ [temp.expl.spec]p11:
4281 // A trailing template-argument can be left unspecified in the
4282 // template-id naming an explicit function template specialization
4283 // provided it can be deduced from the function argument type.
4284 // Perform template argument deduction to determine whether we may be
4285 // specializing this template.
4286 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004287 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004288 FunctionDecl *Specialization = 0;
4289 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004290 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004291 FD->getType(),
4292 Specialization,
4293 Info)) {
4294 // FIXME: Template argument deduction failed; record why it failed, so
4295 // that we can provide nifty diagnostics.
4296 (void)TDK;
4297 continue;
4298 }
4299
4300 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004301 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004302 }
4303 }
4304
Douglas Gregor5de279c2009-09-26 03:41:46 +00004305 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004306 UnresolvedSetIterator Result
4307 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4308 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004309 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004310 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004311 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004312 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004313 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004314 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004315 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004316
4317 // Ignore access information; it doesn't figure into redeclaration checking.
4318 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004319 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004320
4321 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004322 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004323
4324 // If this is a friend declaration, then we're not really declaring
4325 // an explicit specialization.
4326 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004327
Douglas Gregor54888652009-10-07 00:13:32 +00004328 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004329 if (!isFriend &&
4330 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004331 Specialization->getPrimaryTemplate(),
4332 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004333 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004334 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004335
4336 // C++ [temp.expl.spec]p6:
4337 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004338 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004339 // before the first use of that specialization that would cause an implicit
4340 // instantiation to take place, in every translation unit in which such a
4341 // use occurs; no diagnostic is required.
4342 FunctionTemplateSpecializationInfo *SpecInfo
4343 = Specialization->getTemplateSpecializationInfo();
4344 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004345
Abramo Bagnara8075c852010-06-12 07:44:57 +00004346 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004347 if (!isFriend &&
4348 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004349 TSK_ExplicitSpecialization,
4350 Specialization,
4351 SpecInfo->getTemplateSpecializationKind(),
4352 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004353 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004354 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004355
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004356 // Mark the prior declaration as an explicit specialization, so that later
4357 // clients know that this is an explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004358 if (!isFriend)
4359 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004360
4361 // Turn the given function declaration into a function template
4362 // specialization, with the template arguments from the previous
4363 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004364 // Take copies of (semantic and syntactic) template argument lists.
4365 const TemplateArgumentList* TemplArgs = new (Context)
4366 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4367 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4368 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004369 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004370 TemplArgs, /*InsertPos=*/0,
4371 SpecInfo->getTemplateSpecializationKind(),
4372 TemplArgsAsWritten);
4373
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004374 // The "previous declaration" for this function template specialization is
4375 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004376 Previous.clear();
4377 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004378 return false;
4379}
4380
Douglas Gregor86d142a2009-10-08 07:24:58 +00004381/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004382/// specialization.
4383///
4384/// This routine performs all of the semantic analysis required for an
4385/// explicit member function specialization. On successful completion,
4386/// the function declaration \p FD will become a member function
4387/// specialization.
4388///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004389/// \param Member the member declaration, which will be updated to become a
4390/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004391///
John McCall1f82f242009-11-18 22:49:29 +00004392/// \param Previous the set of declarations, one of which may be specialized
4393/// by this function specialization; the set will be modified to contain the
4394/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004395bool
John McCall1f82f242009-11-18 22:49:29 +00004396Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004397 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004398
Douglas Gregor86d142a2009-10-08 07:24:58 +00004399 // Try to find the member we are instantiating.
4400 NamedDecl *Instantiation = 0;
4401 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004402 MemberSpecializationInfo *MSInfo = 0;
4403
John McCall1f82f242009-11-18 22:49:29 +00004404 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004405 // Nowhere to look anyway.
4406 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004407 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4408 I != E; ++I) {
4409 NamedDecl *D = (*I)->getUnderlyingDecl();
4410 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004411 if (Context.hasSameType(Function->getType(), Method->getType())) {
4412 Instantiation = Method;
4413 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004414 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004415 break;
4416 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004417 }
4418 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004419 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004420 VarDecl *PrevVar;
4421 if (Previous.isSingleResult() &&
4422 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004423 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004424 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004425 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004426 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004427 }
4428 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004429 CXXRecordDecl *PrevRecord;
4430 if (Previous.isSingleResult() &&
4431 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4432 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004433 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004434 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004435 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004436 }
4437
4438 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004439 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004440 // specializations are always out-of-line, the caller will complain about
4441 // this mismatch later.
4442 return false;
4443 }
John McCalle820e5e2010-04-13 20:37:33 +00004444
4445 // If this is a friend, just bail out here before we start turning
4446 // things into explicit specializations.
4447 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4448 // Preserve instantiation information.
4449 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4450 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4451 cast<CXXMethodDecl>(InstantiatedFrom),
4452 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4453 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4454 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4455 cast<CXXRecordDecl>(InstantiatedFrom),
4456 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4457 }
4458
4459 Previous.clear();
4460 Previous.addDecl(Instantiation);
4461 return false;
4462 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004463
Douglas Gregor86d142a2009-10-08 07:24:58 +00004464 // Make sure that this is a specialization of a member.
4465 if (!InstantiatedFrom) {
4466 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4467 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004468 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4469 return true;
4470 }
4471
Douglas Gregor06db9f52009-10-12 20:18:28 +00004472 // C++ [temp.expl.spec]p6:
4473 // If a template, a member template or the member of a class template is
4474 // explicitly specialized then that spe- cialization shall be declared
4475 // before the first use of that specialization that would cause an implicit
4476 // instantiation to take place, in every translation unit in which such a
4477 // use occurs; no diagnostic is required.
4478 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004479
Abramo Bagnara8075c852010-06-12 07:44:57 +00004480 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004481 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4482 TSK_ExplicitSpecialization,
4483 Instantiation,
4484 MSInfo->getTemplateSpecializationKind(),
4485 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004486 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004487 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004488
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004489 // Check the scope of this explicit specialization.
4490 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004491 InstantiatedFrom,
4492 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004493 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004494 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004495
Douglas Gregor86d142a2009-10-08 07:24:58 +00004496 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004497 // the original declaration to note that it is an explicit specialization
4498 // (if it was previously an implicit instantiation). This latter step
4499 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004500 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004501 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4502 if (InstantiationFunction->getTemplateSpecializationKind() ==
4503 TSK_ImplicitInstantiation) {
4504 InstantiationFunction->setTemplateSpecializationKind(
4505 TSK_ExplicitSpecialization);
4506 InstantiationFunction->setLocation(Member->getLocation());
4507 }
4508
Douglas Gregor86d142a2009-10-08 07:24:58 +00004509 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4510 cast<CXXMethodDecl>(InstantiatedFrom),
4511 TSK_ExplicitSpecialization);
4512 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004513 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4514 if (InstantiationVar->getTemplateSpecializationKind() ==
4515 TSK_ImplicitInstantiation) {
4516 InstantiationVar->setTemplateSpecializationKind(
4517 TSK_ExplicitSpecialization);
4518 InstantiationVar->setLocation(Member->getLocation());
4519 }
4520
Douglas Gregor86d142a2009-10-08 07:24:58 +00004521 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4522 cast<VarDecl>(InstantiatedFrom),
4523 TSK_ExplicitSpecialization);
4524 } else {
4525 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004526 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4527 if (InstantiationClass->getTemplateSpecializationKind() ==
4528 TSK_ImplicitInstantiation) {
4529 InstantiationClass->setTemplateSpecializationKind(
4530 TSK_ExplicitSpecialization);
4531 InstantiationClass->setLocation(Member->getLocation());
4532 }
4533
Douglas Gregor86d142a2009-10-08 07:24:58 +00004534 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004535 cast<CXXRecordDecl>(InstantiatedFrom),
4536 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004537 }
4538
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004539 // Save the caller the trouble of having to figure out which declaration
4540 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004541 Previous.clear();
4542 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004543 return false;
4544}
4545
Douglas Gregore47f5a72009-10-14 23:41:34 +00004546/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004547///
4548/// \returns true if a serious error occurs, false otherwise.
4549static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004550 SourceLocation InstLoc,
4551 bool WasQualifiedName) {
4552 DeclContext *ExpectedContext
4553 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4554 DeclContext *CurContext = S.CurContext->getLookupContext();
4555
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004556 if (CurContext->isRecord()) {
4557 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4558 << D;
4559 return true;
4560 }
4561
Douglas Gregore47f5a72009-10-14 23:41:34 +00004562 // C++0x [temp.explicit]p2:
4563 // An explicit instantiation shall appear in an enclosing namespace of its
4564 // template.
4565 //
4566 // This is DR275, which we do not retroactively apply to C++98/03.
4567 if (S.getLangOptions().CPlusPlus0x &&
4568 !CurContext->Encloses(ExpectedContext)) {
4569 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004570 S.Diag(InstLoc,
4571 S.getLangOptions().CPlusPlus0x?
4572 diag::err_explicit_instantiation_out_of_scope
4573 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004574 << D << NS;
4575 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004576 S.Diag(InstLoc,
4577 S.getLangOptions().CPlusPlus0x?
4578 diag::err_explicit_instantiation_must_be_global
4579 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004580 << D;
4581 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004582 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004583 }
4584
4585 // C++0x [temp.explicit]p2:
4586 // If the name declared in the explicit instantiation is an unqualified
4587 // name, the explicit instantiation shall appear in the namespace where
4588 // its template is declared or, if that namespace is inline (7.3.1), any
4589 // namespace from its enclosing namespace set.
4590 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004591 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004592
4593 if (CurContext->Equals(ExpectedContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004594 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004595
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004596 S.Diag(InstLoc,
4597 S.getLangOptions().CPlusPlus0x?
4598 diag::err_explicit_instantiation_unqualified_wrong_namespace
4599 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004600 << D << ExpectedContext;
4601 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004602 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004603}
4604
4605/// \brief Determine whether the given scope specifier has a template-id in it.
4606static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4607 if (!SS.isSet())
4608 return false;
4609
4610 // C++0x [temp.explicit]p2:
4611 // If the explicit instantiation is for a member function, a member class
4612 // or a static data member of a class template specialization, the name of
4613 // the class template specialization in the qualified-id for the member
4614 // name shall be a simple-template-id.
4615 //
4616 // C++98 has the same restriction, just worded differently.
4617 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4618 NNS; NNS = NNS->getPrefix())
4619 if (Type *T = NNS->getAsType())
4620 if (isa<TemplateSpecializationType>(T))
4621 return true;
4622
4623 return false;
4624}
4625
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004626// Explicit instantiation of a class template specialization
Douglas Gregora1f49972009-05-13 00:25:59 +00004627Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004628Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004629 SourceLocation ExternLoc,
4630 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004631 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004632 SourceLocation KWLoc,
4633 const CXXScopeSpec &SS,
4634 TemplateTy TemplateD,
4635 SourceLocation TemplateNameLoc,
4636 SourceLocation LAngleLoc,
4637 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004638 SourceLocation RAngleLoc,
4639 AttributeList *Attr) {
4640 // Find the class template we're specializing
4641 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004642 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004643 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4644
4645 // Check that the specialization uses the same tag kind as the
4646 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004647 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4648 assert(Kind != TTK_Enum &&
4649 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004650 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004651 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004652 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004653 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004654 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004655 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004656 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004657 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004658 diag::note_previous_use);
4659 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4660 }
4661
Douglas Gregore47f5a72009-10-14 23:41:34 +00004662 // C++0x [temp.explicit]p2:
4663 // There are two forms of explicit instantiation: an explicit instantiation
4664 // definition and an explicit instantiation declaration. An explicit
4665 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004666 TemplateSpecializationKind TSK
4667 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4668 : TSK_ExplicitInstantiationDeclaration;
4669
Douglas Gregora1f49972009-05-13 00:25:59 +00004670 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004671 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004672 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004673
4674 // Check that the template argument list is well-formed for this
4675 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004676 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4677 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004678 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4679 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004680 return true;
4681
Mike Stump11289f42009-09-09 15:08:12 +00004682 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004683 ClassTemplate->getTemplateParameters()->size()) &&
4684 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004685
Douglas Gregora1f49972009-05-13 00:25:59 +00004686 // Find the class template specialization declaration that
4687 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00004688 void *InsertPos = 0;
4689 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004690 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4691 Converted.flatSize(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004692
Abramo Bagnara8075c852010-06-12 07:44:57 +00004693 TemplateSpecializationKind PrevDecl_TSK
4694 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4695
Douglas Gregor54888652009-10-07 00:13:32 +00004696 // C++0x [temp.explicit]p2:
4697 // [...] An explicit instantiation shall appear in an enclosing
4698 // namespace of its template. [...]
4699 //
4700 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004701 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4702 SS.isSet()))
4703 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004704
Douglas Gregora1f49972009-05-13 00:25:59 +00004705 ClassTemplateSpecializationDecl *Specialization = 0;
4706
Douglas Gregor0681a352009-11-25 06:01:46 +00004707 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004708 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004709 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00004710 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004711 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004712 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004713 HasNoEffect))
Douglas Gregora1f49972009-05-13 00:25:59 +00004714 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004715
Abramo Bagnara8075c852010-06-12 07:44:57 +00004716 // Even though HasNoEffect == true means that this explicit instantiation
4717 // has no effect on semantics, we go on to put its syntax in the AST.
4718
4719 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4720 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004721 // Since the only prior class template specialization with these
4722 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00004723 // declaration node as our own, updating the source location
4724 // for the template name to reflect our new declaration.
4725 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004726 Specialization = PrevDecl;
4727 Specialization->setLocation(TemplateNameLoc);
4728 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004729 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004730 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004731 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004732
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004733 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004734 // Create a new class template specialization declaration node for
4735 // this explicit specialization.
4736 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004737 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004738 ClassTemplate->getDeclContext(),
4739 TemplateNameLoc,
4740 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004741 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004742 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004743
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004744 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00004745 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004746 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004747 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004748 }
4749
4750 // Build the fully-sugared type for this explicit instantiation as
4751 // the user wrote in the explicit instantiation itself. This means
4752 // that we'll pretty-print the type retrieved from the
4753 // specialization's declaration the way that the user actually wrote
4754 // the explicit instantiation, rather than formatting the name based
4755 // on the "canonical" representation used to store the template
4756 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004757 TypeSourceInfo *WrittenTy
4758 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4759 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004760 Context.getTypeDeclType(Specialization));
4761 Specialization->setTypeAsWritten(WrittenTy);
4762 TemplateArgsIn.release();
4763
Abramo Bagnara8075c852010-06-12 07:44:57 +00004764 // Set source locations for keywords.
4765 Specialization->setExternLoc(ExternLoc);
4766 Specialization->setTemplateKeywordLoc(TemplateLoc);
4767
4768 // Add the explicit instantiation into its lexical context. However,
4769 // since explicit instantiations are never found by name lookup, we
4770 // just put it into the declaration context directly.
4771 Specialization->setLexicalDeclContext(CurContext);
4772 CurContext->addDecl(Specialization);
4773
4774 // Syntax is now OK, so return if it has no other effect on semantics.
4775 if (HasNoEffect) {
4776 // Set the template specialization kind.
4777 Specialization->setTemplateSpecializationKind(TSK);
4778 return DeclPtrTy::make(Specialization);
Douglas Gregor0681a352009-11-25 06:01:46 +00004779 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004780
4781 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004782 // A definition of a class template or class member template
4783 // shall be in scope at the point of the explicit instantiation of
4784 // the class template or class member template.
4785 //
4786 // This check comes when we actually try to perform the
4787 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004788 ClassTemplateSpecializationDecl *Def
4789 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004790 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004791 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004792 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004793 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00004794 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004795 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4796 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004797
Douglas Gregor1d957a32009-10-27 18:42:08 +00004798 // Instantiate the members of this class template specialization.
4799 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004800 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004801 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004802 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4803
4804 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4805 // TSK_ExplicitInstantiationDefinition
4806 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4807 TSK == TSK_ExplicitInstantiationDefinition)
4808 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004809
Douglas Gregor12e49d32009-10-15 22:53:21 +00004810 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004811 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004812
Abramo Bagnara8075c852010-06-12 07:44:57 +00004813 // Set the template specialization kind.
4814 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004815 return DeclPtrTy::make(Specialization);
4816}
4817
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004818// Explicit instantiation of a member class of a class template.
4819Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004820Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004821 SourceLocation ExternLoc,
4822 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004823 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004824 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004825 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004826 IdentifierInfo *Name,
4827 SourceLocation NameLoc,
4828 AttributeList *Attr) {
4829
Douglas Gregord6ab8742009-05-28 23:31:59 +00004830 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004831 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004832 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004833 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004834 MultiTemplateParamsArg(*this, 0, 0),
4835 Owned, IsDependent);
4836 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4837
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004838 if (!TagD)
4839 return true;
4840
4841 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4842 if (Tag->isEnum()) {
4843 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4844 << Context.getTypeDeclType(Tag);
4845 return true;
4846 }
4847
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004848 if (Tag->isInvalidDecl())
4849 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004850
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004851 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4852 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4853 if (!Pattern) {
4854 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4855 << Context.getTypeDeclType(Record);
4856 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4857 return true;
4858 }
4859
Douglas Gregore47f5a72009-10-14 23:41:34 +00004860 // C++0x [temp.explicit]p2:
4861 // If the explicit instantiation is for a class or member class, the
4862 // elaborated-type-specifier in the declaration shall include a
4863 // simple-template-id.
4864 //
4865 // C++98 has the same restriction, just worded differently.
4866 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00004867 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004868 << Record << SS.getRange();
4869
4870 // C++0x [temp.explicit]p2:
4871 // There are two forms of explicit instantiation: an explicit instantiation
4872 // definition and an explicit instantiation declaration. An explicit
4873 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004874 TemplateSpecializationKind TSK
4875 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4876 : TSK_ExplicitInstantiationDeclaration;
4877
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004878 // C++0x [temp.explicit]p2:
4879 // [...] An explicit instantiation shall appear in an enclosing
4880 // namespace of its template. [...]
4881 //
4882 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004883 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004884
4885 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004886 CXXRecordDecl *PrevDecl
4887 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004888 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004889 PrevDecl = Record;
4890 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004891 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00004892 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004893 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004894 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004895 PrevDecl,
4896 MSInfo->getTemplateSpecializationKind(),
4897 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004898 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004899 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004900 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004901 return TagD;
4902 }
4903
Douglas Gregor12e49d32009-10-15 22:53:21 +00004904 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004905 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004906 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004907 // C++ [temp.explicit]p3:
4908 // A definition of a member class of a class template shall be in scope
4909 // at the point of an explicit instantiation of the member class.
4910 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004911 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004912 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004913 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4914 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004915 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4916 << Pattern;
4917 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004918 } else {
4919 if (InstantiateClass(NameLoc, Record, Def,
4920 getTemplateInstantiationArgs(Record),
4921 TSK))
4922 return true;
4923
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004924 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004925 if (!RecordDef)
4926 return true;
4927 }
4928 }
4929
4930 // Instantiate all of the members of the class.
4931 InstantiateClassMembers(NameLoc, RecordDef,
4932 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004933
Douglas Gregor88d292c2010-05-13 16:44:06 +00004934 if (TSK == TSK_ExplicitInstantiationDefinition)
4935 MarkVTableUsed(NameLoc, RecordDef, true);
4936
Mike Stump87c57ac2009-05-16 07:39:55 +00004937 // FIXME: We don't have any representation for explicit instantiations of
4938 // member classes. Such a representation is not needed for compilation, but it
4939 // should be available for clients that want to see all of the declarations in
4940 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004941 return TagD;
4942}
4943
Douglas Gregor450f00842009-09-25 18:43:00 +00004944Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4945 SourceLocation ExternLoc,
4946 SourceLocation TemplateLoc,
4947 Declarator &D) {
4948 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004949 // TODO: check if/when DNInfo should replace Name.
4950 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4951 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00004952 if (!Name) {
4953 if (!D.isInvalidType())
4954 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4955 diag::err_explicit_instantiation_requires_name)
4956 << D.getDeclSpec().getSourceRange()
4957 << D.getSourceRange();
4958
4959 return true;
4960 }
4961
4962 // The scope passed in may not be a decl scope. Zip up the scope tree until
4963 // we find one that is.
4964 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4965 (S->getFlags() & Scope::TemplateParamScope) != 0)
4966 S = S->getParent();
4967
4968 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00004969 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
4970 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00004971 if (R.isNull())
4972 return true;
4973
4974 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4975 // Cannot explicitly instantiate a typedef.
4976 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4977 << Name;
4978 return true;
4979 }
4980
Douglas Gregor3c74d412009-10-14 20:14:33 +00004981 // C++0x [temp.explicit]p1:
4982 // [...] An explicit instantiation of a function template shall not use the
4983 // inline or constexpr specifiers.
4984 // Presumably, this also applies to member functions of class templates as
4985 // well.
4986 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4987 Diag(D.getDeclSpec().getInlineSpecLoc(),
4988 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00004989 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004990
4991 // FIXME: check for constexpr specifier.
4992
Douglas Gregore47f5a72009-10-14 23:41:34 +00004993 // C++0x [temp.explicit]p2:
4994 // There are two forms of explicit instantiation: an explicit instantiation
4995 // definition and an explicit instantiation declaration. An explicit
4996 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004997 TemplateSpecializationKind TSK
4998 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4999 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005000
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005001 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005002 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005003
5004 if (!R->isFunctionType()) {
5005 // C++ [temp.explicit]p1:
5006 // A [...] static data member of a class template can be explicitly
5007 // instantiated from the member definition associated with its class
5008 // template.
John McCall27b18f82009-11-17 02:14:36 +00005009 if (Previous.isAmbiguous())
5010 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005011
John McCall67c00872009-12-02 08:25:40 +00005012 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005013 if (!Prev || !Prev->isStaticDataMember()) {
5014 // We expect to see a data data member here.
5015 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5016 << Name;
5017 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5018 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005019 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005020 return true;
5021 }
5022
5023 if (!Prev->getInstantiatedFromStaticDataMember()) {
5024 // FIXME: Check for explicit specialization?
5025 Diag(D.getIdentifierLoc(),
5026 diag::err_explicit_instantiation_data_member_not_instantiated)
5027 << Prev;
5028 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5029 // FIXME: Can we provide a note showing where this was declared?
5030 return true;
5031 }
5032
Douglas Gregore47f5a72009-10-14 23:41:34 +00005033 // C++0x [temp.explicit]p2:
5034 // If the explicit instantiation is for a member function, a member class
5035 // or a static data member of a class template specialization, the name of
5036 // the class template specialization in the qualified-id for the member
5037 // name shall be a simple-template-id.
5038 //
5039 // C++98 has the same restriction, just worded differently.
5040 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5041 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005042 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005043 << Prev << D.getCXXScopeSpec().getRange();
5044
5045 // Check the scope of this explicit instantiation.
5046 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5047
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005048 // Verify that it is okay to explicitly instantiate here.
5049 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5050 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005051 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005052 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005053 MSInfo->getTemplateSpecializationKind(),
5054 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005055 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005056 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005057 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005058 return DeclPtrTy();
5059
Douglas Gregor450f00842009-09-25 18:43:00 +00005060 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005061 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005062 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00005063 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5064 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00005065
5066 // FIXME: Create an ExplicitInstantiation node?
5067 return DeclPtrTy();
5068 }
5069
Douglas Gregor0e876e02009-09-25 23:53:26 +00005070 // If the declarator is a template-id, translate the parser's template
5071 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005072 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005073 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005074 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5075 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005076 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5077 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005078 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5079 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005080 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005081 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005082 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005083 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005084 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005085
Douglas Gregor450f00842009-09-25 18:43:00 +00005086 // C++ [temp.explicit]p1:
5087 // A [...] function [...] can be explicitly instantiated from its template.
5088 // A member function [...] of a class template can be explicitly
5089 // instantiated from the member definition associated with its class
5090 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005091 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005092 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5093 P != PEnd; ++P) {
5094 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005095 if (!HasExplicitTemplateArgs) {
5096 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5097 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5098 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005099
John McCall58cc69d2010-01-27 01:50:18 +00005100 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005101 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5102 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005103 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005104 }
5105 }
5106
5107 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5108 if (!FunTmpl)
5109 continue;
5110
John McCallbc077cf2010-02-08 23:07:23 +00005111 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005112 FunctionDecl *Specialization = 0;
5113 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005114 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005115 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005116 R, Specialization, Info)) {
5117 // FIXME: Keep track of almost-matches?
5118 (void)TDK;
5119 continue;
5120 }
5121
John McCall58cc69d2010-01-27 01:50:18 +00005122 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005123 }
5124
5125 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005126 UnresolvedSetIterator Result
5127 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005128 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005129 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5130 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5131 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005132
John McCall58cc69d2010-01-27 01:50:18 +00005133 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005134 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005135
5136 // Ignore access control bits, we don't need them for redeclaration checking.
5137 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005138
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005139 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005140 Diag(D.getIdentifierLoc(),
5141 diag::err_explicit_instantiation_member_function_not_instantiated)
5142 << Specialization
5143 << (Specialization->getTemplateSpecializationKind() ==
5144 TSK_ExplicitSpecialization);
5145 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5146 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005147 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005148
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005149 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005150 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5151 PrevDecl = Specialization;
5152
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005153 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005154 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005155 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005156 PrevDecl,
5157 PrevDecl->getTemplateSpecializationKind(),
5158 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005159 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005160 return true;
5161
5162 // FIXME: We may still want to build some representation of this
5163 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005164 if (HasNoEffect)
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005165 return DeclPtrTy();
5166 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005167
5168 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005169
5170 if (TSK == TSK_ExplicitInstantiationDefinition)
5171 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5172 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005173
Douglas Gregore47f5a72009-10-14 23:41:34 +00005174 // C++0x [temp.explicit]p2:
5175 // If the explicit instantiation is for a member function, a member class
5176 // or a static data member of a class template specialization, the name of
5177 // the class template specialization in the qualified-id for the member
5178 // name shall be a simple-template-id.
5179 //
5180 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005181 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005182 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005183 D.getCXXScopeSpec().isSet() &&
5184 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5185 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005186 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005187 << Specialization << D.getCXXScopeSpec().getRange();
5188
5189 CheckExplicitInstantiationScope(*this,
5190 FunTmpl? (NamedDecl *)FunTmpl
5191 : Specialization->getInstantiatedFromMemberFunction(),
5192 D.getIdentifierLoc(),
5193 D.getCXXScopeSpec().isSet());
5194
Douglas Gregor450f00842009-09-25 18:43:00 +00005195 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5196 return DeclPtrTy();
5197}
5198
Douglas Gregor333489b2009-03-27 23:10:48 +00005199Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005200Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5201 const CXXScopeSpec &SS, IdentifierInfo *Name,
5202 SourceLocation TagLoc, SourceLocation NameLoc) {
5203 // This has to hold, because SS is expected to be defined.
5204 assert(Name && "Expected a name in a dependent tag");
5205
5206 NestedNameSpecifier *NNS
5207 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5208 if (!NNS)
5209 return true;
5210
Abramo Bagnara6150c882010-05-11 21:36:43 +00005211 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005212
Douglas Gregorba41d012010-04-24 16:38:41 +00005213 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5214 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005215 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005216 return true;
5217 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005218
5219 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5220 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
John McCall7f41d982009-09-11 04:59:25 +00005221}
5222
5223Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005224Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5225 const CXXScopeSpec &SS, const IdentifierInfo &II,
5226 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005227 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005228 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5229 if (!NNS)
5230 return true;
5231
Douglas Gregorf7d77712010-06-16 22:31:08 +00005232 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5233 !getLangOptions().CPlusPlus0x)
5234 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5235 << FixItHint::CreateRemoval(TypenameLoc);
5236
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005237 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005238 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005239 if (T.isNull())
5240 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005241
5242 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5243 if (isa<DependentNameType>(T)) {
5244 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005245 TL.setKeywordLoc(TypenameLoc);
5246 TL.setQualifierRange(SS.getRange());
5247 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005248 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005249 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005250 TL.setKeywordLoc(TypenameLoc);
5251 TL.setQualifierRange(SS.getRange());
5252 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005253 }
5254
5255 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor333489b2009-03-27 23:10:48 +00005256}
5257
Douglas Gregordce2b622009-04-01 00:28:59 +00005258Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005259Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5260 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
5261 TypeTy *Ty) {
5262 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5263 !getLangOptions().CPlusPlus0x)
5264 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5265 << FixItHint::CreateRemoval(TypenameLoc);
5266
John McCallf7bcc812010-05-28 23:32:21 +00005267 TypeSourceInfo *InnerTSI = 0;
5268 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCallf7bcc812010-05-28 23:32:21 +00005269
5270 assert(isa<TemplateSpecializationType>(T) &&
5271 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005272
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005273 if (computeDeclContext(SS, false)) {
5274 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005275 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005276 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005277
5278 // Push the inner type, preserving its source locations if possible.
5279 TypeLocBuilder Builder;
5280 if (InnerTSI)
5281 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5282 else
5283 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5284
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005285 /* Note: NNS already embedded in template specialization type T. */
5286 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCallf7bcc812010-05-28 23:32:21 +00005287 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5288 TL.setKeywordLoc(TypenameLoc);
5289 TL.setQualifierRange(SS.getRange());
5290
5291 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCall99b2fe52010-04-29 23:50:39 +00005292 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005293 }
Mike Stump11289f42009-09-09 15:08:12 +00005294
John McCallc392f372010-06-11 00:33:02 +00005295 // TODO: it's really silly that we make a template specialization
5296 // type earlier only to drop it again here.
5297 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5298 DependentTemplateName *DTN =
5299 TST->getTemplateName().getAsDependentTemplateName();
5300 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005301 assert(DTN->getQualifier()
5302 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5303 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5304 DTN->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00005305 DTN->getIdentifier(),
5306 TST->getNumArgs(),
5307 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005308 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005309 DependentTemplateSpecializationTypeLoc TL =
5310 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5311 if (InnerTSI) {
5312 TemplateSpecializationTypeLoc TSTL =
5313 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5314 TL.setLAngleLoc(TSTL.getLAngleLoc());
5315 TL.setRAngleLoc(TSTL.getRAngleLoc());
5316 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5317 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5318 } else {
5319 TL.initializeLocal(SourceLocation());
5320 }
John McCallf7bcc812010-05-28 23:32:21 +00005321 TL.setKeywordLoc(TypenameLoc);
5322 TL.setQualifierRange(SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005323 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00005324}
5325
Douglas Gregor333489b2009-03-27 23:10:48 +00005326/// \brief Build the type that describes a C++ typename specifier,
5327/// e.g., "typename T::type".
5328QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005329Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5330 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005331 SourceLocation KeywordLoc, SourceRange NNSRange,
5332 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005333 CXXScopeSpec SS;
5334 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005335 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005336
John McCall0b66eb32010-05-01 00:40:08 +00005337 DeclContext *Ctx = computeDeclContext(SS);
5338 if (!Ctx) {
5339 // If the nested-name-specifier is dependent and couldn't be
5340 // resolved to a type, build a typename type.
5341 assert(NNS->isDependent());
5342 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005343 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005344
John McCall0b66eb32010-05-01 00:40:08 +00005345 // If the nested-name-specifier refers to the current instantiation,
5346 // the "typename" keyword itself is superfluous. In C++03, the
5347 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5348 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005349 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005350
John McCall0b66eb32010-05-01 00:40:08 +00005351 if (RequireCompleteDeclContext(SS, Ctx))
5352 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005353
5354 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005355 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005356 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005357 unsigned DiagID = 0;
5358 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005359 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005360 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005361 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005362 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005363
5364 case LookupResult::NotFoundInCurrentInstantiation:
5365 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005366 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005367
5368 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005369 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005370 // We found a type. Build an ElaboratedType, since the
5371 // typename-specifier was just sugar.
5372 return Context.getElaboratedType(ETK_Typename, NNS,
5373 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005374 }
5375
5376 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005377 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005378 break;
5379
John McCalle61f2ba2009-11-18 02:36:19 +00005380 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005381 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005382 return QualType();
5383
Douglas Gregor333489b2009-03-27 23:10:48 +00005384 case LookupResult::FoundOverloaded:
5385 DiagID = diag::err_typename_nested_not_type;
5386 Referenced = *Result.begin();
5387 break;
5388
John McCall6538c932009-10-10 05:48:19 +00005389 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005390 return QualType();
5391 }
5392
5393 // If we get here, it's because name lookup did not find a
5394 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005395 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5396 IILoc);
5397 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005398 if (Referenced)
5399 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5400 << Name;
5401 return QualType();
5402}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005403
5404namespace {
5405 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005406 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005407 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005408 SourceLocation Loc;
5409 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005410
Douglas Gregor15acfb92009-08-06 16:20:37 +00005411 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005412 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5413
Mike Stump11289f42009-09-09 15:08:12 +00005414 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005415 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005416 DeclarationName Entity)
5417 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005418 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005419
5420 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005421 /// transformed.
5422 ///
5423 /// For the purposes of type reconstruction, a type has already been
5424 /// transformed if it is NULL or if it is not dependent.
5425 bool AlreadyTransformed(QualType T) {
5426 return T.isNull() || !T->isDependentType();
5427 }
Mike Stump11289f42009-09-09 15:08:12 +00005428
5429 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005430 /// rebuilt.
5431 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005432
Douglas Gregor15acfb92009-08-06 16:20:37 +00005433 /// \brief Returns the name of the entity whose type is being rebuilt.
5434 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005435
Douglas Gregoref6ab412009-10-27 06:26:26 +00005436 /// \brief Sets the "base" location and entity when that
5437 /// information is known based on another transformation.
5438 void setBase(SourceLocation Loc, DeclarationName Entity) {
5439 this->Loc = Loc;
5440 this->Entity = Entity;
5441 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005442 };
5443}
5444
Douglas Gregor15acfb92009-08-06 16:20:37 +00005445/// \brief Rebuilds a type within the context of the current instantiation.
5446///
Mike Stump11289f42009-09-09 15:08:12 +00005447/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005448/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005449/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005450/// partial specialization thereof). This routine will rebuild that type now
5451/// that we have entered the declarator's scope, which may produce different
5452/// canonical types, e.g.,
5453///
5454/// \code
5455/// template<typename T>
5456/// struct X {
5457/// typedef T* pointer;
5458/// pointer data();
5459/// };
5460///
5461/// template<typename T>
5462/// typename X<T>::pointer X<T>::data() { ... }
5463/// \endcode
5464///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005465/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005466/// since we do not know that we can look into X<T> when we parsed the type.
5467/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005468/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005469/// as the canonical type of T*, allowing the return types of the out-of-line
5470/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005471TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5472 SourceLocation Loc,
5473 DeclarationName Name) {
5474 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005475 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005476
Douglas Gregor15acfb92009-08-06 16:20:37 +00005477 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5478 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005479}
Douglas Gregorbe999392009-09-15 16:23:51 +00005480
John McCall99b2fe52010-04-29 23:50:39 +00005481bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5482 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005483
5484 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5485 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5486 DeclarationName());
5487 NestedNameSpecifier *Rebuilt =
5488 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005489 if (!Rebuilt) return true;
5490
5491 SS.setScopeRep(Rebuilt);
5492 return false;
John McCall2408e322010-04-27 00:57:59 +00005493}
5494
Douglas Gregorbe999392009-09-15 16:23:51 +00005495/// \brief Produces a formatted string that describes the binding of
5496/// template parameters to template arguments.
5497std::string
5498Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5499 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005500 // FIXME: For variadic templates, we'll need to get the structured list.
5501 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5502 Args.flat_size());
5503}
5504
5505std::string
5506Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5507 const TemplateArgument *Args,
5508 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005509 std::string Result;
5510
Douglas Gregore62e6a02009-11-11 19:13:48 +00005511 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005512 return Result;
5513
5514 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005515 if (I >= NumArgs)
5516 break;
5517
Douglas Gregorbe999392009-09-15 16:23:51 +00005518 if (I == 0)
5519 Result += "[with ";
5520 else
5521 Result += ", ";
5522
5523 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5524 Result += Id->getName();
5525 } else {
5526 Result += '$';
5527 Result += llvm::utostr(I);
5528 }
5529
5530 Result += " = ";
5531
5532 switch (Args[I].getKind()) {
5533 case TemplateArgument::Null:
5534 Result += "<no value>";
5535 break;
5536
5537 case TemplateArgument::Type: {
5538 std::string TypeStr;
5539 Args[I].getAsType().getAsStringInternal(TypeStr,
5540 Context.PrintingPolicy);
5541 Result += TypeStr;
5542 break;
5543 }
5544
5545 case TemplateArgument::Declaration: {
5546 bool Unnamed = true;
5547 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5548 if (ND->getDeclName()) {
5549 Unnamed = false;
5550 Result += ND->getNameAsString();
5551 }
5552 }
5553
5554 if (Unnamed) {
5555 Result += "<anonymous>";
5556 }
5557 break;
5558 }
5559
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005560 case TemplateArgument::Template: {
5561 std::string Str;
5562 llvm::raw_string_ostream OS(Str);
5563 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5564 Result += OS.str();
5565 break;
5566 }
5567
Douglas Gregorbe999392009-09-15 16:23:51 +00005568 case TemplateArgument::Integral: {
5569 Result += Args[I].getAsIntegral()->toString(10);
5570 break;
5571 }
5572
5573 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005574 // FIXME: This is non-optimal, since we're regurgitating the
5575 // expression we were given.
5576 std::string Str;
5577 {
5578 llvm::raw_string_ostream OS(Str);
5579 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5580 Context.PrintingPolicy);
5581 }
5582 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005583 break;
5584 }
5585
5586 case TemplateArgument::Pack:
5587 // FIXME: Format template argument packs
5588 Result += "<template argument pack>";
5589 break;
5590 }
5591 }
5592
5593 Result += ']';
5594 return Result;
5595}